Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is it save to expose entity ids of data that is in Google Datastore.
For example in my code i have entity with this id:
```
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
@Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
private String id;
```
The id is going to be similar to this: **agptZeERtzaWYvSQadLEgZDdRsUYRs**
Can anyone extract password, application url and any other information from this string? What is the meaning of that string? | That entity ID contains the object id, appliation id, and object class name. It's just an encoded string. Not really any sort of security risk. | You can use the KeyFactory to convert to keytoString, stringToKey as follows URL [Google App Engine](http://code.google.com/appengine/docs/java/datastore/creatinggettinganddeletingdata.html):
the ID that I believe that it was an unique id for the data storage in Google App Engine.
> Key instances can be converted to and
> from the encoded string representation
> using the KeyFactory methods
> keyToString() and stringToKey().
>
> When using encoded key strings, you
> can provide access to an object's
> string or numeric ID with an
> additional fields.
I hope it helps.
Tiger. | Exposing Entity IDs of Google Datastore data | [
"",
"java",
"google-app-engine",
"google-cloud-datastore",
""
] |
How to hide cmd window while running a batch file?
I use the following code to run batch file
```
process = new Process();
process.StartInfo.FileName = batchFilePath;
process.Start();
``` | If proc.StartInfo.UseShellExecute is **false**, then you are launching the process and can use:
```
proc.StartInfo.CreateNoWindow = true;
```
If proc.StartInfo.UseShellExecute is **true**, then the OS is launching the process and you have to provide a "hint" to the process via:
```
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
```
However the called application may ignore this latter request.
If using UseShellExecute = **false**, you might want to consider redirecting standard output/error, to capture any logging produced:
```
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
proc.StartInfo.RedirectStandardError = true;
proc.ErrorDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
```
And have a function like
```
private void ProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data)) // use the output outLine.Data somehow;
}
```
There's a good page covering `CreateNoWindow` this on [an MSDN blog](http://blogs.msdn.com/jmstall/archive/2006/09/28/CreateNoWindow.aspx).
There is also a bug in Windows which may throw a dialog and defeat `CreateNoWindow` if you are passing a username/password. For details
<http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98476>
<http://support.microsoft.com/?kbid=818858> | According to the [Process properties](http://dotnetperls.com/process-start-net), you do have a:
> Property: `CreateNoWindow`
> Notes: Allows you to run a command line program silently.
> It does not flash a console window.
and:
> Property: `WindowStyle`
> Notes: Use this to set windows as hidden.
> The author has used `ProcessWindowStyle.Hidden` often.
As an example!
```
static void LaunchCommandLineApp()
{
// For the example
const string ex1 = "C:\\";
const string ex2 = "C:\\Dir";
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "dcm2jpg.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch
{
// Log error.
}
}
``` | How to hide cmd window while running a batch file? | [
"",
"c#",
"process",
"batch-file",
""
] |
I'm having a hard time using std::string::iterators in C++. This code compiles fine (still not getting correct output, but that's my fault: TODO, fix algorithm) in Dev-C++, and I don't get runtime errors. The error is with Visual Studio Express 2008 C++, where I'm getting an error pointing to < xstring>: "Expression: string iterator not dereferencable," and points to line 112 of the < xstring> file.
My debugging tells me I might be trying to dereference past the end of the sentence input, but I can't see where. Can anyone shed some light?
```
std::string wordWrap(std::string sentence, int width)
{
std::string::iterator it = sentence.begin();
//remember how long next word is
int nextWordLength = 0;
int distanceFromWidth = width;
while (it < sentence.end())
{
while (*it != ' ' && it != sentence.end())
{
nextWordLength++;
distanceFromWidth--;
it++;
}
if (nextWordLength > distanceFromWidth)
{
*it = '\n';
distanceFromWidth = width;
nextWordLength = 0;
}
//skip the space
it++;
}
return sentence;
}
``` | Firstly, use operator!=() on iterators, not operator<():
```
while (it != sentence.end())
```
---
Secondly, this is backwards: `while (*it != ' ' && it != sentence.end())`
You do something with the iterator, than check if the iterator is valid. Rather, you should check if it's valid first:
```
while (it != sentence.end() && *it != ' ')
```
---
Thirdly, you should use ++iterator over iterator++, though this isn't related to your crashing.
---
Fourth, a main issue is here:
```
*it = '\n';
```
Because of the preceeding check, `while (it != sentence.end()`, it's possible to reach that iterator dereference while being at the end. A fix would be to do this:
```
if (it != sentence.end() && nextWordLength > distanceFromWidth)
```
So now if you have reached the end, you stop.
---
After fixing the previous issue, now the only problem is this:
```
//skip the space
++it;
```
This assumes that the character you are skipping is in fact a space. But what about the end of the string? Run this function with this string:
`"a test string " // <- space at end`
And it will succeed; it skips the space, putting the iterator at `end()`, the loop exits and success.
However, without the space it will crash, because you have reached the end, and are skipping past the end. To fix, add a check:
```
//skip the space
if (it != sentence.end())
{
++it;
}
```
---
Resulting in this final code:
```
std::string wordWrap(std::string sentence, int width)
{
std::string::iterator it = sentence.begin();
//remember how long next word is
int nextWordLength = 0;
int distanceFromWidth = width;
while (it != sentence.end())
{
while (it != sentence.end() && *it != ' ')
{
nextWordLength++;
distanceFromWidth--;
++it;
}
if (it != sentence.end() && nextWordLength > distanceFromWidth)
{
*it = '\n';
distanceFromWidth = width;
nextWordLength = 0;
}
//skip the space
if (it != sentence.end())
{
++it;
}
}
return sentence;
}
```
---
You might notice this seems like it has a lot of redundant checks. This can be fixed:
```
std::string wordWrap(std::string sentence, int width)
{
std::string::iterator it = sentence.begin();
//remember how long next word is
int nextWordLength = 0;
int distanceFromWidth = width;
while (it != sentence.end())
{
while (*it != ' ')
{
nextWordLength++;
distanceFromWidth--;
++it;
// check if done
if (it == sentence.end())
{
return sentence;
}
}
if (nextWordLength > distanceFromWidth)
{
*it = '\n';
distanceFromWidth = width;
nextWordLength = 0;
}
//skip the space
++it;
}
return sentence;
}
```
---
Hopefully that helps! | ```
while (*it != ' ' && it != sentence.end())
```
changes to
```
while (it != sentence.end() && *it != ' ')
```
so the second expression isn't evaluated if the first if false.
```
if (nextWordLength > distanceFromWidth)
```
should probably change to
```
if (it == sentence.end())
break;
if (nextWordLength > distanceFromWidth)
``` | Expression: String iterator not dereferencable | [
"",
"c++",
"iterator",
"dereference",
""
] |
is this solution possible in asp.net [dragging picturebox inside winform on runtime](https://stackoverflow.com/questions/1086989/dragging-picturebox-inside-winform-on-runtime)
i just want to be able to move an image around on a webform | The question you referenced is written in windows forms. You can not drag'n drop elements in your web form as in windows forms.
If you want to drag and drop elements in a web application, you should use client side code.
The best option in client side is to use a library, and the best one is [JQuery UI](http://jqueryui.com/demos/draggable/) in my opinion. [In the demo I linked](http://jqueryui.com/demos/draggable/) user can drag a div element. Here is a simple dragging example with a static image and a server-side ASP.NET control :
```
<head runat="server">
<script src="js/jquery-1.3.2.min.js" language="javascript" ></script>
<script src="js/jquery-ui-1.7.2.custom.min.js" language="javascript" ></script>
<script type="text/javascript">
$(function() {
$("#draggable").draggable();
$("#<%= imgServerControl.ClientID %>").draggable();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<!-- Static Draggable Image -->
<img src="ac-dc.jpg" id="draggable" />
<!-- ASP.NET server image control -->
<asp:Image ImageUrl="ac-dc.jpg" ID="imgServerControl" runat="server" />
</form>
</body>
</html>
```
**Note :** To test this code, all you need to do is to download the [JQuery UI](http://jqueryui.com/demos/draggable/) with draggable component [from here](http://jqueryui.com/download) and add it to your script folder. | The point, that Canavar & John Saumders are trying to make, is that you need to understand the distinction between ASP.NET and client side UI code.
Whilst it's true that ASP.NET Webforms do use a certain amount of client-side code to do their work, this is mostly related to communicating UI events to the server-side , so that they can be processed.
If your drag-drop operation results in some server-side data manipulation (And this is highly likely) then you would also need to communicate the appropriate information to the server-side.
The concepts involved are fairly straightforward, but tying them all together can be slighlty tricky - and depends heavily on your underlying webforms and application architecture.
Could you rpvide further explanation of the application functionality, what you'd expect to happen when an image is dragged from one place to another, and if/how you expect the image position to be remembered. | moving image on webpage | [
"",
"c#",
"asp.net",
"vb.net",
"webforms",
""
] |
What's wrong with the following code?
```
Object[] a = new Object[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;
```
The code has the following error at the last line :
> Exception in thread "main" java.lang.ClassCastException:
> [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; | Ross, you can use Arrays.copyof() or Arrays.copyOfRange() too.
```
Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class);
Integer[] integerArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class);
```
Here the reason to hitting an `ClassCastException` is you can't treat an array of `Integer` as an array of `Object`. `Integer[]` is a subtype of `Object[]` but `Object[]` is not a `Integer[]`.
And the following also will not give an `ClassCastException`.
```
Object[] a = new Integer[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;
``` | You can't cast an `Object` array to an `Integer` array. You have to loop through all elements of a and cast each one individually.
```
Object[] a = new Object[1];
Integer b=1;
a[0]=b;
Integer[] c = new Integer[a.length];
for(int i = 0; i < a.length; i++)
{
c[i] = (Integer) a[i];
}
```
Edit: I believe the rationale behind this restriction is that when casting, the JVM wants to ensure type-safety at runtime. Since an array of `Objects` can be anything besides `Integers`, the JVM would have to do what the above code is doing anyway (look at each element individually). The language designers decided they didn't want the JVM to do that (I'm not sure why, but I'm sure it's a good reason).
However, you can cast a subtype array to a supertype array (e.g. `Integer[]` to `Object[]`)! | casting Object array to Integer array error | [
"",
"java",
"casting",
""
] |
If I change a field in a Django model, how can I synchronize it with the database tables? Do I need to do it manually on the database or is there a tool that does helps with the process? | Alas, Django does not support any easy solution to this.
The only thing django will do for you, is restart your database with new tables that match your new models:
```
$ #DON'T DO THIS UNLESS YOU CAN AFFORD TO LOSE ALL YOUR DATA!
$ python PROJECT_DIR/manage.py syncdb
```
the next option is to use the various sql\* options to manage.py to see what django would do to match the current models to the database, then issue your own `ALTER TABLE` commands to make everything work right. Of course this is error prone and difficult.
The real solution is to use a database migration tool, such as [south](http://south.aeracode.org/) to generate migration code.
Here is a [similar question](https://stackoverflow.com/questions/426378/what-is-your-favorite-solution-for-managing-database-migrations-in-django) with discussion about various database migration options for django. | Can't seem to be able to add a comment to the marked answer, probably because I haven't got enough rep (be nice if SO told me so though).
Anyway, just wanted to add that in the answered post, I believe it is wrong about syncdb - syncdb does **not** touch tables once they have been created and have data in them. You should **not** lose data by calling it (otherwise, how could you add new tables for new apps?)
I believe the poster was referring to the reset command instead, which **does** result in data loss - it will drop the table and recreate it and hence it'll have all the latest model changes. | Django Model Sync Table | [
"",
"python",
"database",
"django",
"django-models",
"synchronization",
""
] |
I'm trying to create a simulation for our web Portal and need to add custom HTTP headers. I am to assume the user has already been authenticated and these headers are just for storing user information (ie, "test-header: role=user; oem=blahblah; id=123;").
I've setup a filter to extract the header information but I can't find a way to inject the header information. They don't want it to be stored in cookies and maybe they will want to setup a global filter to include the headers on every page; is it possible to do something like this with the filter interface or through any other methods? | Maybe you can store that information in the session:
```
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author rodrigoap
*
*/
public class UserInfoFilter implements Filter {
/**
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
// TODO
}
/**
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest))
throw new ServletException("Can only process HttpServletRequest");
if (!(response instanceof HttpServletResponse))
throw new ServletException("Can only process HttpServletResponse");
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpRequest.getSession().setAttribute("role", "user");
httpRequest.getSession().setAttribute("id", "123");
filterChain.doFilter(request, response);
}
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
// TODO
}
}
``` | You would need to utilize [HttpServletRequestWrapper](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequestWrapper.html "HttpServletRequestWrapper") and provide your custom headers in when the various getHeader\* methods are called. | Adding custom HTTP headers in java | [
"",
"java",
"http",
"header",
""
] |
How can I get the text value from an elements's child?
Say I have this code on a page:
```
<div class='geshitop'>
[ CODE ] [ <a href="#" onclick="javascript:copy(); return false;">PLAIN-TEXT</a> ]
</div>
<div class='geshimain'>
<pre><div class="text" style="font-family:monospace;">Code goes here...</div></pre>
</div>
```
The function `copy()`:
```
<script type="text/javascript">
function copy() {
var text = this.parent.getElementsByName("text");
var code = text[0].value;
var popup = window.open("", "window", "resizeable,width=400,height=300");
popup.document.write("<textarea name='code' cols='40' rows='15'></textarea>");
popup.code.value = code;
}
```
How would I go about getting that child's data: the `<div class "text">`. How can I get that from the parent?
---
I'm still having problems. If there is two codeboxes on one page, then it does not work. Remember, I am unable to use ID's. It must be classes.
If I was able to use jQuery this would be easy. | Try this:
Change your HTML slightly. The "javascript:" prefix isn't necessary inside an onclick handler. Also, pass a reference of "this" to your copy function:
```
<div class='geshitop'>
[ CODE ] [ <a href="#" onclick="copy(this); return false;">PLAIN-TEXT</a> ]
</div>
<div class='geshimain'>
<pre><div class="text" style="font-family:monospace;">Code goes here...</div></pre>
</div>
```
Having done that, alter your copy function to accept the new parameter. Then you just have to locate the correct node. From the question, I think you are looking for the next <div class="text"> that is a child of the <div class="geshimain"> that is the next sibling of the parent node that contains the link that was clicked. This function should accomplish that:
```
function copy(node) {
node = node.parentNode; // <div class="geshitop">
// Loop over adjacent siblings, looking for the next geshimain.
while (node.nextSibling) {
node = node.nextSibling;
if (node.nodeName === 'DIV' && node.className === 'geshimain') {
break;
}
}
if (!node) {
throw new Error("Could not locate geshimain");
}
// Locate the <div class="text">
node = (function () {
var divs = node.getElementsByTagName('div');
for (var x = 0; x < divs.length; x++) {
if (divs[x].className === 'text') {
return divs[x];
}
}
return null;
}());
if (!node) {
throw new Error("Could not locate text");
}
node =
'<textarea name="code" cols="40" rows="15">' + node.innerHTML + "</textarea>";
popup = window.open("", "window", "resizeable,width=400,height=300");
popup.document.write(node);
popup.document.close();
}
```
Good luck! | Get a reference to the node you want to retrieve text from and try:
```
someNode.firstChild.nodeValue
```
When you have a node like this:
```
<span>Here is some text</span>
```
You're actually looking at two nodes, a span node which has a text node child. In DOM, that text node child's nodeValue is "Here is some text" | Javascript - Get child's text value | [
"",
"javascript",
"html",
"dom",
""
] |
How to get the file names inside a directory using PHP?
I couldn't find the relevant command using Google, so I hope that this question will help those who are asking along the similar lines. | There's a lot of ways. The older way is [`scandir`](http://www.php.net/scandir) but [`DirectoryIterator`](http://www.php.net/manual/en/class.directoryiterator.php) is probably the best way.
There's also [`readdir`](http://www.php.net/readdir) (to be used with [`opendir`](http://www.php.net/manual/en/function.opendir.php)) and [`glob`](http://www.php.net/glob).
Here are some examples on how to use each one to print all the files in the current directory:
### `DirectoryIterator` usage: (recommended)
```
foreach (new DirectoryIterator('.') as $file) {
if($file->isDot()) continue;
print $file->getFilename() . '<br>';
}
```
### `scandir` usage:
```
$files = scandir('.');
foreach($files as $file) {
if($file == '.' || $file == '..') continue;
print $file . '<br>';
}
```
### `opendir` and `readdir` usage:
```
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if($file == '.' || $file == '..') continue;
print $file . '<br>';
}
closedir($handle);
}
```
### `glob` usage:
```
foreach (glob("*") as $file) {
if($file == '.' || $file == '..') continue;
print $file . '<br>';
}
```
As mentioned in the comments, `glob` is nice because the asterisk I used there can actually be used to do matches on the files, so `glob('*.txt')` would get you all the text files in the folder and `glob('image_*')` would get you all files that start with image\_ | The [Paolo Bergantino's answer](https://stackoverflow.com/users/16417/paolo-bergantino) was fine but is now outdated!
Please consider the below official ways to get the Files inside a directory.
---
## [`FilesystemIterator`](http://php.net/manual/class.filesystemiterator.php)
`FilesystemIterator` has many new features compared to its ancestor `DirectoryIterator` as for instance the possibility to avoid the statement `if($file->isDot()) continue;`. See also the question [Difference between `DirectoryIterator` and `FilesystemIterator`](https://stackoverflow.com/questions/12532064).
```
$it = new FilesystemIterator(__DIR__);
foreach ($it as $fileinfo) {
echo $fileinfo->getFilename() , PHP_EOL;
}
```
---
## [`RecursiveDirectoryIterator`](http://php.net/manual/class.recursivedirectoryiterator.php)
This snippet lists PHP files in all sub-directories.
```
$dir = new RecursiveDirectoryIterator(__DIR__);
$flat = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($flat, '/\.php$/i');
foreach($files as $file) {
echo $file , PHP_EOL;
}
```
See also the [Wrikken's answer](https://stackoverflow.com/a/3321905/938111). | Get the files inside a directory | [
"",
"php",
""
] |
Am I right in assuming that adding/removing elements to an std::map does not effect the other elements (ie cause them to be relocated in memory) and so that the following is safe:
I looked at various sites with info on the container but only found out about the cases where iterators are invalidated, which I already know...
```
std::map<std::string,std::string> map;
PopulateMap(map);
std::string &a= map["x"];
AddMoreData(map);
RemoveRandomKeysExceptX(map);
map["x"] = "foo";
std::cout << a << " " << map["x"] << std::endl;//prints "foo foo"
a = "bar";
std::cout << a << " " << map["x"] << std::endl;//prints "bar bar"
```
I tested some similar code on VC9, which seems to work however that doesn't mean I didn't just get lucky or that it doesn't vary across compilers. | The Standard is clear on this in `23.1.2/8` about associative containers
> The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements. | > Map has the important property that inserting a new element into a map does not invalidate iterators that point to existing elements.
> quote taken from [sgi docs](http://www.sgi.com/tech/stl/Map.html).
If the iterators are guaranteed not to change then the values they point at also cannot change.
naveen previously had an answer that was similar to this. Unless there is a mistake in my logic what you are doing is safe.
Edit 2:
See point 3 in [sgi docs](http://www.sgi.com/tech/stl/Map.html#3) to see how getting a value from operator [] is the same as getting the value from an iterator. | C++ Storing references to values in std::map | [
"",
"c++",
"reference",
"stdmap",
""
] |
If I have a string that contains a url (for examples sake, we'll call it $url) such as;
```
$url = "Here is a funny site http://www.tunyurl.com/34934";
```
How do i remove the URL from the string?
Difficulty is, urls might also show up without the http://, such as ;
```
$url = "Here is another funny site www.tinyurl.com/55555";
```
There is no HTML present. How would i start a search if http or www exists, then remove the text/numbers/symbols until the first space? | I re-read the question, here is a function that would work as intended:
```
function cleaner($url) {
$U = explode(' ',$url);
$W =array();
foreach ($U as $k => $u) {
if (stristr($u,'http') || (count(explode('.',$u)) > 1)) {
unset($U[$k]);
return cleaner( implode(' ',$U));
}
}
return implode(' ',$U);
}
$url = "Here is another funny site www.tinyurl.com/55555 and http://www.tinyurl.com/55555 and img.hostingsite.com/badpic.jpg";
echo "Cleaned: " . cleaner($url);
```
Edit #2/#3 (I must be bored). Here is a version that verifies there is a TLD within the URL:
```
function containsTLD($string) {
preg_match(
"/(AC($|\/)|\.AD($|\/)|\.AE($|\/)|\.AERO($|\/)|\.AF($|\/)|\.AG($|\/)|\.AI($|\/)|\.AL($|\/)|\.AM($|\/)|\.AN($|\/)|\.AO($|\/)|\.AQ($|\/)|\.AR($|\/)|\.ARPA($|\/)|\.AS($|\/)|\.ASIA($|\/)|\.AT($|\/)|\.AU($|\/)|\.AW($|\/)|\.AX($|\/)|\.AZ($|\/)|\.BA($|\/)|\.BB($|\/)|\.BD($|\/)|\.BE($|\/)|\.BF($|\/)|\.BG($|\/)|\.BH($|\/)|\.BI($|\/)|\.BIZ($|\/)|\.BJ($|\/)|\.BM($|\/)|\.BN($|\/)|\.BO($|\/)|\.BR($|\/)|\.BS($|\/)|\.BT($|\/)|\.BV($|\/)|\.BW($|\/)|\.BY($|\/)|\.BZ($|\/)|\.CA($|\/)|\.CAT($|\/)|\.CC($|\/)|\.CD($|\/)|\.CF($|\/)|\.CG($|\/)|\.CH($|\/)|\.CI($|\/)|\.CK($|\/)|\.CL($|\/)|\.CM($|\/)|\.CN($|\/)|\.CO($|\/)|\.COM($|\/)|\.COOP($|\/)|\.CR($|\/)|\.CU($|\/)|\.CV($|\/)|\.CX($|\/)|\.CY($|\/)|\.CZ($|\/)|\.DE($|\/)|\.DJ($|\/)|\.DK($|\/)|\.DM($|\/)|\.DO($|\/)|\.DZ($|\/)|\.EC($|\/)|\.EDU($|\/)|\.EE($|\/)|\.EG($|\/)|\.ER($|\/)|\.ES($|\/)|\.ET($|\/)|\.EU($|\/)|\.FI($|\/)|\.FJ($|\/)|\.FK($|\/)|\.FM($|\/)|\.FO($|\/)|\.FR($|\/)|\.GA($|\/)|\.GB($|\/)|\.GD($|\/)|\.GE($|\/)|\.GF($|\/)|\.GG($|\/)|\.GH($|\/)|\.GI($|\/)|\.GL($|\/)|\.GM($|\/)|\.GN($|\/)|\.GOV($|\/)|\.GP($|\/)|\.GQ($|\/)|\.GR($|\/)|\.GS($|\/)|\.GT($|\/)|\.GU($|\/)|\.GW($|\/)|\.GY($|\/)|\.HK($|\/)|\.HM($|\/)|\.HN($|\/)|\.HR($|\/)|\.HT($|\/)|\.HU($|\/)|\.ID($|\/)|\.IE($|\/)|\.IL($|\/)|\.IM($|\/)|\.IN($|\/)|\.INFO($|\/)|\.INT($|\/)|\.IO($|\/)|\.IQ($|\/)|\.IR($|\/)|\.IS($|\/)|\.IT($|\/)|\.JE($|\/)|\.JM($|\/)|\.JO($|\/)|\.JOBS($|\/)|\.JP($|\/)|\.KE($|\/)|\.KG($|\/)|\.KH($|\/)|\.KI($|\/)|\.KM($|\/)|\.KN($|\/)|\.KP($|\/)|\.KR($|\/)|\.KW($|\/)|\.KY($|\/)|\.KZ($|\/)|\.LA($|\/)|\.LB($|\/)|\.LC($|\/)|\.LI($|\/)|\.LK($|\/)|\.LR($|\/)|\.LS($|\/)|\.LT($|\/)|\.LU($|\/)|\.LV($|\/)|\.LY($|\/)|\.MA($|\/)|\.MC($|\/)|\.MD($|\/)|\.ME($|\/)|\.MG($|\/)|\.MH($|\/)|\.MIL($|\/)|\.MK($|\/)|\.ML($|\/)|\.MM($|\/)|\.MN($|\/)|\.MO($|\/)|\.MOBI($|\/)|\.MP($|\/)|\.MQ($|\/)|\.MR($|\/)|\.MS($|\/)|\.MT($|\/)|\.MU($|\/)|\.MUSEUM($|\/)|\.MV($|\/)|\.MW($|\/)|\.MX($|\/)|\.MY($|\/)|\.MZ($|\/)|\.NA($|\/)|\.NAME($|\/)|\.NC($|\/)|\.NE($|\/)|\.NET($|\/)|\.NF($|\/)|\.NG($|\/)|\.NI($|\/)|\.NL($|\/)|\.NO($|\/)|\.NP($|\/)|\.NR($|\/)|\.NU($|\/)|\.NZ($|\/)|\.OM($|\/)|\.ORG($|\/)|\.PA($|\/)|\.PE($|\/)|\.PF($|\/)|\.PG($|\/)|\.PH($|\/)|\.PK($|\/)|\.PL($|\/)|\.PM($|\/)|\.PN($|\/)|\.PR($|\/)|\.PRO($|\/)|\.PS($|\/)|\.PT($|\/)|\.PW($|\/)|\.PY($|\/)|\.QA($|\/)|\.RE($|\/)|\.RO($|\/)|\.RS($|\/)|\.RU($|\/)|\.RW($|\/)|\.SA($|\/)|\.SB($|\/)|\.SC($|\/)|\.SD($|\/)|\.SE($|\/)|\.SG($|\/)|\.SH($|\/)|\.SI($|\/)|\.SJ($|\/)|\.SK($|\/)|\.SL($|\/)|\.SM($|\/)|\.SN($|\/)|\.SO($|\/)|\.SR($|\/)|\.ST($|\/)|\.SU($|\/)|\.SV($|\/)|\.SY($|\/)|\.SZ($|\/)|\.TC($|\/)|\.TD($|\/)|\.TEL($|\/)|\.TF($|\/)|\.TG($|\/)|\.TH($|\/)|\.TJ($|\/)|\.TK($|\/)|\.TL($|\/)|\.TM($|\/)|\.TN($|\/)|\.TO($|\/)|\.TP($|\/)|\.TR($|\/)|\.TRAVEL($|\/)|\.TT($|\/)|\.TV($|\/)|\.TW($|\/)|\.TZ($|\/)|\.UA($|\/)|\.UG($|\/)|\.UK($|\/)|\.US($|\/)|\.UY($|\/)|\.UZ($|\/)|\.VA($|\/)|\.VC($|\/)|\.VE($|\/)|\.VG($|\/)|\.VI($|\/)|\.VN($|\/)|\.VU($|\/)|\.WF($|\/)|\.WS($|\/)|\.XN--0ZWM56D($|\/)|\.XN--11B5BS3A9AJ6G($|\/)|\.XN--80AKHBYKNJ4F($|\/)|\.XN--9T4B11YI5A($|\/)|\.XN--DEBA0AD($|\/)|\.XN--G6W251D($|\/)|\.XN--HGBK6AJ7F53BBA($|\/)|\.XN--HLCJ6AYA9ESC7A($|\/)|\.XN--JXALPDLP($|\/)|\.XN--KGBECHTV($|\/)|\.XN--ZCKZAH($|\/)|\.YE($|\/)|\.YT($|\/)|\.YU($|\/)|\.ZA($|\/)|\.ZM($|\/)|\.ZW)/i",
$string,
$M);
$has_tld = (count($M) > 0) ? true : false;
return $has_tld;
}
function cleaner($url) {
$U = explode(' ',$url);
$W =array();
foreach ($U as $k => $u) {
if (stristr($u,".")) { //only preg_match if there is a dot
if (containsTLD($u) === true) {
unset($U[$k]);
return cleaner( implode(' ',$U));
}
}
}
return implode(' ',$U);
}
$url = "Here is another funny site badurl.badone somesite.ca/worse.jpg but this badsite.com www.tinyurl.com/55555 and http://www.tinyurl.com/55555 and img.hostingsite.com/badpic.jpg";
echo "Cleaned: " . cleaner($url);
```
returns:
```
Cleaned: Here is another funny site badurl.badone but this and and
``` | ```
$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);
``` | PHP Remove URL from string | [
"",
"php",
""
] |
In C#, I can use the `throw;` statement to rethrow an exception while preserving the stack trace:
```
try
{
...
}
catch (Exception e)
{
if (e is FooException)
throw;
}
```
Is there something like this in Java (**that doesn't lose the original stack trace**)? | ```
catch (WhateverException e) {
throw e;
}
```
will simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace. | You can also wrap the exception in another one AND keep the original stack trace by passing in the Exception as a Throwable as the cause parameter:
```
try
{
...
}
catch (Exception e)
{
throw new YourOwnException(e);
}
``` | Rethrowing exceptions in Java without losing the stack trace | [
"",
"java",
"exception",
""
] |
I'm working on a legacy system that has uses stored procs, business objects and DTO:s. The business objects and the DTO:s often have the same properties. When calling a method in the service layer that returns a DTO, many transformations are happening. Stored proc -> dataset -> business object -> DTO. If a new property is added, it sometimes happens that a developer forgets to add code that moves it from one layer/object to another.
In some parts of the system I solved this by using AutoMapper which will automatically project properties with the same name.
My question is for the other parts. Can I somehow write a unit test that checks if every property in an object has been set/given a value? That way I could write an integration test that calls our service layer and all the transformations have to be successful for the test to pass.
I guess the solution would involve reflection. | Reflection is one way, but it has its caveats, if you set a property to its default value, you will not pick up on the fact it was set.
You can intercept with a real proxy and then listen on all property changes. [See the code here](http://github.com/SamSaffron/Media-Browser/blob/cfb3afdbec276c3fba2c4ffd73ec8534a3de1c0d/MediaBrowser/Library/Extensions/Interceptor.cs) for a base interceptor you can use. Note interceptors mean you need your object to be MarshalByRefObject which may not be something you want. So the other option is to tell your factory to wrap up the object before it returns it in the test scenario. Something that ninject or many other inversion of control libs will allow you to do. | Yes, reflection would be the way to go.
It's probably best to perform the unit test against some mock objects, so you have a known value to test for. | How do I test that every property in an object has been set/given a value? | [
"",
"c#",
".net",
"integration-testing",
""
] |
Calling TextRenderer.MeasureText as follows:
```
TextRenderer.MeasureText(myControl.Text, myControl.Font);
```
and comparing the result to the size of the control to check if text fits. The results are sometimes incorrect. Have observed the following two issues:
* Often when a Label is set to AutoSize, TextRenderer will report a width that is 1 pixel wider than the auto-sized width of the Control.
* False negative where TextRenderer reports a width smaller than the control's but the text is still cut off. This occurred with "Estación de trabajo" -- not sure if the accent could somehow affect the width calculation?
Is there any way to improve the accuracy of the MeasureText method? Should I be calling one of the overrides that accepts a device context and/or format flags? | > Is there any way to improve the accuracy of the MeasureText method? Should I be calling one of the overrides that accepts a device context and/or format flags?
You have answered your question by yourself. Actually MeasureText based on Win32 DrawTextEx, and this function cannot work without valid device context. So when you call MeasureText override without hdc, it internally create desktop compatible hdc to do measurement.
Of course measurement depends on additional TextFormatFlags. Also keep in mind that Label painting (and measurement) depends on [UseCompatibleTextRendering](http://blogs.msdn.com/jfoscoding/archive/2005/10/13/480632.aspx).
So general conclusion you should use MeasureText for your own code, for example when you then call DrawText with exactly same parameters, in all other cases size returned by MeasureText cannot be treated as precise.
If you need to get expected Label size, you should use [GetPreferredSize](http://msdn.microsoft.com/en-us/library/system.windows.forms.label.getpreferredsize.aspx) method. | I know it's probably no actual anymore. Yet for future readers here is a simple yet accurate method of measuring text in a control:
```
Graphics g=Graphics.FromHwnd(YOUR CONTROL HERE.Handle);
SizeF s=g.MeasureString("YOUR STRING HERE", Font, NULL, NULL, STRING LENGTH HERE, 1)
``` | Accuracy of TextRenderer.MeasureText results | [
"",
"c#",
"winforms",
"textrenderer",
""
] |
I'm trying to track down a memory leak in a java process, using [jmap](http://java.sun.com/javase/6/docs/technotes/tools/share/jmap.html) and [jhat](http://java.sun.com/javase/6/docs/technotes/tools/share/jhat.html). Every time I do this I see those weird notation for specific object types, like `[S` for string arrays and `[C` for Character arrays. I never remember what means what, and it's very hard to google this stuff.
(**EDIT**: to prove my point, it turns out that `[S` is array of short and `[C` is array of char.)
Anyone care to make a table listing all the different class names and what they mean? Or point me to such table?
Specifically I'd like to know what `[Ljava.lang.Object;` means. | You'll find the complete list documented under [Class.getName()](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getName()):
> If this class object represents a
> reference type that is not an array
> type then the binary name of the class
> is returned, as specified by the *Java™
> Language Specification, Second
> Edition*.
>
> If this class object represents a
> primitive type or void, then the name
> returned is a `String` equal to the Java
> language keyword corresponding to the
> primitive type or void.
>
> If this class object represents a
> class of arrays, then the internal
> form of the name consists of the name
> of the element type preceded by one or
> more '[' characters representing the
> depth of the array nesting. The
> encoding of element type names is as
> follows:
>
> ```
> Element Type Encoding
> boolean Z
> byte B
> char C
> class or interface Lclassname;
> double D
> float F
> int I
> long J
> short S
> ``` | it is an array of objects as specified by [JVM Specifications](http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#14757) for internal representation of class names:
* a single [ means **an array of**
* L followed by a fully qualified class name (e.g. java/lang/Object) is the **class name** terminated by semicolon ;
so **[Ljava.lang.object;** means **Object[]** | What do those strange class names in a java heap dump mean? | [
"",
"java",
"debugging",
"memory-leaks",
"heap-memory",
"jmap",
""
] |
I have a small winapp that uses LinqToSQL as it's DAL. I am creating a summary view of all the CaseNotes for a given person and one of the fields is a Details box. I need to return only the first 50 characters of that column to my treeview function.
Any hints on how I do that? The below is how my TreeView function gets its data for display and the ContactDetails is the column in question.
```
public static DataTable GetTreeViewCNotes(int personID)
{
var context = new MATRIXDataContext();
var caseNotesTree = from cn in context.tblCaseNotes
where cn.PersonID == personID
orderby cn.ContactDate
select new { cn.CaseNoteID,cn.ContactDate, cn.ParentNote, cn.IsCaseLog, cn.ContactDetails };
var dataTable = caseNotesTree.CopyLinqToDataTable();
context.Dispose();
return dataTable;
}
```
---
## ANSWER
I am posting this here in case any future searchers wonder what the solution looks like in the questions context.
```
public static DataTable GetTreeViewCNotes(int personID)
{
DataTable dataTable;
using (var context = new MATRIXDataContext())
{
var caseNotesTree = from cn in context.tblCaseNotes
where cn.PersonID == personID
orderby cn.ContactDate
select new
{
cn.CaseNoteID,
cn.ContactDate,
cn.ParentNote,
cn.IsCaseLog,
ContactDetailsPreview = cn.ContactDetails.Substring(0,50)
};
dataTable = caseNotesTree.CopyLinqToDataTable();
}
return dataTable;
}
``` | [`String.Substring`](http://msdn.microsoft.com/en-us/library/system.string.substring.aspx):
```
var caseNotesTree = from cn in context.tblCaseNotes
where cn.PersonID == personID
orderby cn.ContactDate
select new {
cn.CaseNoteID,
cn.ContactDate,
cn.ParentNote,
cn.IsCaseLog,
ContactDetailsClip = cn.ContactDetails.Substring(0, Math.Min(cn.ContactDetails.Length, 50))
};
```
Also, I would suggest wrapping your use of [`DataContext`s](http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx) in [`using`](http://msdn.microsoft.com/en-us/library/yh598w02.aspx) blocks. | With LinQ you can also do the following :
```
new string( myString.Take(50).ToArray() );
``` | How to return first 50 characters of text in LINQ call | [
"",
"c#",
"winforms",
"linq-to-sql",
""
] |
If there were such a thing I would imagine the syntax to be something along the lines of
```
while(Integer item : group<Integer>; item > 5)
{
//do something
}
```
Just wondering if there was something like this or a way to imitate this? | No, the closest would be:
```
for (Integer item : group<Integer>)
{
if (item <= 5)
{
break;
}
//do something
}
```
Of course if Java ever gets concise closures, it would be reasonable to write something like .NET's [`Enumerable.TakeWhile`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.takewhile.aspx) method to wrap the iterable (`group` in this case) and make it finish early if the condition stops holding.
That's doable even now of course, but the code to do it would be ugly. For reference, the C# would look like this:
```
foreach (int item in group.TakeWhile(x => x > 5))
{
// do something
}
```
Maybe Java will get nice closures some time... | ```
for(Integer item : group<Integer>)
{
if (item <= 5)
break;
//do something
}
```
This is what I can think of. | Is there a such thing as a while each loop in Java? | [
"",
"java",
"while-loop",
""
] |
I am trying to turn off Request Validation for all action methods in a controller by doing this:
```
[ValidateInput(false)]
public class MyController : Controller
{
...
```
The reference I am using says this is possible and tells me to do it this way, but for some reason it's not working.
If I submit any html (even a simple <b> tag) through a text box, I get the error:
> A potentially dangerous Request.Form value was detected from the client (text=<b>").
It's also not working by attaching the attribute to an individual method.
How can I disable Request Validation for a controller?
# EDIT
I am working in VS2008 built in test server. | I tested it on my machine, on both the class definition and the action method, and it worked for me in both cases. Are you sure your view lines up with your method/controller? Are you putting the attribute on the GET method or the POST method?
```
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult MyAction (int id, string content) {
// ...
}
``` | To make it working you need to modify web.config as well:
```
<system.web>
<httpRuntime requestValidationMode="2.0"/>
...
</system.web>
``` | I can't turn off Request Validation for an ASP.NET MVC Controller | [
"",
"c#",
".net",
"asp.net",
"asp.net-mvc",
"request-validation",
""
] |
I have a datagridview with a number of columns, one of these is a datetime column.
I want to display the rows from most recent downwards.
e.g.
Today
Yesterday
The Day Before Yesterday etc.
Is it possible to do this with the datagridview?
The gridviews datasource is an xmldocument.......
help appreciated greatly.
Regards, | ```
this.dataGridView1.Sort(dataGridView1.Columns["DateTime"], ListSortDirection.Ascending);
``` | What is your datasource?
You have to have a datasource that supports sorting.
e.g. a DataTable.
If you have a List you can't sort by default.
In theory you need your on class that inherits from BindingList and implements IBindingList (inheritance from BindingList is not nessacary, but makes it a bit easier).
If your BingingList is bound to the DataGridView you can sort. | c# datagridview order rows? | [
"",
"c#",
"datagridview",
""
] |
I have a ListBox bound to an observable collection of DiceViewModel. Whenever I click a button to add a new item, the ListBox displays the new item like I expect. Everything so far is working well.
```
<ListBox
ItemsSource="{Binding Path=AllDice}"
DisplayMemberPath="Value"/>
```
However, I have another button to roll all existing dice. The items already listed in the box don't get updated, and I'm not sure how to enforce this while keeping to the MVVM design pattern.
Also, my DiceViewModel already implements INotifyPropertyChanged.
Any suggestions? | After some more digging around, here's what I've found. The ObservableCollection doesn't automatically register itself with my DiceViewModel's INotifyPropertyChanged event. So any property changes don't get handled.
However, there is a way to do it in the xaml file:
I added this namespace definition to my Window element.
```
xmlns:vm="clr-namespace:Rolling.ViewModel"
```
Then I modified my ListBox to use a DataTemplate with a specified DataType:
```
<ListBox ItemsSource="{Binding Path=AllDice}">
<ListBox.Resources>
<DataTemplate DataType="{x:Type vm:DiceViewModel}">
<TextBlock Text="{Binding Path=Value}"/>
</DataTemplate>
</ListBox.Resources>
</ListBox>
```
With the specified DataType, the ObservableCollection could register itself with my collection items, receive their events, and then fire it's own CollectionChanged event.
I hope this helps some other people with this poorly documented feature. | In the case of ObservableCollection INotifyPropertyChanged will only notify on changes to the structure of the collection, generally this is the addition and removal of items. The collection has no knowledge of changes to the properties of an individual item within the collection. Instead that individual item itself is responsible for sending notification of its properties changing.
The reasoning behind this goes back to class responsibility and separation of concerns. Since the DiceViewModel likely has data related rolling a die and the value of its last roll then it would follow that it would send notification when its own properties change. | Updating items inside ListBox | [
"",
"c#",
"wpf",
"mvvm",
"binding",
"viewmodel",
""
] |
I have a filelist.txt file and I created a file called clear.php to clear the content of filelist.
I put a button in index.html to call clear.php to clear the file.
Can anyone help me out regarding what PHP code I should write in clear.php?
How to code a button to call clear.php and then return back to index.html showing the result that it has been cleared? | ```
file_put_contents("filelist.txt", "");
```
You can redirect by using the [header()](http://php.net/manual/en/function.header.php) function to modify the Location header. | This would truncate the file:
```
$fh = fopen( 'filelist.txt', 'w' );
fclose($fh);
```
In clear.php, redirect to the caller page by making use of `$_SERVER['HTTP_REFERER']` value. | Clearing content of text file using php | [
"",
"php",
"html",
"text-files",
""
] |
I want a std::vector to contain some functions, and that more functions can be added to it in realtime. All the functions will have a prototype like this:
void name(SDL\_Event \*event);
I know how to make an array of functions, but how do I make a std::vector of functions? I've tried this:
```
std::vector<( *)( SDL_Event *)> functions;
std::vector<( *f)( SDL_Event *)> functions;
std::vector<void> functions;
std::vector<void*> functions;
```
But none of them worked. Please help | Try using a typedef:
```
typedef void (*SDLEventFunction)(SDL_Event *);
std::vector<SDLEventFunction> functions;
``` | Try this:
```
std::vector<void ( *)( SDL_Event *)> functions;
``` | std::vector of functions | [
"",
"c++",
"function",
"pointers",
"stdvector",
""
] |
I have written an Office shared Add-in with C# and .NET 2.0. It uses the same COM Shim for all office apps. Currently, every instance creates its own instance of my class -- they have no knowledge of the fact that the add-in is running on another application.
Is it possible to make it so that, say, when the Word add-in launches it can detect that the Excel add-in is already running? Can they communicate between each other?
Let's say my dll is called Addin.dll. When, for example, Word opens, it runs the code in Addin.dll that implements the IExtensibility interface, and creates a class, let's call it WordAddin. When Excel opens, it also runs the code in Addin.dll, and it creates an instance of ExcelAddin. Now, suppose that Word is running and WordAddin exists. When Excel is opened, Addin.dll is loaded into a different AppDomain. It has no knowledge that WordAddin exists. I want ExcelAddin to have know WordAddin exists, and be able to communicate with it, perhaps through a parent class that creates both.
Anyone know how to do this? | I ended up using named pipes to communicate between processes | You could do this using a Microsoft Message Queue (MSMQ): [Use Microsoft Message Queuing in C# for inter-process communication](https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6170794.html)
This code project article shows how to detect a running instance and how to copy command line parameters between them:
[Single-Instance C# Application - for .NET 2.0](http://www.codeproject.com/KB/cs/CSSIApp.aspx)
Not quite what you are asking but might be of interest: [Detecting a running instance of a program and passing it information](https://stackoverflow.com/questions/632522/detecting-a-running-instance-of-a-program-and-passing-it-information/632578) | Sharing Add-in between Office Apps | [
"",
"c#",
"com",
"ms-office",
"add-in",
""
] |
I asked a question some time ago on java 2d pathfinding...
[Pathfinding 2D Java game?](https://stackoverflow.com/questions/735523/pathfinding-2d-java-game)
The game im developing is based on the idea of theme hospital.
The chosen answer from my question, A\* pathfinding, the link was awesome, and very helpful.
I'm eventually getting to implement this into my game, however I have some further questions/issues regarding it.
In my game, the map will change. The tutorial assumes that the map is static (I think). I have been looking at the code, and as far as I can work out, I just need to create a method to call to update the game map in the pathfinding code.
Second, I see the class GameMap. I have my own class called Board which houses all the tiles. I believe I could integrate the methods on GameMap into my Board class. Right?
Third, I have been working on the reasoning that any rooms would be counted as blocked. I mean as in, any squares the room is covering are counted as blocked. I was thinking ahead to where the people will enter the rooms. They will then have to move around these rooms to get to various places. I was thinking I would just invert the Blocked boolean for each square, but this would not work for 2 reasons. 1, rooms could have ajoining walls, and potentially muck up pathfinding. 2, if the blocked status is simply inverted, then any solid items in the room would be seen as not solid when inverted back, which could cause problems when they are touching a wall.
Thinking about it, it would be better if you could make sides of a square blocked rather than actual whole squares. This must be possible, but I am just getting by using the tutorial in the previous question, and not sure if I should try and change A\* to do this, or work on workarounds for the room items issue.
Any thoughts or suggestions on any of these issues?
I'm implementing the simple path finding today, but just thinking ahead of myself. | From a quick look, it looks like the isValidLocation(mover,sx,sy,xp,yp) method defines if moving from point(sx,sy) to point(xp,yp) is a valid move.
If this method took into consideration the direction of the move, you could block specific directions out of / into a block without making the block entirely impenetrable. This way, you could have 2 accessible blocks next to each other with a solid boundary between them.
This approach has some interesting side-effects such as the ability to create one-way boundaries (block A has access to block B, but not vice versa.) Could be a useful game mechanic in letting the A\* take one way doors (fire escapes?) into account.
There is an algorithm called Adaptive A\* which can recalculate a portion of a path say, if someone stands in front of you. I would concentrate on the vanilla A\* first, you could always calculate a new path from that point on if you found half way through that a previously valid path was blocked.
This looks like interesting reading: [Real-Time Adaptive A\* [PDF]](http://idm-lab.org/bib/abstracts/papers/aamas06.pdf) | If the game map changes you do need to recalculate paths, however you don't necessarily need to recalculate *all* paths depending on what changed.
You should integrate the methods of GameMap into your Board class (with modifications to the GameMap class).
To block sides of a square you could think of each tile as nine separate ones instead (3X3).
For example for a tile with blocked horizontal walls,
instead of a single square you can represent the tile (to your a\* algorithm) as:
```
[X| |X]
[X| |X]
[X| |X]
```
A tile with a vertical and horizontal tile blocked:
```
[ | |X]
[ | |X]
[X|X|X]
```
You would have to store the additional edge information with your game map.
Hope this helps. | Pathfinding 2d java game further issues | [
"",
"java",
"2d",
"path-finding",
"a-star",
""
] |
I want to make the XNA game window be in "windowed" mode but "always on top", is there a way to do this? | Thanks for your response, the code from that webpage wouldn't compile for me, however it did point me in the right direction, this is the code I am using (using XNA 3.1)
First, within the same namespace as the game copy and paste in this code
```
class User32
{
[DllImport("user32.dll")]
public static extern void SetWindowPos(uint Hwnd, int Level, int X, int Y, int W, int H, uint Flags);
}
```
I just wrote it above my main "Game" class, since I only use it within my Game class.
Then within the LoadContent() of the game class (MUST be within the LoadContent() method, doesn't work properly anywhere else), write this somewhere...
```
User32.SetWindowPos((uint)this.Window.Handle, -1, 0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight, 0);
```
note: "graphics" is the instance of GraphicsDeviceManager that is premade for you whenever you start your project.
This can also be used to position the game window wherever you want on the screen. For me I wanted it in the top left corner of the screen. | <http://www.pinvoke.net/default.aspx/user32/SetWindowPos.html>
Include the values from the sample Page in a WinApi class and call this function from your game class:
```
WinApi.SetWindowPos(this.Window.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
```
That should do it. | make game window "always on top" in XNA | [
"",
"c#",
"xna",
""
] |
I have an application where there is a FormWizard with 5 steps, one of them should only appear when some conditions are satisfied.
The form is for a payment wizard on a on-line cart, one of the steps should only show when there are promotions available for piking one, but when there are no promotions i want to skip that step instead of showing an empty list of promotions.
So I want to have 2 possible flows:
```
step1 - step2 - step3
step1 - step3
``` | The hook method [process\_step()](https://django-formtools.readthedocs.io/en/latest/wizard.html#formtools.wizard.views.WizardView.process_step) gives you exactly that opportunity.
After the form is validated you can modify the **self.form\_list** variable, and delete the forms you don't need.
Needles to say if you logic is very complicated, you are better served creating separate views for each step/form, and forgoing the FormWizard altogether. | To make certain forms optional you can introduce conditionals in the list of forms you pass to the FormView in your urls.py:
```
contact_forms = [ContactForm1, ContactForm2]
urlpatterns = patterns('',
(r'^contact/$', ContactWizard.as_view(contact_forms,
condition_dict={'1': show_message_form_condition}
)),
)
```
For a full example see the Django docs: <https://django-formtools.readthedocs.io/en/latest/wizard.html#conditionally-view-skip-specific-steps> | Skip steps on a django FormWizard | [
"",
"python",
"django",
"formwizard",
""
] |
What is the correct way to do conditional formatting in Django?
I have a model that contains a date field, and I would like to display a list of records, but colour the rows depending on the value of that date field. For example, records that match today's date I want to be yellow, records that is before today I want green and ones after I want red.
Somewhere in Django you will need to do that comparison, comparing the current date with the date in the record.
I can see three different places that comparison could be done:
1. Add a method to my model, for example, status(), that returns either 'past', 'present', 'future' and then use that in the template to colour the rows.
2. In the view instead of returning a queryset to the template, pre-process the list and compare each record, build a new dict containing the 'past', 'present' and 'future' values to be used in the template
3. Create a new template tag that does the comparison.
Which of these methods is the correct Django way of doing it? It sounds like conditional formating is something that would come up quite often, and since you can't do arbitrary comparisons in the template some other solution is needed.
The same would apply for simpler formatting rules, for example, if I wanted to display a list of student grades, and I wanted to make the ones higher than 80% green and the ones below 30% red. | I'm a big fan of putting ALL "business" logic in the view function and ALL presentation in the templates/CSS.
Option 1 is ideal. You return a list of pairs: ( date, state ), where the state is the class name ("past", "present", "future").
Your template then uses the state information as the class for a `<span>`. Your CSS then provides the color coding for that span.
You are now free to change the rules without breaking the template. You can change the CSS without touching HTML or Python code.
```
{% for date,state in the_date_list %}
<span class="{{state}}">date</span>
{% endfor %}
``` | I had a very similar requirement; as this is pretty connected to the business logic, I have added a model method to manage this kind of information, to be used then in the template:
```
{% if not bug.within_due_date %}bgcolor="OrangeRed"{% endif %}
```
It could also be obtained through a template tag or filter; but in my case, I felt the best place for the logic was inside the model; I would suggest you analyzing it in the same way. | Django way to do conditional formatting | [
"",
"python",
"django",
"formatting",
"django-templates",
""
] |
I am trying to add an entry to an LDAP server using JNDI. I could successfully read the entries from the LDAP server. But when I try to add a new entry I am getting the errors. I checked various ways but I failed.
```
private String getUserAttribs (String searchAttribValue) throws NamingException{
SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
Attributes matchAttrs = new BasicAttributes(true);
matchAttrs.put(new BasicAttribute("uid", searchAttribValue));
NamingEnumeration answer = ctx.search("ou=People,ou=ABCLdapRealm,dc=abcdomain",matchAttrs);
SearchResult item =(SearchResult) answer.next();
// uid userpassword description objectclass wlsmemberof sn cn
return item.toString();
}
```
This worked correctly.
Then I moved a step forward and tried to add an entry. The code is as follows.
```
public static void bindEntry(DirContext dirContext)throws Exception{
Attributes matchAttrs = new BasicAttributes(true);
// uid userpassword description objectclass wlsmemberof sn cn
matchAttrs.put(new BasicAttribute("uid", "defaultuser"));
matchAttrs.put(new BasicAttribute("userpassword", "password"));
matchAttrs.put(new BasicAttribute("description", "defaultuser"));
matchAttrs.put(new BasicAttribute("cn", "defaultuser"));
matchAttrs.put(new BasicAttribute("sn", "defaultuser"));
matchAttrs.put(new BasicAttribute("objectclass", "top"));
matchAttrs.put(new BasicAttribute("objectclass", "person"));
matchAttrs.put(new BasicAttribute("objectclass", "organizationalPerson"));
matchAttrs.put(new BasicAttribute("objectclass","inetorgperson"));
matchAttrs.put(new BasicAttribute("objectclass", "wlsUser"));
String name="uid=defaultuser";
InitialDirContext iniDirContext = (InitialDirContext)dirContext;
iniDirContext.bind(name,dirContext,matchAttrs);
}
```
But with this I am getting an exception.
```
Exception in thread "main" javax.naming.OperationNotSupportedException: [LDAP: error code 53 - Unwilling To Perform]; remaining name 'uid=defaultuser'
```
Definitely I am violating something. Any idea on this? | LDAP 53, Unwilling to Perform, usually means what it says. You tried to do something 'illegal' from the LDAP servers perspective.
First guess, unlikely though, are you pointing at eDirectory? If so, adding sn is important as it is mandatory in eDirectory's schema to provide a Surname value at create time. In which case, you would probably get a slightly different error, more like a 608 or 611 error.
Second guess, you are point at Active Directory, in which case fullName is a mandatory attribute. But in that case, you also usually get a slightlty different result code. Ought to have more in the error. (Though this might be JNDI's return versus the tools I am used too).
Third guess, you are pointing at someone elses LDAP server and you have missed a mandatory attribute in the schema.
In fact, maybe it is an object class issue. Is wlsUser an auxiliary class, or a real class? Is inetorgperson a real (I am blanking on the name for this type of class, there is aux, structural, and something else) class in your directory?
My basic guess is you have missed a mandatory attribute and are violating schema in your target directory, and I hope the possible examples of missing mandatory's listed above is helpful. | This is the error you get when trying to set the password in Active Directory over a non-SSL connection. Try your code again without the password line. | Adding LDAP entries using JNDI | [
"",
"java",
"ldap",
"jndi",
""
] |
I am now ready to use NHibernate to persist my data layer access. I used DDD until that point and I use fake for unit tests and for the test site.
I know that I can use SchemaExport for unit/integration tests of my NHibernate concrete repositories but how should I generate the schema to be used for the test site ?
Should I create a special class in my tests that create the schema and insert the static data or should I generate the schema at the launch of the site if the database is not created ? | Personally I like to use a small console application which loads all the mappings and executes a SchemaExport as below:
```
new SchemaExport(config).Execute(ddlScript => {
using (var writer = new StreamWriter(fileName, true))
{
writer.Write(ddlScript);
writer.Flush();
}
}, false, false);
```
This console app runs as a step of the build script and the DDL script file then gets picked up by WiX and is included in the MSI package (which generates the whole database at install time). | As a simple scenario you can miss use a unit test for that. Just create unit test called **CreateSchema** which will do the schemaexport. Then run it before you will run the other tests.
I have a similar question [here on STO](https://stackoverflow.com/questions/1097514/how-do-you-add-sample-dummy-data-to-your-unit-tests) | Best practices to generate schema for production with NHibernate | [
"",
"c#",
"asp.net",
"nhibernate",
"asp.net-2.0",
""
] |
I'm trying to make an applet which I can simply drag an image. And I want image object to listen events. So here is the applet code which simple run in a thread:
```
import java.awt.*;
import java.net.URL;
import javax.swing.JApplet;
public class Client extends JApplet implements Runnable {
private static final long serialVersionUID = 1L;
MediaTracker mediaTracker;
Image [] imgArray;
Tas t1;
public void init()
{
mediaTracker = new MediaTracker(this);
imgArray = new Image[1];
URL base = getCodeBase();
imgArray[0] = getImage(base,"okey.png");
mediaTracker.addImage(imgArray[0],1);
try {
mediaTracker.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
t1 = new Tas(this, new Rectangle(0, 0, imgArray[0].getWidth(this), imgArray[0].getHeight(this)), imgArray[0]);
Thread t = new Thread(this);
t.start();
}
public void paint(Graphics g)
{
t1.paint(g);
}
@Override
public void run() {
while(true){
//System.out.println("run");
repaint();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
And the class of object which holds image is:
```
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Movable extends JPanel implements MouseListener {
public Client mainObj;
public Rectangle rect;
public Image image;
public Movable(Client mainObj, Rectangle rect, Image image) {
this.mainObj = mainObj;
this.rect = rect;
this.image = image;
addMouseListener(this);
}
public void paint(Graphics g) {
g.drawImage(image, rect.x, rect.y, rect.width, rect.height, this);
}
@Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("clicked");
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent arg0) {
System.out.println("pressed");
}
@Override
public void mouseReleased(MouseEvent arg0) {
}
}
@SuppressWarnings("serial")
class Tas extends Movable{
public String name = "";
public Tas(Client mainObj, Rectangle rect, Image image) {
super(mainObj, rect, image);
}
}
```
I can see the image in my applet but nothing happens when I click in or out of the image. So what's wrong with this code. | Assuming that Tas in code #1 is Moveable in code #2...
You don't actually use the Moveable as a Component, but instead ask it to paint itself onto the Applet's graphics context, here:
```
public void paint(Graphics g)
{
t1.paint(g);
}
```
Instead you should add an instance of Moveable onto the Applet's container, wherein painting will become automatic, and it will start to receive mouse events. You can also remove that paint() method then too. | First of all you should never override the paint method of a top level container (JApplet, JFrame, JDialog).
Then to do custom painting on other Swing components you override the paintComponent() method of the component, NOT the paint() method. Read the Swing tutorial on [Custom Painting](http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html). So first fix those problems.
I'm not sure what the point of the Thread is but remove it from your code until you solve your other problems. If you are trying to do animation, then you should be using a [Swing Timer](http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html), not a Thread.
If you want to see some code for dragging components you can take a look at [Moving Windows](http://www.camick.com/java/blog.html?name=moving-windows) for some generic code. | Adding mouseListener to my object in java | [
"",
"java",
"applet",
"mouse",
"listener",
""
] |
Having recently learned of the [DebuggerDisplay](http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerdisplayattribute.aspx) attribute, I've found it quite useful. However, one thing that surprises me is that it doesn't have a `[ConditionalAttribute("DEBUG")]` attribute attached to it. Is there some way to force this or is it a bad idea to try? Or does it not matter for some other reason? | The [ConditionalAttribute("DEBUG")] is only used for optimising out method calls.
If you really want to remove these from your builds you can use #ifdef so that the code is only compiled in release mode.
One thing to bear in mind is that you can still debug binaries in release mode, as long as you have the pdb files it shouldn't matter. Release mode just clears up variables sooner and applies some compiler optimisations | As I often have to debug things in Release configuration builds that don't have the `DEBUG` directive, I would not want these hints to the debugger to be removed.
However, if you have some proprietary or confidential information in the way you display things when debugging that you don't want to make it into your release build, you may want to consider using the [`ConditionalAttribute`](http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx) or [`#if/#elif/#endif`](http://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx) preprocessor directives to control what is emitted into your release builds.
For example, you could do:
```
#if DEBUG
[DebuggerDisplay...]
#endif
public class MyAwesomeClass
{
}
```
This would ensure the attribute is only emitted when the DEBUG directive is given. | Do debugging attributes such as [DebuggerDisplay] still get compiled into Release binaries? | [
"",
"c#",
"debugging",
"release-management",
""
] |
I am in the process of evaluating FindBugs and am trying to make use of the excludeFilter so that the tool does not process the test packages or the generated ejb stubs.
I have tried the following:
```
<FindBugsFilter>
<!-- Match any test packages -->
<Match>
<Package name="~.*\.test"/>
</Match>
<Match>
<Or>
<Class name="~.*\.^_*"/>
<Class name="~.*EJS*"/>
</Or>
<Bug pattern="MALICIOUS_CODE"/>
</Match>
```
The generated EJB's are still being looked at. Can someone provide some better direction on this.
I want to exclude out all classes that start with "\_"
Example:
com/mycompany/business/admin/ejb/\_AdminRemoteHome\_Stub.java
com/mycompany/business/admin/ejb/\_EJSRemoteStatelessAdminHome\_054d51b9\_Tie.java
**Updated filter file.**
I change the filter file to the following structure using the suggested regx changes and now things are working as expected:
```
<FindBugsFilter>
<!-- Match any test packages -->
<Match>
<Package name="~.*\.test"/>
</Match>
<Match>
<Class name="~.*\._.*"/>
</Match>
<Match>
<Class name="~.*?EJS.*"/>
</Match>
```
Looks like I need to go back and brush up on my regx. | Regarding [FindBugFilter](http://findbugs.sourceforge.net/manual/filter.html),
(just to be sure) are you sure you are considering the compiled class files directories, and not the sourcePath? (as mentioned in this [SO answer](https://stackoverflow.com/questions/756523/findbugs-filter-file-for-ignoring-junits)).
From the [Java element name matching](http://findbugs.sourceforge.net/manual/filter.html#d0e2197) section:
> If the name attribute of Class, Method or Field starts with the ~ character the rest of attribute content is interpreted as a **Java regular expression** that is matched against the names of the Java element in question.
Would the following regex be more accurate?
```
<Class name="~.*\._.*"/>
<Class name="~.*?EJS.*"/>
```
* "`.*\._.*`" instead of "`.*\.^_*`" because the [anchor](http://www.regular-expressions.info/anchors.html) is supposed to match at the start of the string the regex pattern is applied to.
* "`.*?EJS.*`" instead of "`.*EJS*`" because the `?` [quantifier](http://www.regular-expressions.info/repeat.html) makes the matching lazy, avoiding to 'eat' EJS. (Plus "`S*`" means "0 or n S", which does not help here) | My findbugs exclude file was not working as above. I'm using the findbugs-maven-plugin v3.0.0. To resolve the issue I ran a build which generated findbugsXml.xml, then issued:
```
mvn findbugs:gui
```
This starts the User Interface to findbugs. I then loaded the findbugsXml.xml file, navigated to the warnings I desired excluded, excluded them and then saved the exclusions to findbugs\_exclude.xml. I added this to the maven plugin as
```
<excludeFilterFile>findbugs_exclude.xml</excludeFilterFile>
```
The generated file works and the exclusions are truly omitted from the findbugs report.
Another great tip I found for the maven plugin was to add:
```
<omitVisitors>UnreadFields</omitVisitors>
``` | Problems with FindBugs exclude filter | [
"",
"java",
"findbugs",
""
] |
Hy,
is there any event-drive/event-based Webframework for Python?
I mean something like [NitroGen](http://www.nitrogenproject.com) is for erlang.
You simply get some components you add to a website (like a button) and accociate a python-function to the "onclick"-handler of the button and it gets executed. It should generate all needed html and js core for me (just as nitrogen does) and support all needed components (like span, p, button, textbox, passwordfield...)
Like the following code:
```
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.Button import Button
from pyjamas import Window
def greet(fred):
Window.alert("Hello, AJAX!")
if __name__ == '__main__':
b = Button("Click me", greet)
RootPanel().add(b)
```
which gets [this](http://pyjs.org/examples/helloworld/output/Hello.html).
The only framework I found is [PyJamas](http://pyjs.org/) but it is made for Web-Applications (so things like Webmailers) and not for Web-Pages (where google needs content to index and which should be readable without js, with limited functionality). So is there something similar like PyJamas or Nitrogen?
Thanks! | KSS (Kinetic Style Sheets) provides something similar to NitroGen. Although KSS differs from NitroGen in that it defines a simple domain-specific language (DSL) for declaring how JavaScript events should be bound to an HTML page on the client side, and this DSL can also declare that events need to trigger a server-side component via AJAX. With NitroGen and PyJamas the information containing how the JavaScript interacts with the HTML is deduced from data structures that are part of a server-side language.
<http://kssproject.org/>
From the KSS project description, "KSS has both a client-side Javascript library and server-side support. The client-side Javascript library needs to be included in your page. It fetches Kinetic style sheets from the server, parses them and binds a set of action to browser events and/or page elements. It is clean Javascript code that can peacefully coexist with other clean Javascript librarys like JQuery or ExtJS."
KSS can be used independant of any Python or server-side code. However, there are facilities in KSS for binding KSS client-side events back to server-side callables in a Python web framework. There are bindings to use KSS with many of Python's popular web frameworks (Django, Pylons, Zope, Plone, Grok). | HTML is not event-driven, so you can't make an event-driven web framework like that without resorting to Ajax, and you didn't want that. So the answer is no, because such a thing is simply impossible,
What I suspect you mean rather than event-driven, is that you have a system where you define up a schema and has forms generated for you. And every Web framework has that.
But of you like components and event driven development, look into the Zope Toolkit based web frameworks, i.e. Grok, Repoze.BFG, Zope3 and the newest of them: Bobo.
<http://grok.zope.org/>
<http://bfg.repoze.org/>
<http://wiki.zope.org/zope3/Zope3Wiki>
<http://bobo.digicool.com/>
Edit: OK, evidently the problem was only with Pyjamas, not using Javascript.
In that case KSS, as mentioned above works. And it's useable with the frameworks above! | Eventdriven Webframework for Python | [
"",
"python",
"frameworks",
""
] |
Ok, I am trying to filter a list/dictionary passed to me and "clean" it up a bit, as there are certain values in it that I need to get rid of.
So, if it's looking like this:
```
"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"...}]
```
How would I quickly and easily run through it all and replace all values of "AAA" with something like "XXX"?
Focus is on speed and resources, as these may be long lists and I don't want this process to consume too much time. | ```
DATA = {"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"}]}
for name, datalist in DATA.iteritems(): # Or items() in Python 3.x
for datadict in datalist:
for key, value in datadict.items():
if value == "AAA":
datadict[key] = "XXX"
print (DATA)
# Prints {'records': [{'key3': 'CCC', 'key2': 'BBB', 'key1': 'XXX', 'key4': 'XXX'}]}
``` | ```
dic = root['records'][0]
for i, j in dic.items(): # use iteritems in py2k
if j == 'AAA':
dic[i] = 'xxx'
``` | Replacing values in a Python list/dictionary? | [
"",
"python",
"list",
"dictionary",
"replace",
""
] |
How to find memory used by an object in PHP? (c's sizeof). The object I want to find out about is a dictionary with strings and ints in it so it makes it hard to calculate it manually. Also string in php can be of varied length depending on encoding (utf8 etc) correct? | You could use [memory\_get\_usage()](http://php.net/memory_get_usage).
Run it once before creating your object, then again after creating your object, and take the difference between the two results. | To get an idea about the objects size, try
```
strlen(serialize($object));
```
It is by no means accurate, but an easy way to get a number for comparison. | How to find memory used by an object in PHP? (sizeof) | [
"",
"php",
"memory",
"memory-management",
""
] |
I am experimenting with EJB3 on JBoss, developing a stateless bean. Basically once the module has been deployed I need to perform some actions related to load application settings.
To do this I've annotated a method as @PostConstruct, which as far as I know from the API instructs the container to invoke it once the bean has been deployed and before get in service. (correct?)
Now, I am confused, because from the log on that method looks like is not simply called after has been deployed but before each exposed method is called.
I only need to call that method once, not every time it receives a call. What would be the best approach?
Thanks in advance
Alessandro Ilardo | A stateless bean should be just that - stateless. Meaning that in use, you should neither be able to tell or to care if the bean was pulled from a pool or constructed on demand for your request. I'm hard-put to envision how a PostConstruct could apply to a stateless environment, since I always use that function to finish building a bean's state.
Apparently, JBoss is either forgoing the pooling of stateless beans and constructing them fresh each time, or, if it is using pooling, treating them like they were reconstructed each time (since they shouldn't be carrying state information). I'm actually a little surprised that it invokes the PostConstruct at all. | First of all PostConstruct is called before first method will be invoked on the bean. If no method will be invoked no post construct ever be called.
Secondly you can execute inverse actions in PreDestory method to remove side effects.
Anyway which kind of action you have to perform? | java ejb3 @PostConstruct | [
"",
"java",
"ejb-3.0",
""
] |
I am an experienced C++ programmer with average Python skills. The reasons I studied Python in the first place were:
* to get a different perspective on programming (static vs dynamic, interpreted vs compiled, etc.)
* to increase the breadth of projects that I can work on (Python allows me to do web development, develop for Symbian phones or knock up quick system administration scripts)
* to complement my C++ skills.
I think that Python is great and I believe that I have achieved the above goals. I will continue to use it for small projects, scripts and web development.
I doubt that I can use it for medium to large projects though. While the dynamic typing is convenient, it allows a certain class of bugs that I find disturbing. Unit testing and linting can alleviate this problem, but static typing completely eliminates it.
After looking at some programming languages, I think that Scala looks like a good candidate:
I like the type inference and it runs on the JVM so it should be available wherever the JVM is available. I can also learn more about functional programming when using it.
But... I also have some doubts, and this is where I hope that the Stack Overflow community can help:
* Portability: Linux and Windows at least I hope. What about mobile phones, is it possible to get it to run there?
* C++ compatibility: can I mix C++ code with Scala? (JNI?)
* Programming paradigm: I don't feel comfortable with switching to functional programming (FP) at this time. Can I use object oriented and procedural with some FP at first and then change the proportions as I learn?
* Tool chain maturity: what's your experience with IDEs and debuggers? I'm using Eclipse right now and it seems OK.
* Learning speed: considering my experience, how fast do you think that I can reach a workable level with Scala?
* Deployment: how exactly do you deploy a Scala program? Is it a jar, is it an executable?
Finally, what do you think that are some of Scalas disadvantages? | * Portability: Linux and Windows at least I hope. What about mobile phones, did anyone succeed in getting it to run there?
Yes. There is quite some movement about Scala on Android. As for J2ME, I saw something in that respect, but not much. There is some code pertaining to J2ME on the source code repository. I'm not sure how viable it is, but it looks to me that there isn't much demand for that.
I'll also mention that there is/was a pool on Scala-Lang about the desired target platforms, and J2ME was one of them, very low on the totem pole.
* C++ compatibility: can I mix C++ code with Scala? (JNI?)
As well as you can mix C++ with Java, for whatever that is worth. If you haven't any experience with that, you can just read the Java resources, as anything in them will be applicable with Scala with no changes (aside Scala syntax).
* Programming paradigm: I don't feel comfortable with switching to FP at this time. Can I use OO and procedural with some FP at first and then change the proportions as I learn?
Definitely, yes. Scala goes out of it's way to make sure you don't need to program in a functional style. This is the main criticism of Scala from functional folks, as a matter of fact: some do not consider a language functional unless it forces the programmer to write in functional style.
Anyway, you can go right on doing things your way. My bet, though, is that you'll pick up functional habits without even realizing they are functional.
Perhaps you can look at the [Matrices](http://dcsobral.blogspot.com/search/label/matrix) series in my own blog about writing a Matrix class. Even though it looks like standard OO code, it is, in fact, very functional.
* Tool chain maturity: what's your experience with IDEs and debuggers? I'm using Eclipse right now and it seems ok.
IDEA (IntelliJ), NetBeans and Eclipse all have good support for Scala. It seems IDEA's is the best, and NetBeans/Eclipse keep frog-jumping each other, though NetBeans has certainly been more stable than Eclipse of late. On the other hand, the support on Eclipse is taking a very promising route that should produce results in the next 6 months or so -- it's just that it's a bumping route. :-)
Some interesting signs of Scala tooling for these enviroments is the fact that the Eclipse plugin in development uses AOP to merge more seamlessly with the whole IDE, that the NetBeans plugin is being completely rewritten in Scala, and that there's a Scala Power Pack on IDEA that supports, among other things, translating Java code into Scala code.
The EMACS folks have extensive tools for Scala as well, and lots of smaller editors have support for it too. I'm very comfortable with jEdit's support for small programs and scripts, for instance.
There is also good Maven support -- in fact, the standard way to install [Lift](http://liftweb.net/) is to install maven, and then build a Lift archetype. That will pull in an appropriate Scala version. There's an `scala:cc` target that will do triggered recompilation as well.
Speaking of recompilation, neither Maven, and particularly nor Ant do a good job at identifying what needs to be recompiled. From that problem sprung [SBT](http://code.google.com/p/simple-build-tool/) (Simple Build Tool), written in Scala, which solves that problem through the use of Scala compiler plugin. SBT uses the same project layout as Maven, as well as Maven/Ivy repositories, but project configurations are done in Scala code instead of XML -- with support for Maven/Ivy configuration files as well.
* Learning speed: considering my experience, how fast do you think that I can reach a workable level with Scala?
Very fast. As a purely OO language, Scala already introduces some nice features, comparable to some stuff that's present in C++ but not Java, though they work in different fashion. In that respect, once you realize what such features are for and relate them to C++ stuff, you'll be much ahead of Java programmers, as you'll already know what to do with them.
* Deployment: how exactly do you deploy a Scala program? Is it a jar, is it an executable?
The same thing as Java. You can deploy JARs, WARs, or any other of Java targets, because the scala compiler generate class files. In fact, you use Java's jar to generate a Scala's JAR file from the class files, and the Maven targets for Lift support building WAR files.
There is an alternative for script files, though. You can call "scala" to run Scala source code directly, similar to a Perl of Shell script. It can also be done on Windows. However, even with the use of a compilation daemon to speed up execution, start up times are slow enough that effective use of Scala in a heavy scripting environment needs something like [Nailgun](http://martiansoftware.com/nailgun/index.html).
As for Scala's disadvantages, take a look at my answer (and other's) in [this](https://stackoverflow.com/questions/1104274/scala-as-the-new-java/1105733#1105733) Stack Overflow question. | Scala is an evolving language well worth to invest in, especially if you are coming from Java world. Scala is widely covered at [Artima](http://www.artima.com/). See this [article](http://www.artima.com/scalazine/articles/programming_style.html) from Bill Venners and also read about [Twitter and Scal](http://www.artima.com/scalazine/articles/twitter_on_scala.html)a.
Regarding your questions:
* Java can run wherever there is a JVM. No luck with the mobile phones however. You need a full JRE, not the subset that is available there.
* This is possible with JNI. If something is possible with Java, then it is possible with Scala. Scala can call Java classes.
* Functional programming is a strong point of Scala - you do need to learn it. However you could also start using it without taking full advantage of it and work your way with it.
* There is a plug-in of Eclipse. It is not best, but it will do the job. More details [here](http://www.artima.com/forums/flat.jsp?forum=270&thread=255770).
* If you are experienced, I would say really fast. I recommend that you find a book to start with.
* See this [faq](http://www.scala-lang.org/faq/2) entry for deployment. | Should I study Scala? | [
"",
"java",
"scala",
"jvm-languages",
""
] |
The title is the main question. The exact scenario (I am 'using namespace std;'):
```
void SubstringMiner::sortByOccurrence(list<Substring *> & substring_list) {
list::sort(substring_list.begin(), substring_list.end(), Substring::OccurrenceComparator);
}
```
This is the comparator definition:
```
class Substring {
// ...
class OccurrenceComparator {
public:
bool operator() (Substring * a, Substring *b);
}
};
```
Implementation of the comparator is intuitive and trivial. I am also using a very similar comparator in a std::set and it works fine. When I add the sortByOccurrence() funcion it gives me the error in the title.
What should I do?
**EDIT:** I'm now trying to pass Substring::OccurrenceComparator() as the comparator, and am getting the following error:
```
g++ -Wall -g -c substring_miner.cpp -o obj/subtring_miner.o
substring_miner.cpp: In function ‘void SubstringMiner::sortByOccurrence(std::list<Substring*, std::allocator<Substring*> >&)’:
substring_miner.cpp:113: error: no matching function for call to ‘std::list<Substring*, std::allocator<Substring*> >::sort(std::_List_iterator<Substring*>, std::_List_iterator<Substring*>, Substring::OccurrenceComparator)’
/usr/include/c++/4.3/bits/list.tcc:303: note: candidates are: void std::list<_Tp, _Alloc>::sort() [with _Tp = Substring*, _Alloc = std::allocator<Substring*>]
make: *** [substring_miner] Error 1
```
My code line is now:
```
list<Substring *>::sort(substring_list.begin(), substring_list.end(), Substring::OccurrenceComparator());
```
I can't remove the template or it gives me an error saying that template parameters were wrong. | `list` member `sort` is a non-static function so must be called on a list instance.
```
substring_list.sort( Substring::OccurrenceComparator() );
```
**Edit:** You can't use the free function `std::sort` as it requires random access iterators which `list` iterators are not. | You're passing a *class* as an argument to a function. You cannot do that - you have to create an instance of the class, and pass that:
```
substring_list.sort(Substring::OccurrenceComparator());
```
Note the extra parentheses after `OccurenceComparator` above that create a temporary object of the class using default constructor.
Another mistake is that you're calling `list::sort` as a static function on class `std::list`. It's not static, so you need to call it as a member function on `substring_list`. | Error in std::list::sort with custom comparator (expected primary-expression before ')' token) | [
"",
"c++",
"stl",
"sorting",
"comparator",
""
] |
I have a number of objects, all from the same class(ColorNum) Each object has 2 member variabels (m\_Color and m\_Number)
Example:
```
ColorNum1(Red,25)
ColorNum2(Blue,5)
ColorNum3(Red,11)
ColorNum4(White,25)
```
The 4 objects are in the ColorNumList
```
List<ColorNum> ColorNumList = new List<ColorNum>();
```
Now I want to order the list so the objects with mColor = "Red" is in the top.
I dont care about the order of the remaining objects.
What should my predicate method look like? | Using linq:
```
var sortedRedAtTop =
from col in ColorNumList
order by col.Color == Red ? 1 : 2
select col;
```
Or the list's sort method:
```
ColorNumList.Sort( (x,y) =>
(x.Color == Red ? 1 : 2)-(y.Color == Red ? 1 : 2) );
``` | ```
ColorNumList.Sort((x, y) => x.m_Color == Red ? 1 : (y.m_Color == Red ? -1 : 0));
``` | Sort List alternative in c# | [
"",
"c#",
".net",
"list",
"generic-collections",
""
] |
I have an eclipse's .classpath file that looks like this:
```
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="test"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
<classpathentry kind="lib" path="/libraries/jee/servlet-api.jar"/>
<classpathentry kind="lib" path="/libraries/junit/junit-4.6.jar"/>
<classpathentry kind="lib" path="/libraries/log4j/log4j-1.2.15.jar"/>
</classpath>
```
I'd like to add a whole directory of jars to the classpath - I like eclipse (or more precisely, our ant-based build process that uses .classpath format) to know several jars that reside in a single directory, without specifying them directly. How can I do that? | I'm not sure eclipse can do that itself.
You could try
1. Move to Maven for you build system and then it's eclipse:eclipse command will generate the .classpath file for you
2. Get ant to modify the .classpath after a build. After all, it's just xml | My colleague implemented a classpath container which recursivly looks for jars in a given directory within the workspace, have a look at <http://openscada.org/2010/05/31/adding-a-directory-as-class-path-to-eclipse/>
The update site can be found at <http://repo.openscada.org/p2/bob/R>
The plugin is licensed unter LGPL V3 and you can find the source code under git://git.openscada.org/ (<http://git.openscada.org/?p=org.openscada.bob.git;a=tree>) | Include multiple jars with classpathentry | [
"",
"java",
"eclipse",
"jar",
"classpath",
""
] |
I'm coding a simple little class with a single method send an email. My goal is to implement it in a legacy Visual Basic 6 project, exposing it as a COM object via the COM Interop facility.
There's a detail I'm finding difficult to resolve, that being how granular should I be at validating parameters. On that light, a thing I'm really not happy about, and which is not a detail at all, is the way I'm actually handling exceptions:
```
public class MyMailerClass
{
#region Creation
public void SendMail(string from, string subject, string to, string body)
{
if (this.IsValidMessage(from, subject, to, body)) // CS1501
{
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;
msg.From = new MailAddress(from);
msg.To.Add(to);
msg.Subject = subject;
msg.Body = body;
SmtpClient srv = new SmtpClient("SOME-SMTP-HOST.COM");
srv.Send(msg);
}
else
{
throw new ApplicationException("Invalid message format.");
}
}
#endregion Creation
#region Validation
private bool IsValidMessage(string from, string subject, string to, string body)
{
Regex chk = new Regex(@"(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})");
if (!chk.IsMatch(from))
{
return false;
}
if (!chk.IsMatch(to))
{
return false;
}
if (!string.IsNullOrEmpty(subject))
{
return false;
}
if (!string.IsNullOrEmpty(body))
{
return false;
}
else
{
return true;
}
}
#endregion Validation
}
```
**Any** suggestion will be much appreciated, so **thanks much** in advance for all your comments!
**Note**: Would it be convenient to implement Enterprise Library's [Validation Application Block](http://msdn.microsoft.com/en-us/library/cc309509.aspx) on this particular case? | Consider the contract that you are imposing upon the callers of SendMail. They are required to pass you a "valid email address". Who decides what is valid? SendMail does. Basically your method is "high maintenance" -- it wants things exactly the way it likes, and the only way to tell whether what you're going to give it will be satisfactory is to try and hope for the best.
Don't write high-maintenance methods without giving the caller a chance to know how to satisfy it, or at least have a way to avoid the exception. Extract the validation logic to an "IsValidAddress" method that returns a Boolean. Then have your SendMail method call IsValidAddress and throw if it is invalid.
You get several nice effects from this change:
(1) Increased separation of concerns. SendMail's job is to make the email mechanism work, not to pass judgment on whether an email address is valid. Isolate that policy decision to code that specializes in verification.
(2) Address validation is a useful tool in of itself; there are lots of times when you want to know whether an address is well-formed without sending mail to it.
(3) You can update and improve your validation logic easily because it is all in one sensible place.
(4) Callers have a way that they can guarantee that no exception will be thrown. If a caller cannot call a method without guaranteeing that the arguments are valid, then they have to catch the exception. Ideally you should never make a caller have to handle an exception to make their code correct; there should be a way they can write correct code that never throws, even if the data they've been handed is bad.
Here are a couple of articles I've written on this subject that you might find helpful:
Exception handling: [http://ericlippert.com/2008/09/10/vexing-exceptions/](http://blogs.msdn.com/ericlippert/archive/2008/09/10/vexing-exceptions.aspx)
High-maintenance methods: <http://blogs.msdn.com/ericlippert/archive/2008/09/08/high-maintenance.aspx> | Having two `throw` statements in a row makes no sence - only the first one will be executed and then control will be passed to the exception handler and never to the second `throw`.
In my opinion it is more than enough to just say smth like "Sender e-mail is invalid." An e-mail is quite simple and short and so the user will be able to resolve this without any additional guidance.
I also think it would be better to first check all the passed in values and only then start work. What's the point in partially doing work if you can then encounter an invalid parameter value and throw an exception and never complete this work. Try to indicate errors as early as you can - at the very beginning if possible. | Exception handling: how granular would you go when it comes to argument validation? | [
"",
"c#",
"vb6",
"exception",
"com-interop",
""
] |
This is a little different than the questions that have already been asked on this topic. I used that advice to turn a function like this:
```
function foo() {
document.getElementById('doc1').innerHTML = '<td>new data</td>';
}
```
into this:
```
function foo() {
newdiv = document.createElement('div');
newdiv.innerHTML = '<td>new data</td>';
current_doc = document.getElementById('doc1');
current_doc.appendChild(newdiv);
}
```
But this still doesn't work. An "unknown runtime error" occurs on the line containing innerHTML in both cases.
I thought creating the newdiv element and using innerHTML on that would solve the problem? | It is not possible to create td or tr separately in Internet Explorer. This same problem has existed in other browsers for quite some time too, however latest versions of those do not suffer from that issue any more.
You have 2 options to:
1. Use table specific APIs to add
cells/rows. See for example [MSDN
for insertCell](http://msdn.microsoft.com/en-us/library/dd347123(VS.85).aspx) and more
2. Create a utility function, that
would help you creating DOM nodes
out of strings. In case of a table you would need to wrap up your HTML so that the resulting HTML is always a table and then get required element by tag name.
For example like this:
```
var oHTMLFactory = document.createElement("span");
function createDOMElementFromHTML(sHtml) {
switch (sHtml.match(/^<(\w+)/)) {
case "td":
case "th":
sHtml = '<tr>' + sHtml + '</tr>';
// no break intentionally left here
case "tr":
sHtml = '<tbody>' + sHtml + '</tbody>';
// no break intentionally left here
case "tbody":
case "tfoot":
case "thead":
sHtml = '<table>' + sHtml + '</table>';
break;
case "option":
sHtml = '<select>' + sHtml + '</select>';
}
oHTMLFactory.innerHTML = sHtml;
return oAML_oHTMLFactory.getElementsByTagName(cRegExp.$1)[0] || null;
}
```
Hope this helps! | I found that this (innerHTML += "") would cause the table to appear. The down side is that any javascript events applied to the table or elements inside the table are blown away.
```
var szBR = "\r\n";
var szClass = "myTable";
var szSelector = "#divDisplay123";
var szSelector2 = "divDisplay123";
var pnlID = "myTable2";
var szRtn =
"<table id=\"" + pnlID + "\" class=\"" + szClass + "\" >" + szBR +
"</table>";
$(szSelector).append (szRtn);
for (var y=0; y<10; y++)
{
var pnlID_TR = pnlID + "_TR_" + y;
szRtn =
" <tr id=\"" + pnlID_TR + "\" class=\"" + szClass + "_TR\">" + szBR +
" </tr>";
$("#" + pnlID).append (szRtn);
for (var x=0; x<5; x++)
{
var pnlID_TD = pnlID + "_TD_" + x + "_" + y;
szRtn =
" <td id=\"" + pnlID_TD + "\" class=\"" + szClass + "_TD\">" + szBR +
"Hello World2" + szBR +
" </td>";
$("#" + pnlID_TR).append (szRtn);
}
}
$(szSelector).append ("<HR>");
document.getElementById (szSelector2).innerHTML += "";
``` | IE innerHTML error | [
"",
"javascript",
"dom",
""
] |
What is the best cross browser way to open a download dialog (let's assume we can set content-disposion:attachment in the headers) without navigating away from the current page, or opening popups, which doesn't work well in Internet Explorer(IE) 6. | 7 years have passed and
I don't know whether it works for IE6 or not, but this prompts OpenFileDialog in FF and Chrome.
```
var file_path = 'host/path/file.ext';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
``` | This javascript is nice that it doesn't open a new window or tab.
```
window.location.assign(url);
``` | Easiest way to open a download window without navigating away from the page | [
"",
"javascript",
""
] |
I have a javascript/jQuery block as a callback after $.get function:
```
function myCallBack(data, textStatus) {
var text1 = $(data).html();
document.write(text1);
}
```
The data contains html data ok. I'd like to strip the html and get only inner html into text1 variable. For some reason it doesn't work. Firebug kinda "crashes" upon executing line 'var text1 = ...'
**Edited**:
My **data** variable contains:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "w3.org/TR/xhtml1/…;\r\n\r\n<html xmlns="w3.org/1999/xhtml">;\r\n
<head>\r\n
<title></title>\r\n
</head>\r\n
<body>\r\n Testing...\r\n</body>\r\n
</html>\r\n
```
And I'd like to parse the part between body tags. | You mean you want the inner text?
```
var text1 = $(data).text();
```
**[Update]**
Try it with this regular expression:
```
var bodyText = new RegExp(/<body[^>]*>([\S\s]*?)<\/body>/).exec(data)[1];
``` | Try this:
```
$(data)[1].data
```
But I think that just works with a specific example and not in general. | Getting inner html with jQuery? | [
"",
"javascript",
"jquery",
""
] |
which one is faster
```
select * from parents p
inner join children c on p.id = c.pid
where p.x = 2
```
OR
```
select * from
(select * from parents where p.x = 2)
p
inner join children c on p.id = c.pid
where p.x = 2
``` | In `MySQL`, the first one is faster:
```
SELECT *
FROM parents p
INNER JOIN
children c
ON c.pid = p.id
WHERE p.x = 2
```
, since using an inline view implies generating and passing the records twice.
In other engines, they are usually optimized to use one execution plan.
`MySQL` is not very good in parallelizing and pipelining the result streams.
Like this query:
```
SELECT *
FROM mytable
LIMIT 1
```
is instant, while this one (which is semantically identical):
```
SELECT *
FROM (
SELECT *
FROM mytable
)
LIMIT 1
```
will first select all values from `mytable`, buffer them somewhere and then fetch the first record.
For `Oracle`, `SQL Server` and `PostgreSQL`, the queries above (and both of your queries) will most probably yield the same execution plans. | I know this is a simple case, but your first option is much more readable than the second one. As long as the two query plans are comparable I'd always opt for the more maintainable SQL code which your first example is for me. | simple sql query | [
"",
"sql",
"performance",
""
] |
**DO NOT DO THIS.**
This question is still getting upvotes, so I wanted to add a warning to it. If you're using Python 3, just use the included [`json` package](https://docs.python.org/3/library/json.html). If you're using Python 2, *do everything you can to move to Python 3*. If you're prevented from using Python 3 (my condolences), use the [simplejson package](https://pypi.org/project/simplejson/) suggested by [James Thompson](https://stackoverflow.com/questions/1083250/running-json-through-pythons-eval#answer-1083262).
Original question follows.
---
Best practices aside, is there a compelling reason **not** to do this?
I'm writing a post-commit hook for use with a Google Code project, which provides commit data via a JSON object. GC provides an HMAC authentication token along with the request (outside the JSON data), so by validating that token I gain high confidence that the JSON data is both benign (as there's little point in distrusting Google) and valid.
My own (brief) investigations suggest that JSON happens to be completely valid Python, with the exception of the `"\/"` escape sequence — which GC doesn't appear to generate.
So, as I'm working with Python 2.4 (i.e. no `json` module), `eval()` is looking *really* tempting.
**Edit:** For the record, I am very much **not** asking if this is a good idea. I'm *quite* aware that it isn't, and I very much doubt I'll ever use this technique for any future projects even if I end up using it for this one. I just wanted to make sure that I know what kind of trouble I'll run into if I do. :-) | If you're comfortable with your script working fine for a while, and then randomly failing on some obscure edge case, I would go with eval.
If it's important that your code be robust, I would take the time to add simplejson. You don't need the C portion for speedups, so it really shouldn't be hard to dump a few .py files into a directory somewhere.
As an example of something that might bite you, JSON uses Unicode and simplejson returns Unicode, whereas eval returns str:
```
>>> simplejson.loads('{"a":1, "b":2}')
{u'a': 1, u'b': 2}
>>> eval('{"a":1, "b":2}')
{'a': 1, 'b': 2}
```
Edit: a better example of where eval() behaves differently:
```
>>> simplejson.loads('{"X": "\uabcd"}')
{u'X': u'\uabcd'}
>>> eval('{"X": "\uabcd"}')
{'X': '\\uabcd'}
>>> simplejson.loads('{"X": "\uabcd"}') == eval('{"X": "\uabcd"}')
False
```
Edit 2: saw yet another problem today pointed out by SilentGhost: eval doesn't handle true -> True, false -> False, null -> None correctly.
```
>>> simplejson.loads('[false, true, null]')
[False, True, None]
>>> eval('[false, true, null]')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'false' is not defined
>>>
``` | The point of best practices is that in most cases, it's a bad idea to disregard them. If I were you, I'd use a parser to parse JSON into Python. Try out [simplejson](http://undefined.org/python/#simplejson), it was very straightforward for parsing JSON when I last tried it and it claims to be compatible with Python 2.4.
I disagree that there's little point in distrusting Google. I wouldn't distrust them, but I'd verify the data you get from them. The reason that I'd actually use a JSON parser is right in your question:
> My own (brief) investigations suggest that JSON happens to be completely valid Python, with the exception of the "/" escape sequence — which GC doesn't appear to generate.
What makes you think that Google Code will never generate an escape sequence like that?
Parsing is a solved problem if you use the right tools. If you try to take shortcuts like this, you'll eventually get bitten by incorrect assumptions, or you'll do something like trying to hack together a parser with regex's and boolean logic when a parser already exists for your language of choice. | Running JSON through Python's eval()? | [
"",
"python",
"json",
""
] |
I want to be able to select a bunch of rows from a table of e-mails and group them by the from sender. My query looks like this:
```
SELECT
`timestamp`, `fromEmail`, `subject`
FROM `incomingEmails`
GROUP BY LOWER(`fromEmail`)
ORDER BY `timestamp` DESC
```
The query almost works as I want it — it selects records grouped by e-mail. The problem is that the subject and timestamp don't correspond to the most recent record for a particular e-mail address.
For example, it might return:
```
fromEmail: john@example.com, subject: hello
fromEmail: mark@example.com, subject: welcome
```
When the records in the database are:
```
fromEmail: john@example.com, subject: hello
fromEmail: john@example.com, subject: programming question
fromEmail: mark@example.com, subject: welcome
```
If the "programming question" subject is the most recent, how can I get MySQL to select that record when grouping the e-mails? | A simple solution is to wrap the query into a subselect with the ORDER statement *first* and applying the GROUP BY *later*:
```
SELECT * FROM (
SELECT `timestamp`, `fromEmail`, `subject`
FROM `incomingEmails`
ORDER BY `timestamp` DESC
) AS tmp_table GROUP BY LOWER(`fromEmail`)
```
This is similar to using the join but looks much nicer.
**Using non-aggregate columns in a SELECT with a GROUP BY clause is non-standard.** MySQL will generally return the values of the first row it finds and discard the rest. Any ORDER BY clauses will only apply to the returned column value, not to the discarded ones.
**IMPORTANT UPDATE**
Selecting non-aggregate columns used to work in practice but should not be relied upon. Per the [MySQL documentation](https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html) "this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is **free to choose any value** from each group, so **unless they are the same, the values chosen are indeterminate**."
As of [5.7.5](https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html) ONLY\_FULL\_GROUP\_BY is enabled by default so non-aggregate columns cause query errors (ER\_WRONG\_FIELD\_WITH\_GROUP)
As @mikep points out below the solution is to use [ANY\_VALUE()](https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value) from 5.7 and above
See
<http://www.cafewebmaster.com/mysql-order-sort-group>
<https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html>
<https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html>
<https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value> | As pointed in a reply already, the current answer is wrong, because the GROUP BY arbitrarily selects the record from the window.
If one is using MySQL 5.6, or MySQL 5.7 with `ONLY_FULL_GROUP_BY`, the correct (deterministic) query is:
```
SELECT incomingEmails.*
FROM (
SELECT fromEmail, MAX(timestamp) `timestamp`
FROM incomingEmails
GROUP BY fromEmail
) filtered_incomingEmails
JOIN incomingEmails USING (fromEmail, timestamp)
GROUP BY fromEmail, timestamp
```
In order for the query to run efficiently, proper indexing is required.
Note that for simplification purposes, I've removed the `LOWER()`, which in most cases, won't be used. | MySQL "Group By" and "Order By" | [
"",
"mysql",
"sql",
"group-by",
"sql-order-by",
"aggregate-functions",
""
] |
I'm quite experienced in PHP but I don't quite use `mod_rewrite` (although I should). All I want to ask is if it's possible to pass many variables through a single rewrite rule.
For example, is it possible to rewrite this:
```
localhost/test.php?id=1&name=test&var1=3
```
into this:
```
localhost/mysupertest/
```
and also use the same rewrite rule for different values?
```
localhost/test.php?id=5&name=another_name&var3=42
```
into
```
localhost/mysupertest/
```
I know it can be done using Ajax, cookie, session, or POST variables, but I really want to use GET variables. | I'm not exactly sure what you're asking for, but you probably should be using the `[QSA]` option for mod\_rewrite, which will append all the URL parameters from '`?`' onwards. For example:
```
RewriteRule ^mysupertest/? test.php [QSA]
```
Take a look at [this question](https://stackoverflow.com/questions/822421/match-question-mark-in-modrewrite-rule-regex) for more details. | Definitely possible. Something like this would do it:
```
RewriteRule test.php\?(.*)$ mysupertest/
```
However, you will lose your variables if you do that, as it's effectively the same thing as accessing localhost/mysupertest directly, with no query string data. If you want to keep the variables, perhaps in a REST-style url, you can use back-references to rewrite them. As John mentioned, a back-reference is simply a set of brackets, and whatever matches inside them becomes a variable in a numeric ordering scheme.
```
RewriteRule test.php\?id=(.*)&name=(.*)&var3=(.*) mysupertest/$1/$2/$3
```
With the above rule, accessing `test.php?id=567&name=test&var3=whatever` would be the same as accessing `mysupertest/567/test/whatever` | Can I pass matched variables to the new URL with mod_rewrite? | [
"",
"php",
"apache",
"url",
"mod-rewrite",
"get",
""
] |
Is there a JavaScript framework that allows to define a parsing grammar using JavaScript syntax, similar to the way [Irony](http://www.codeplex.com/irony) does it for C#? | I don't know much about how Irony works, but Chris Double has a library that lets you define grammars in JavaScript here: <http://www.bluishcoder.co.nz/2007/10/javascript-parser-combinators.html>. The code is [available on GitHub](https://github.com/doublec/jsparse).
It's a "parser combinator" library which means you combine parsers for each production in your grammar into a larger parser that parses the whole thing. Each "sub-grammar" is a just a function that you create by calling the library functions. | I have built a JavaScript Parsing **DSL** called **Chevrotain**.
**Source:** <https://github.com/SAP/chevrotain>
**Online Playground:** <http://sap.github.io/chevrotain/playground/>
It is **not** a Parser combinator like Irony, but it is very similar
as it allows you to **"define a parsing grammar using JavaScript syntax"**
without any code generation phase.
Using it is similar to "hand building" a recursive decent parser,
only without most of the headache such as:
* Lookahead function creation (deciding which alternative to take)
* Automatic Error Recovery.
* Left recursion detection
* Ambiguity Detection.
* Position information.
* ...
as Chevrotain handles that automatically. | Is there a framework for defining parsers in JavaScript? | [
"",
"javascript",
"parsing",
""
] |
i have written an application, but for some reason it keeps peaking at 100%. I ran a profile r on a few of the classes and a report show that isReset() and isRunning() seems to be called alot of times. Do you see anything wrong please inform me. thanks
Class 1 is the only class that uses the isReset() code so i hope this helps u guys in detecting the error
**Class 1**
```
package SKA;
/*
* ver 0.32 June 2009
*
* Bug Fix Release:
*
* Fixed Array resize
* Fixed Red Black Tree delete method
* Fixed Red Black Tree save/read option
* Update help file
*
*/
/*
* Additions:
* ver 0.30 May 2009
*
* Added Red Black Tree structure
* Added Delete method for canvases
* Added Array structure
* Added ability to recolor nodes.
* Added Bubble Sort Algorithm
* Added Insertion Sort Algorithm
* Added Shell Sort Algorithm
* Added Selection Sort Algorithm
* Added Quick Sort Algorithm
* Added Red Black Tree Search Algorithm
* Added Black Height Check Algorithm
* Bug fix in canvas - could not delete canvas properly
*/
// Additions:
/* ver 0.25 August 2004
* Added recursion in SkaExecutionPanel by adding SkaFunction
* and using desktop internal panes.
*
* Added binary tree node annotation - text and drawn
* Added subtree highlight feature to VizBinaryTreeNode using SkaRectangle
* Improved node highlighting and selection scheme in VizBinaryTrees/VizDS
* Added Binary tree save and read methods
* Added visual subtree deletion (has bug)
*
* Added ability to set breaks from within algorithm
* Added tooltip messages to SkaProgram/SkaFunction to show variable values
* Added simple value input and output methods to SkaProgram/SkaFunction
* Added SkaTriangle.
* Added Font Adjustment and Color scheme options to show on overhead projectors
*
* Found bug in SkaGraph deleteVertex (with edges)
*/
/* ver 0.16 October 15, 2001
Added Graph save and read methods.
Save is an instance method, while read is a class method.
Added circular layout for graphs,
Added fit/adjust graph layout to plate size method.
Added label editing for Binary Trees and Graphs.
SkaLabels (glyphs) now truncate the string displayed to the width specified
in the constructor.
*/
/* ver 0.15 July 21, 2001
Fixed Reset function in Execution using exceptions so that Ska Algorithms
can be run repeatedly without quitting the entire Ska System.
This also allows trying the same program on different data structures.
Problems with reset so far:
1. Reset message to user can appear much later.
I think this is an I/O sequencing problem and it should go away if
a message status GUI area is used.
2. Bound variable names remain afterwards,
e.g. Graph bound to G will still show name as G after
algorithm is interrupted.
Fixed problem with multiple input requests in 0.14 - by adding another
wait call which waits on before asking for input.
Also introduced trial orderly layout of canvas and program windows ,
which fixes problem in 0.14
*/
/* ver 0.14 July 18, 2001
Added subclasses of SkaProgram, so that multiple programs
can run simultaneously.
Problem - when multiple programs start, their windows overlay each other
Problem - Send DS to algorithm can get confused, if an algorithm
requests input while another is waiting on input or if
two algorithms request input at the same time
*/
/* ver 0.13
Added BinaryTree - does not have node value display yet.
Added arrows on edges of directed graphs
*/
/* ver 0.12
Added VizElementListener - separated from VizElement
Element Input menu item only highlights when input for that DS is requested
DS Input has been cleaned up
*/
/* ver 0.11
can ask user to select individual elements, e.g. vertices
removed standard java cloning code which wasn't being used anyway
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.border.BevelBorder;
import javax.swing.border.SoftBevelBorder;
// TimerQueue
public class SkaTest {
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int CANVAS_X = 100;
public static final int CANVAS_Y = 100;
public static final int CANVAS_FRAME_WIDTH = WIDTH+100;
public static final int CANVAS_FRAME_HEIGHT = HEIGHT + 100;
public static final int EXEC_WIDTH = 550;
public static final int EXEC_HEIGHT = 400;
static VizDSList dsList = new VizDSList();
static SkaCanvas canvas = new SkaCanvas(dsList);
static JFrame canvasFrame = new JFrame("Data Structure Canvas");
static JMenuBar menuBar = new JMenuBar();
static JMenu algorithmMenu = new JMenu("Algorithm");
static JMenu dsMenu = new JMenu("Create");
static JMenu helpMenu = new JMenu ("Help");
static JLabel status = new JLabel(" ");
static SkaProgram[] alg;
static JFrame execFrame[];
static SkaExecutionPanel execPanel[];
public static void setupFrames(int nAlgs) {
int i;
for (i=0; i < nAlgs; i++) {
// execFrame[i] = new JFrame("Execution Control Panel "+(i+1));
execFrame[i] = new JFrame();
execPanel[i] = new SkaExecutionPanel(execFrame[i]);
}
canvas.setMinimumSize(new Dimension(WIDTH, HEIGHT));
canvasFrame.setSize(CANVAS_FRAME_WIDTH, CANVAS_FRAME_WIDTH);
canvasFrame.getContentPane().setLayout(new BorderLayout(10,7));
// canvasFrame.getContentPane().setPreferredSize(new Dimension(WIDTH, HEIGHT));
canvasFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// canvas.setMinimumSize(new Dimension(WIDTH, HEIGHT));
for (i=0; i < nAlgs; i++) {
execFrame[i].setSize(EXEC_WIDTH, EXEC_HEIGHT);
// execFrame[i].getContentPane().setLayout(new BorderLayout(10,7));
execFrame[i].addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
execPanel[i].setBorder(new SoftBevelBorder(BevelBorder.RAISED));
// execFrame[i].setContentPane(execPanel[i]);
execFrame[i].getContentPane().add("Center", execPanel[i]);
// execFrame[i].setLocation(CANVAS_X +CANVAS_FRAME_WIDTH, CANVAS_Y + i*EXEC_HEIGHT);
execFrame[i].setLocation(CANVAS_X +CANVAS_FRAME_WIDTH + i*30, CANVAS_Y + i*50);
}
canvas.setBorder(new SoftBevelBorder(BevelBorder.RAISED));
canvasFrame.getContentPane().add("Center", new JScrollPane(canvas) );
// canvasFrame.getContentPane().add("Center", new JScrollPane(canvas, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS) );
canvasFrame.getContentPane().add("South", status);
canvasFrame.setLocation(CANVAS_X, CANVAS_Y);
JMenu fileMenu = new JMenu("File");
JMenuItem quitItem = new JMenuItem("Quit");
//TODO Add quit listener
quitItem.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent arg0) {
//System.exit(0);
int again = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit system", "Exiting", JOptionPane.YES_NO_OPTION);
if (again == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
}
);
fileMenu.add(quitItem);
menuBar.add(fileMenu);
menuBar.add(algorithmMenu);
// menuBar.add(dsMenu);
menuBar.add(helpMenu);
JMenuItem help = new JMenuItem ("Help Contents");
//help.setMnemonic(KeyEvent.VK_H);
//TODO Fix this method
help.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, ActionEvent.CTRL_MASK));
help.addActionListener(new ActionListener()
{
/*
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Alot of the functionality have not yet been included in this version\nCurrently working on the automation features now!", "SKA 0.2 Beta", JOptionPane.WARNING_MESSAGE);
}
*/
public void actionPerformed(ActionEvent arg0) {
try {
Runtime.getRuntime().exec("hh.exe C:/ska.chm");
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "File not found", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
JMenuItem about = new JMenuItem ("About SKA");
about.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "SKA Version 0.1 Beta");
}
});
helpMenu.add(help);
helpMenu.add(about);
canvasFrame.setJMenuBar(menuBar);
}
/** The create menu item */
public static void createProgram(int i) {
JMenuItem algItem;
switch (i) {
case 0 :
alg[0] = new RedBlackValidate(canvas, execPanel[0]);
execFrame[0].setTitle("Validate Algorithm");
System.out.println("Validate Algorithm");
algItem = new JMenuItem("Validate Algorithm");
algorithmMenu.add(algItem);
break;
/* case 0 :
alg[0] = new BreadthFirstSearch(canvas, execPanel[0]);
execFrame[0].setTitle("BFS Graph Algorithm");
// System.out.println("BreadthFirstSearch");
algItem = new JMenuItem("BFS Graph Algorithm");
algorithmMenu.add(algItem);
break;
case 1:
alg[1] = new LevelOrderAlgorithm(canvas, execPanel[1]);
execFrame[1].setTitle("Level Order Tree Algorithm");
System.out.println("LevelOrderAlgorithm");
algItem = new JMenuItem("Level Order Tree Algorithm");
algorithmMenu.add(algItem);
break;
case 2:
alg[2] = new BinarySearchTreeAlgRecursive(canvas, execPanel[2]);
execFrame[2].setTitle("BinaryTreeSearchRec Algorithm");
System.out.println("BinaryTreeSearchRec Algorithm");
algItem = new JMenuItem("BinaryTreeSearchRec Algorithm");
algorithmMenu.add(algItem);
break;
case 3:
alg[3] = new BinarySearchTreeAlgIterative(canvas, execPanel[3]);
execFrame[3].setTitle("BinaryTreeSearchIter Algorithm");
System.out.println("BinaryTreeSearchIter Algorithm");
algItem = new JMenuItem("BinaryTreeSearchIter Algorithm");
algorithmMenu.add(algItem);
break;
case 4:
alg[4] = new RebBlackTreeSearch (canvas, execPanel[4]);
execFrame[4].setTitle("Red Black Search Algorithm");
System.out.println("Red Black Search Algorithm");
algItem = new JMenuItem("Red Black Search Algoithm Algorithm");
algorithmMenu.add(algItem);
break;
case 5:
alg[5] = new ArrayInsertionSortAlg (canvas, execPanel[5]);
execFrame[5].setTitle("Array Insertion Sort Algorithm");
System.out.println("Array Insertion Sort");
algItem = new JMenuItem("Array Insertion Sort Algorithm");
algorithmMenu.add(algItem);
break;
case 6:
alg[6] = new ArraySelectionSortAlg (canvas, execPanel[6]);
execFrame[6].setTitle("Array Selection Sort Algorithm");
System.out.println("Array SelectionSearch");
algItem = new JMenuItem("Array Selection Sort Algorithm");
algorithmMenu.add(algItem);
break; */
default:
break;
}
}
public static void main(String args[]) {
int i, nAlgs = 1; //nAlgs = 7;
alg = new SkaProgram[nAlgs];
execPanel = new SkaExecutionPanel[nAlgs];
execFrame = new JFrame[nAlgs];
// canvas.setDebugGraphicsOptions(DebugGraphics.BUFFERED_OPTION);
setupFrames(nAlgs);
canvasFrame.setVisible(true);
for (i=0; i < alg.length; i++) {
createProgram(i);
execFrame[i].setVisible(true);
alg[i].start();
alg[i].displayAlgorithm();
}
while (true) {
for (i=0; i < alg.length; i++)
if (execPanel[i].isReset()) {
alg[i].terminate();
createProgram(i);
alg[i].start();
execPanel[i].unreset();
}
}
}
} // End class SkaTest
```
**Class 2**
```
package SKA;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Stack;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
@SuppressWarnings("serial")
public
class SkaExecutionPanel extends JDesktopPane {
public static final int EXEC_WIDTH = SkaTest.EXEC_WIDTH-100;
public static final int EXEC_HEIGHT = SkaTest.EXEC_HEIGHT-50;
boolean run = false, pause = true, step = false, reset = false;
JToolBar toolbar = new JToolBar();
JTextArea textOutputArea = new JTextArea();
SkaProgram prog;
Stack<SkaFunction> functionStack = new Stack<SkaFunction>();
SkaFunction currentFunction = null;
int level = 0, in = 30;
public void doCall(String[] subAlg, String subAlgName) {
doCall(subAlg, subAlgName, false); // make non-icon default
}
public void doCall(String[] subAlg, String subAlgName, boolean iconify) {
if (currentFunction != null)
functionStack.push(currentFunction);
currentFunction = new SkaFunction(this, subAlg, subAlgName, iconify);
add(currentFunction, new Integer(1));
currentFunction.setBounds(level*in,level*in,EXEC_WIDTH, EXEC_HEIGHT);
// currentFunction.setBounds(level*in,level*in,EXEC_WIDTH-(level+1)*in, EXEC_HEIGHT-(level+1)*in);
currentFunction.setVisible(true);
level++;
}
public void doReturn() {
if (currentFunction == null)
return;
if (currentFunction.makeIconWhenDone()) {
getDesktopManager().iconifyFrame(currentFunction);
// currentFunction.setIcon(true);
currentFunction.setIconifiable(true);
}
else
currentFunction.setVisible(false);
currentFunction = (SkaFunction) functionStack.pop();
level--;
}
public void displayAlgorithm(String[] a) {
doCall(a, "main");
}
public void displayAlgorithm(String[] a, String aname) {
doCall(a, aname);
}
public void setControlsEnabled(boolean b) {
toolbar.setEnabled(b);
}
class RunAction extends AbstractAction {
RunAction() {
super("run");
}
public void actionPerformed(ActionEvent e) {
run = true; pause = false; step = false;
}
}
class StepAction extends AbstractAction {
StepAction() {
super("step");
}
public void actionPerformed(ActionEvent e) {
run = false; pause = false; step = true;
}
}
class PauseAction extends AbstractAction {
PauseAction() {
super("pause");
}
public void actionPerformed(ActionEvent e) {
pause = true;
// System.out.print("breaks");
// for (int i=0; i<breaks.length; i++)
// System.out.print("[" +i+ "]=" + breaks[i].toString() + " ");
// System.out.println("");
}
}
class ResetAction extends AbstractAction {
ResetAction() {
super("reset");
putValue(Action.SHORT_DESCRIPTION, "stop program and reset state to begining");
}
public void actionPerformed(ActionEvent e) {
run = false; pause = true; step = false;
// should also restart SkaProgram
reset = true;
if (currentFunction != null) currentFunction.reset();
/*
JInternalFrame[] frames = getAllFrames();
for (int i = 0; i < frames.length; i++) {
// frames[i].dispose();
if (frames[i].isIcon())
frames[i].dispose();
}
*/
}
}
JComboBox speedControl;
String speedNames[] = { "slow", "normal", "fast", "very fast" };
int speeds[] = {4000, 2000, 1000, 500} ; // milliseconds
int speed = speeds[1];
private void initSpeedMenu() {
speedControl = new JComboBox(speedNames);
// speedControl.setMaximumRowCount(3);
speedControl.addItemListener(
new ItemListener() {
public void itemStateChanged( ItemEvent e) {
speed = speeds[speedControl.getSelectedIndex()];
}
}
);
speedControl.setSelectedIndex(1);
speedControl.setMaximumSize(speedControl.getPreferredSize());
speedControl.setToolTipText("execution speed");
}
SkaExecutionPanel(JFrame frame) {
initSpeedMenu();
toolbar.add(new RunAction());
toolbar.add(new StepAction());
toolbar.add(new ResetAction());
toolbar.add(new PauseAction());
toolbar.addSeparator();
toolbar.add(speedControl);
// frame.getContentPane().setLayout(new BorderLayout(10,7));
// makeTable();
frame.getContentPane().add("North", toolbar);
Font f = new Font("SansSerif", Font.BOLD, 14);
textOutputArea.setFont(f);
frame.getContentPane().add("South", new JScrollPane(textOutputArea));
// frame.getContentPane().add(this, BorderLayout.CENTER)
// frame.getContentPane().add("Center", toolbar, BorderLayout.NORTH);
// setSize(300,250);
// add toolbar, table, set layout, sizes
}
// public void setAlgorithm(SkaProgram p) {
// prog = p;
// sendAlgorithm(p.getPseudocode());
// }
public int getSpeed() { return speed;
}
public boolean isRunning() { return run;
}
public boolean isPaused() { return pause;
}
public boolean isStepping() { return step;
}
public boolean isReset() { return reset;
}
public void pause() { pause = true;
}
public void unreset() { reset = false;
}
public void aboutToWait() {
currentFunction.aboutToWait();
}
public void doneWait() {
currentFunction.doneWait();
}
public void showToolTipValue(String s) {
currentFunction.showToolTipValue(s);
}
public void showAlgLineBreak(int i) {
currentFunction.showAlgLineBreak(i);
}
public void showAlgLine(int i) {
currentFunction.showAlgLine(i);
}
public void displayText(String s) {
textOutputArea.append(s); // +"\n" add newline?
}
} // End class SkaExecutionPanel
``` | The problem doesn't seem to be in the methods which are being used a lot, it's how frequently you call them which appears to be why they are showing up so frequently. I'd check for all of the calls, see if any are superfluous then go to the third most time consuming method. After that, I would check my algorithms for being particularly intensive. Also, check all method calls and make sure they're not being run without need.
I know this isn't solving the problem itself, but its a start with the information given.
EDIT: The while loop is an infinite loop causing a for loop to run in which every item in an array has been checked to see if its been reset. You can replace this with an observer pattern where when an object is reset, it notifies the observing object which then performs that set of steps. This way you don't have an infinite loop and you cut down on the usage of .isReset(). This is in the main method of Class 1.
Edit 2: Here's the example of an [implementation of the observer](http://en.wikipedia.org/wiki/Observer_pattern) pattern which is on wikipedia. | > "*How do I start optimising my Java code?*"
You start by [profiling](http://java-source.net/open-source/profilers) it first. | How do I start optimising my Java code? - CPU is at 100% | [
"",
"java",
"class",
"function",
"jframe",
"jpanel",
""
] |
How to navigate from one Activity screen to another Activity screen? In the first screen I'm having one button if I click the button it has to move to another Activity screen. | ```
OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(action));
}
};
Button button = (Button) findViewById(id);
button.setOnClickListener(onClickListener);
``` | The most trivial case (called from activity):
```
startActivity(new Intent(this, ActivityToLaunch.class));
```
More details here: <http://developer.android.com/guide/topics/fundamentals.html> | How to navigate from one screen to another screen | [
"",
"java",
"android",
"android-activity",
""
] |
I have filled `List<Object1>` Object 1 contain 2 fields (int id & string name)
Also i Have `IEnumerable<Object2>` Generated by linq2sql. With fields (id, name)
i need to get items from `List<Object1>` which **Id's** are absent in `IEnumerable<Object2>`.
by **Key Field = id**
(like where in in sql..)
i used code like
```
IEnumerable Object2
List<Object1> excepted = Object2.Where(t => obj1.Contains == t.Id);
```
Thank you! | How about:
```
HashSet<string> knownIds = new HashSet<string>(list2.Select(x => x.Id));
var exceptions = list1.Where(x => !knownIds.Contains(x.Id));
```
As Earwicker rightly says, this will just give an `IEnumerable<Object1>` - if you need a list, change the second line to:
```
var exceptions = list1.Where(x => !knownIds.Contains(x.Id)).ToList();
``` | I'm surprised nobody has suggested join:
```
var excepted = (from o1 in List1
join o2 in List2
on o1.Id equals o2.Id into j
where !j.Any() // j is empty
select o1
).ToList();
```
Perhaps marginally less as efficient than Jon's HashSet solution, but query syntax is fun. | Linq where in between IENumerable and List<> | [
"",
"c#",
".net",
"linq",
""
] |
I am using matplotlib in a django app and would like to directly return the rendered image.
So far I can go `plt.savefig(...)`, then return the location of the image.
What I want to do is:
```
return HttpResponse(plt.renderfig(...), mimetype="image/png")
```
Any ideas? | Django's `HttpResponse` object supports file-like API and you can pass a file-object to savefig.
```
response = HttpResponse(mimetype="image/png")
# create your image as usual, e.g. pylab.plot(...)
pylab.savefig(response, format="png")
return response
```
Hence, you can return the image directly in the `HttpResponse`. | what about [cStringIO](http://docs.python.org/library/stringio.html#module-cStringIO)?
```
import pylab
import cStringIO
pylab.plot([3,7,2,1])
output = cStringIO.StringIO()
pylab.savefig('test.png', dpi=75)
pylab.savefig(output, dpi=75)
print output.getvalue() == open('test.png', 'rb').read() # True
``` | Returning Matplotlib image as string | [
"",
"python",
"django",
"matplotlib",
""
] |
Can I check the number of values in an array,
for example...
```
$abc=array();
$abc[0]="asd";
$abc[1]="sadaf";
$abc[2]="sfadaf";
```
I want to check and store it(2) in a variable that array abc[] exists till $abc[2]..
Thanks | Use [`count`](http://docs.php.net/count) or [`sizeof`](http://docs.php.net/sizeof) for the total number of values or [`array_count_values`](http://docs.php.net/array_count_values) to count the frequency of each value. | There is [count](https://www.php.net/manual/en/function.count.php) function. | PHP - Check how many values in array | [
"",
"php",
"arrays",
""
] |
python decimal comparison
```
>>> from decimal import Decimal
>>> Decimal('1.0') > 2.0
True
```
I was expecting it to convert 2.0 correctly, but after reading thru [PEP 327](http://www.python.org/dev/peps/pep-0327) I understand there were some reason for not implictly converting float to Decimal, but shouldn't in that case it should raise TypeError as it does in this case
```
>>> Decimal('1.0') + 2.0
Traceback (most recent call last):
File "<string>", line 1, in <string>
TypeError: unsupported operand type(s) for +: 'Decimal' and 'float'
```
so does all other operator / - % // etc
so my questions are
1. is this right behavior? (not to raise exception in cmp)
2. What if I derive my own class and
right a float converter basically
Decimal(repr(float\_value)), are
there any caveats? my use case
involves only comparison of prices
System details: Python 2.5.2 on Ubuntu 8.04.1 | Re 1, it's indeed the behavior we designed -- right or wrong as it may be (sorry if that trips your use case up, but we were trying to be general!).
Specifically, it's long been the case that every Python object could be subject to inequality comparison with every other -- objects of types that aren't really comparable get arbitrarily compared (consistently in a given run, not necessarily across runs); main use case was sorting a heterogeneous list to group elements in it by type.
An exception was introduced for complex numbers only, making them non-comparable to anything -- but that was still many years ago, when we were occasionally cavalier about breaking perfectly good user code. Nowadays we're much stricter about backwards compatibility within a major release (e.g. along the `2.*` line, and separately along the `3.*` one, though incompatibilities *are* allowed between 2 and 3 -- indeed that's the whole point of *having* a `3.*` series, letting us fix past design decisions even in incompatible ways).
The arbitrary comparisons turned out to be more trouble than they're worth, causing user confusion; and the grouping by type can now be obtained easily e.g. with a `key=lambda x: str(type(x))` argument to `sort`; so in Python 3 comparisons between objects of different types, unless the objects themselves specifically allow it in the comparison methods, does raise an exception:
```
>>> decimal.Decimal('2.0') > 1.2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: Decimal() > float()
```
In other words, in Python 3 this behaves exactly as you think it should; but in Python 2 it doesn't (and never will in any Python `2.*`).
Re 2, you'll be fine -- though, look to [gmpy](http://code.google.com/p/gmpy/) for what I hope is an interesting way to convert doubles to infinite-precision fractions through Farey trees. If the prices you're dealing with are precise to no more than cents, use `'%.2f' % x` rather than `repr(x)`!-)
Rather than a subclass of Decimal, I'd use a factory function such as
```
def to_decimal(float_price):
return decimal.Decimal('%.2f' % float_price)
```
since, once produced, the resulting Decimal is a perfectly ordinary one. | The greater-than comparison works because, by default, it works for all objects.
```
>>> 'abc' > 123
True
```
`Decimal` is right merely because it correctly follows the spec. Whether the spec was the correct approach is a separate question. :)
Only the normal caveats when dealing with floats, which briefly summarized are: beware of edge cases such as negative zero, +/-infinity, and NaN, don't test for equality (related to the next point), and count on math being slightly inaccurate.
```
>>> print (1.1 + 2.2 == 3.3)
False
``` | python decimal comparison | [
"",
"python",
"comparison",
"decimal",
""
] |
I am creating a windows application using VB.Net and this application will take a SQl create .sql file as a parameter and will return all fields and their data types inside in a list or array.
Example:
```
USE [MyDB] GO /****** Object: Table [dbo].[User] Script Date: 07/07/2009 10:16:48 ******/
SET
ANSI_NULLS ON GO
SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[User]( [UserId] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [MiddleName]
[varchar](50) COLLATE SQL_Latin1_General_CP1_CI_A
```
Should Return:
UserId int, FirstName string, MiddleName string
I want to do this by any way, pure vb.net code or using RegEx.
Anyone knows the fastest way to finish this? | First, what flavor of SQL are you using? Second, the [syntax](http://tinyurl.com/mcqsav) for `CREATE TABLE` can be fairly "detailed". Are you dealing with a smaller subset of the general syntax that might make approaching this problem simpler?
But rather than trying to parse the statement, the fastest way might be having a trash database that you can execute the `CREATE TABLE` statement on, and then extracting the column names and types via
```
SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='MyCreatedTable'
```
(I am assuming SQL Server here.)
Thusly,
```
string createTableCommandText; // "CREATE TABLE MyCreatedTable..."
using(var connection = new SqlConnection(connectionString)) {
connection.Open();
var createCommand = connection.CreateCommand();
createCommand.CommandText = createTableCommandText;
createCommand.ExecuteNonQuery();
var schemaCommand = connection.CreateCommand();
schemaCommand.CommandText = "SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='MyCreatedTable'";
var reader = schemaCommand.ExecuteReader();
while(reader.Read()) {
Console.WriteLine(String.Format("{0}|{1}", reader["COLUMN_NAME"], reader["DATA_TYPE"]));
}
var deleteCommand = connection.CreateCommand();
deleteCommand.CommandText = "DROP TABLE MyCreatedTable";
deleteCommand.ExecuteNonQuery();
}
```
Sorry that it's in C#. I am not fluent enough with VB to write approximately correct code without a compiler at my fingertips. | One option is to create an in-memory database using SMO, execute the script, and then iterate through the table columns.
[Here](http://davidhayden.com/blog/dave/archive/2006/05/07/2939.aspx) is an article that does the opposite but you should be able to start down the path with it.
Disclosure: I think using splits and regex is probably a better solution but I figured you would get many of this so I thought I would throw in an alternate. After all, that is what this site is about | How to extract all fields from create sql statment using .Net? | [
"",
".net",
"sql",
"vb.net",
"regex",
""
] |
Given a string that isn't too long, what is the best way to read it line by line?
I know you can do:
```
BufferedReader reader = new BufferedReader(new StringReader(<string>));
reader.readLine();
```
Another way would be to take the substring on the eol:
```
final String eol = System.getProperty("line.separator");
output = output.substring(output.indexOf(eol + 1));
```
Any other maybe simpler ways of doing it? I have no problems with the above approaches, just interested to know if any of you know something that may look simpler and more efficient? | You can also use the `split` method of String:
```
String[] lines = myString.split(System.getProperty("line.separator"));
```
This gives you all lines in a handy array.
I don't know about the performance of split. It uses regular expressions. | There is also [`Scanner`](http://java.sun.com/javase/6/docs/api/java/util/Scanner.html). You can use it just like the `BufferedReader`:
```
Scanner scanner = new Scanner(myString);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// process the line
}
scanner.close();
```
I think that this is a bit cleaner approach that both of the suggested ones. | Read String line by line | [
"",
"java",
"string",
""
] |
The cms I'm currently working with only supports live editing of data (news, events, blogs, files, etc), and I've been asked to build a system that supports drafting (with moderation) + revision history system. The cms i'm using was developed in house so I'll probably have to code it from scratch.
At every save of a item it would create a snapshot of the data into a "timeline". The same would go for drafts. Automated functionality would pull the timeline draft into the originating record when required.
The timeline table would store the data type & primary key, seralised version of the data + created/modified dates + a drafting date (if in the future)
I've had a quick look around at other systems, but I've yet to improve from my current idea.
I'm sure someone has already built a system like this and I would like to improve on my design before I start building. Any good articles/resources would help as well.
Thanks | I think using serialize() to encode each row into a single string, then saving that to a central database may be a solution.
You'd have your 'live' database with relevant tables etc., but when you edit or create something (without clicking publish) it would instead of being saved in your main table go into a table like:
```
id - PRI INT
date - DATETIME
table - VARCHAR
table_id - INT
type - ENUM('UNPUBLISHED','ARCHIVED','DELETED');
data - TEXT/BLOB
```
...with the type set to 'unpublished' and the table and table\_id stored so it knows where it is from. Clicking publish would then serialize the current tables contents, store it in the above table set to 'archive', then read out the latest change (marked as unpublished) and place this in the database. The same could also apply to deleting rows - place them in and mark as 'deleted' for potential undelete/rollback functionality.
It'll require quite a lot of legwork to get it all working, but should provide full publish/unpublish and rollback facilities. Integrated correctly into custom database functions it may also be possible to do all this transparently (from a SQL point of view).
I have been planning on implementing this as a solution to the same problem you appear to be have, but it's still theoretical from my point of view but I reckon the idea is sound. | This sounds very wiki-like to me. You may want to look at [MediaWiki](http://www.mediawiki.org/), the system used by Wikipedia, which also uses PHP and MySQL. | resources for designing a good content publishing system | [
"",
"php",
"mysql",
"content-management-system",
""
] |
Can anyone see anything wrong with this login script:
```
public function login($username, $pass, $remember) {
// check username and password with db
// else throw exception
$connect = new connect();
$conn = $connect->login_connect();
// check username and password
$result = $conn->query("select * from login where
username='".$username."' and
password=sha1('".$pass."')");
if (!$result) {
throw new depException('Incorrect username and password combination. Please try again.');
} else {
echo $username, $pass;
}
```
To explain:
At the moment the script is allowing anything through. In other words the query is returning true for any username and password that are passed to it.
I've put the echo statement just as a check - obviously the script would continue in normal circumstances!
I know that the connect class and `login_connect` method are working because I use them in a register script that is working fine. depException is just an extension of the Exception class.
The function login() is part of the same class that contains register() that is working fine.
I know that the two variables ($username and $pass) are getting to the function because the echo statement is outputting them accurately. (The $remember variable is not needed for this part of the script. It is used later for a remember me process).
I'm stumped. Please help!
## UPDATE
Thanks for those responses. I was getting confused with what the query was returning. The complete script does check for how many rows are returned and this is where the checking should have been done. Everything is now working EXCEPT for my remember me function. Perhaps someone could help with that?!?! Here is the full script:
```
public function login($username, $pass, $remember) {
// check username and password with db
// else throw exception
$connect = new connect();
$conn = $connect->login_connect();
// check username and password
$result = $conn->query("select * from login where
username='".$username."' and
password=sha1('".$pass."')");
if (!$result) {
throw new depException('Incorrect username and password combination. Please try again.');
}
if ($result->num_rows>0) {
$row = $result->fetch_assoc();
//assign id to session
$_SESSION['user_id'] = $row[user_id];
// assign username as a session variable
$_SESSION['username'] = $username;
// start rememberMe
$cookie_name = 'db_auth';
$cookie_time = (3600 * 24 * 30);*/ // 30 days
// check to see if user checked box
if ($remember) {
setcookie ($cookie_name, 'username='.$username, time()+$cookie_time);
}
// If all goes well redirect user to their homepage.
header('Location: http://localhost/v6/home/index.php');
} else {
throw new depException('Could not log you in.);
}
}
```
Thanks very much for your help.
UPDATE 2!
Thanks to your help I've got the main part of this script working. However, the remember me bit at the end still doesn't want to work.
Could someone give me a hand to sort it out?
$username, $pass and $remember are all short variable names that I assigned before passing them to the function to save writing $\_POST['username'] etc. everytime. $remember refers to a checkbox. | What does `$conn->query()` return, a MySQL resource object like [`mysql_query()`](http://us.php.net/manual/en/function.mysql-query.php) does? If so then it'll always compare "true". `mysql_query()` only returns `FALSE` if the query completely fails, like it has a syntax error or a table doesn't exist.
To check if you got any results you need to try to fetch a row from the result set and see if you get anything, via whatever your equivalent of [`mysql_fetch_row()`](http://us.php.net/manual/en/function.mysql-fetch-row.php) is.
**Important:** Your script is vulnerable to [SQL injection attacks](http://us.php.net/manual/en/security.database.sql-injection.php), or even just odd usernames like `o'neil` with an apostrophe. You should escape all variables in a query with [`mysql_real_escape_string()`](http://us.php.net/manual/en/function.mysql-real-escape-string.php) (or equivalent) to make sure your query doesn't get messed up by special characters. Or, even better, use prepared statements which look like
```
select * from login where username=? and password=sha1(?)
```
---
**Re: UPDATE**
Variables from a form are available via either `$_GET` or `$_POST`, depending on which method was used to submit the form. Try `if (isset($_POST['remember']))` to see if that check box was checked.
**Important:** I see that you tried to use a bare `$remember` to see if the check box was checked. That suggests to me that you are trying to take advantage of the [`register_globals`](https://www.php.net/manual/en/security.globals.php) feature in PHP which makes your GET and POST variables accessible via regular variable names. If that is the case you should heed the warning in the PHP manual!
> ## WARNING
>
> [`register_globals`] has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.
Use `$_GET` and `$_POST` instead. I could tell you how to make `if ($remember)` work, actually, but given the inherent evil-ness of `register_globals` I'm not gonna! ;-) | Your query is open for [sql-injections](https://www.php.net/manual/en/security.database.sql-injection.php)...
> SELECT \*
> FROM users
> WHERE
> username = '**' OR 'a' = 'a**'
> AND password =
> sha1('**guessAnyPassword**')
I'd also check your result, and base the action on how many records were returned.
```
if (mysql_num_rows($result) > 0)
``` | php login script - remember me | [
"",
"php",
"mysql",
"oop",
"login-script",
""
] |
We have a content delivery system that delivers many different content types to devices.
All the content is stored in a database with a `contentID` & `mediaTypeID`.
For this example lets assume the `MediaType` can be one of these 2 but in reality theres many more of them.
```
Gif
MP3
```
Because the content is stored in different places based on mediatype and requires different headers to be sent, theres a big nasty piece of legacy code that essentially switches on each mediatype and sets the correct parameters. \*I'd like to change this into a more generic implementation. So heres what I've got so far in my wireframe
```
public interface IContentTypeDownloader
{
MemoryStream GetContentStream();
Dictionary<string, string> GetHeaderInfo();
}
public class GifDownloader : IContentTypeDownloader
{
public MemoryStream GetContentStream(int contentID)
{
//Retrieve Specific Content gif
}
public Dictionary<string, string> GetHeaderInfo()
{
//Retrieve Header Info Specific To gifs
}
}
public class MP3Downloader : IContentTypeDownloader
{
public MemoryStream GetContentStream(int contentID)
{
//Retrieve Specific Content mp3
}
public Dictionary<string, string> GetHeaderInfo()
{
//Retrieve Header Info Specific To mp3s
}
}
```
Which all seems sensible... Until I get to the Manager Class.
```
public class ContentManager<T> where T : IContentTypeDownloader
{
public int ContentID { get; set; }
public MemoryStream GetContent()
{
IContentTypeDownloader ictd = default(T);
return ictd.GetContentStream(this.ContentID);
}
... etc
}
```
The problem is, I still need to initialise this type with the specific IContentTypeDownloader for that mediaTypeID.
And I'm back to square 1, with a situation like
```
if(mediaTypeID == 1)
ContentManager<GifDownloader> cm = new ContentManager<GifDownloader>();
else if (mediaTypeID == 2)
ContentManager<MP3Downloader> cm = new ContentManager<MP3Downloader>();
```
etc...
Anyone any idea on how to make this last decision generic based on the value of the `mediaTyepID` that comes out of the Database | I duno if you can generify it any further than what you have already.
Perhaps creating a factory class which just returns you the correct Interface based on whatever media type would be a neater solution i.e.
```
public static class MediaInterfaceFactory
{
public static IContentTypeDownloader Create(int mediaId)
{
switch (mediaId)
{
case 1:
return new GifDownloader();
case 2:
return new Mp3Downloader();
}
}
``` | I think I may go about this like that:
* Define an attribute you place on your specific content type downloaders:
[MediaType(ID = 1)]
* Upon startup scan your assembly and set up a dictionary of style contentID -> instance of the content type downloader associated with the id (you figured that out with the attribute)
* Have your content type downloaders some method like IContentTypeDownloader Clone();
Then your code should be reduced to
```
downloader = dictionary[mediaType].Clone();
```
With a DI Container of your choice you may be able to replace the dictionary and scanning with e.g. a convention-based configuration. | How do I use C# Generics for this implementation when the Generic Decision is based on a DB Value | [
"",
"c#",
".net",
"generics",
"interface",
""
] |
In my new job more people are using Python than Perl, and I have a very useful API that I wrote myself and I'd like to make available to my co-workers in Python.
I thought that a compiler that compiled Perl code into Python code would be really useful for such a task. Before trying to write something that parsed Perl (or at least, the subset of Perl that I've used in defining my API), I came across [bridgekeeper](http://www.crazy-compilers.com/bridgekeeper/) from a consultancy.
It's almost certainly not worth the money for me to engage a consultancy to translate this API, but that's a really interesting tool.
Does anyone know of a compiler that will parse (or try to parse!) Perl5 code and compile it into Python? If there isn't such a thing, how should I start writing a simple compiler that parses my object-oriented Perl code and turns it into Python? Is there an ANTLR or YACC grammar that I can use as a starting point?
Edit: I found [perl.y](http://cpansearch.perl.org/src/NWCLARK/perl-5.8.8/perly.y), which might be a starting point if I were to roll my own compiler. | James,
I recommend you to just rewrite the module in Python, for several reasons:
1. Parsing Perl is DARN HARD. Unless this is an important and desirable exercise for you, you'll find yourself spending *much* more time on the translation than on useful work.
2. By rewriting it, you'll have a great chance to practice Python. Learning is best done by doing, and having a task you really need done is a great boon.
3. Finally, Python and Perl have quite different philosophies. To get a more Pythonic API, it's best to just rewrite it in Python. | I think you should rewrite your code. The quality of the results of a parsing effort depends on your Perl coding style.
I think the quote below sums up the theoretical side very well.
From Wikipedia:[Perl in Wikipedia](http://en.wikipedia.org/wiki/Perl)
> Perl has a Turing-complete grammar because parsing can be affected by run-time code executed during the compile phase.[25] Therefore, Perl cannot be parsed by a straight Lex/Yacc lexer/parser combination. Instead, the interpreter implements its own lexer, which coordinates with a modified GNU bison parser to resolve ambiguities in the language.
>
> It is often said that "Only perl can parse Perl," meaning that only the Perl interpreter (perl) can parse the Perl language (Perl), but even this is not, in general, true. Because the Perl interpreter can simulate a Turing machine during its compile phase, it would need to decide the Halting Problem in order to complete parsing in every case. It's a long-standing result that the Halting Problem is undecidable, and therefore not even Perl can always parse Perl. Perl makes the unusual choice of giving the user access to its full programming power in its own compile phase. The cost in terms of theoretical purity is high, but practical inconvenience seems to be rare.
>
> Other programs that undertake to parse Perl, such as source-code analyzers and auto-indenters, have to contend not only with ambiguous syntactic constructs but also with the undecidability of Perl parsing in the general case. Adam Kennedy's PPI project focused on parsing Perl code as a document (retaining its integrity as a document), instead of parsing Perl as executable code (which not even Perl itself can always do). It was Kennedy who first conjectured that, "parsing Perl suffers from the 'Halting Problem'."[26], and this was later proved.[27] | Are there programmatic tools for Perl to Python conversion? | [
"",
"python",
"perl",
"parsing",
"compilation",
""
] |
I would like to know if in C++ standard libraries there is any **gaussian distribution** number generator, or if you have any code snippet to pass.
Thanks in advance. | The standard library does not. Boost.Random does, however. I'd use that if I were you. | C++ Technical Report 1 adds support for random number generation. So if you're using a relatively recent compiler (visual c++ 2008 GCC 4.3), chances are that it is available out of the box.
See [here](http://www.johndcook.com/cpp_TR1_random.html) for sample usage of `std::tr1::normal_distribution` (and many more). | C++: generate gaussian distribution | [
"",
"c++",
"gaussian",
"normal-distribution",
""
] |
I am trying to mask a password in Java. Sun java has suggested a way to mask a password as follows.
[Masking a password](http://java.sun.com/developer/technicalArticles/Security/pwordmask/)
It uses a simple way to do that.
```
public void run () {
stop = true;
while (stop) {
System.out.print("\010*");
try {
Thread.currentThread().sleep(1);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
```
But this approach has several drawbacks.
1. If the user uses the arrow keys + delete keys the password gets revealed.
2. If the user accidentally press 2 keys at the same time (Extremely high typing speed) some characters does not get masked.
Do you guys think of any way that can get a 100% correct masking? | Use [Console.readPassword()](http://java.sun.com/javase/6/docs/api/java/io/Console.html#readPassword()). | You can now use [System.console](http://java.sun.com/javase/6/docs/api/java/lang/System.html)();
```
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
char [] password = c.readPassword("Enter your password: ");
``` | How to mask a password in Java 5? | [
"",
"java",
"passwords",
"masking",
""
] |
I need to have a Java EE project generate a WAR file automatically - preferably exploded - as opposed to choosing Export -> War file.
I have played with the various server definitions but have not been able to get either the Java EE preview or the HTTP server to work, and before installing each of the external container specific servers I'd like to hear if anybody has made this work.
So, question is: Which steps to take to have a WAR deployment automatically created and maintained by Eclipse?
---
EDIT: This is Eclipse 3.5 Java EE, and it is a Dynamic Web project in Eclipse. I want the WAR file/tree to be easily copyable to a network drive to be accessible for the target host. It runs an embedded Jetty, but I am interested in the generic WAR.
MyEclipse can do this, but we are standardizing on plain Eclipse.
---
EDIT: This particular web application will run inside an embedded Jetty. Since this question was asked we have found empirically that we need to have the complete tree containing the application with embedded Jetty, war file (exploded) and all built by the Hudson server in order to avoid human steps in the build-deploy-process. The answer for us therefore is scripting with ant (using ant4eclipse).
---
EDIT 2012: The ant4eclipse approach proved to be generally too inflexible and fragile in the long run, so we have switched to Maven. This solved very many problems, this one included. | Make an ant task to build the war (and copy if you like). Then add an Ant builder to the project (project -> properties -> builders). As long as your project is configured to build automatically the war will always be upto date.
This would equally work with maven, or pretty much any other build tool. | You should be able to do this with "File" -> "Export", scroll down to "Web" -> "WAR File" and follow the instructions | How to have Eclipse Java EE automatically generate the exploded WAR for a web project? | [
"",
"java",
"eclipse",
"jakarta-ee",
""
] |
I get this error when I run a django app ([dpaste](http://github.com/bartTC/django-paste/tree))
```
Template error
In template c:\python\projects\mycms\dpaste\templates\dpaste\base.html, error at line 1
Template u'base.html' cannot be extended, because it doesn't exist
1 {% extends "base.html" %}
```
But the ["base.html"](http://github.com/bartTC/django-paste/blob/bc7445d7a3973684bc2641d1841332080c464f3e/dpaste/templates/dpaste/base.html) do exist in the template directory and it has this one line in it:
```
{% extends "base.html" %}
```
What is wrong with that? | Your base.html template cannot extend itself. The problem lies there. Remove that line and replace it with valid html or other Django template tags (or extend some other template). | A template can't extend itself. | Django Template Error : Template u'base.html' cannot be extended | [
"",
"python",
"django",
"django-templates",
""
] |
I wrote an abstraction class for a math object, and defined all of the operators. While using it, I came across:
```
Fixed f1 = 5.0f - f3;
```
I have only two subtraction operators defined:
```
inline const Fixed operator - () const;
inline const Fixed operator - (float f) const;
```
I get what is wrong here - addition is swappable (1 + 2 == 2 + 1) while subtraction is not (same goes for multiplication and division).
I immediately wrote a function *outside* my class like this:
```
static inline const Fixed operator - (float f, const Fixed &fp);
```
But then I realized this cannot be done, because to do that I would have to touch the class's privates, which results to using the keyword `friend` which I loath, as well as polluting the namespace with a 'static' unnecessary function.
Moving the function inside the class definition yields this error in gcc-4.3:
```
error: ‘static const Fixed Fixed::operator-(float, const Fixed&)’ must be either a non-static member function or a non-member function
```
Doing as GCC suggested, and making it a non-static function results the following error:
```
error: ‘const Fixed Fixed::operator-(float, const Fixed&)’ must take either zero or one argument
```
Why can't I define the same operator inside the class definition? if there's no way to do it, is there anyway else not using the `friend` keyword?
Same question goes for division, as it suffers from the same problem. | If you need reassuring that friend functions can be OK:
<http://www.gotw.ca/gotw/084.htm>
> Which operations need access to
> internal data we would otherwise have
> to grant via friendship? These should
> normally be members. (There are some
> rare exceptions such as operations
> needing conversions on their left-hand
> arguments and some like operator<<()
> whose signatures don't allow the \*this
> reference to be their first
> parameters; even these can normally be
> nonfriends implemented in terms of
> (possibly virtual) members, but
> sometimes doing that is merely an
> exercise in contortionism and they're
> best and naturally expressed as
> friends.)
You are in the "operations needing conversions on the left-hand arguments" camp. If you don't want a friend, and assuming you have a non-explicit `float` constructor for `Fixed`, you can implement it as:
```
static inline Fixed operator-(const Fixed &lhs, const Fixed &rhs) {
return lhs.minus(rhs);
}
```
then implement `minus` as a public member function, that most users won't bother with because they prefer the operator.
I assume if you have `operator-(float)` then you have `operator+(float)`, so if you don't have the conversion operator, you could go with:
```
static inline Fixed operator-(float lhs, const Fixed &rhs) {
return (-rhs) + lhs;
// return (-rhs) -(-lhs); if no operator+...
}
```
Or just `Fixed(lhs) - rhs` if you have an explicit `float` constructor. Those may or may not be as efficient as your friend implementation.
Unfortunately the language is not going to bend over backwards to accommodate those who happen to loathe one of its keywords, so operators can't be static member functions and get the effects of friendship that way ;-p | 1. *"That's what friends are for..."*
2. You could add an implicit conversion between `float` and your type (e.g. with a constructor accepting `float`)... but I do think using a `friend` is better. | Defining a proper subtraction operator | [
"",
"c++",
"operator-overloading",
""
] |
What is the best way to loop through an assembly, and for each class in the assembly list out it's "SuperClass"? | ```
Assembly assembly = typeof(DataSet).Assembly; // etc
foreach (Type type in assembly.GetTypes())
{
if (type.BaseType == null)
{
Console.WriteLine(type.Name);
}
else
{
Console.WriteLine(type.Name + " : " + type.BaseType.Name);
}
}
```
Note that generics and nested types have funky names, any you might want to use `FullName` to include the namespace. | ```
foreach(Type type in assembly.GetTypes()) {
var isChild = type.IsSubclassOf(typeof(parentClass))
}
```
Reference from [MSDN](http://msdn.microsoft.com/en-us/library/system.type.issubclassof.aspx). | .NET / C# - Reflection Help - Classes in an Assembly | [
"",
"c#",
".net",
"reflection",
"assemblies",
"superclass",
""
] |
Is there any chance that a SHA-1 hash can be purely numeric, or does the algorithm ensure that there must be at least one alphabetical character?
**Edit:** I'm representing it in base 16, as a string returned by PHP's sha1() function. | technically, a SHA1 hash is a number, it is just most often encoded in base 16 (which is what PHP's sha1() does) so that it nearly always has a letter in it. There is no guarantee of this though.
The odds of a hex encoded 160 bit number having no digits A-F are (10/16)40 or about 6.84227766 × 10-9 | The SHA-1 hash is a 160 bit number. For the ease of writing it, it is normally written in hexadecimal. Hexadecimal (base 16) digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e and f. There is nothing special about the letters. Each hexadecimal character equivalent to 4 bits which means the hash can be written in 40 characters.
I don't believe there is any reason why a SHA-1 hash can't have any letters, but it is improbable. It's like generating a 40 digit (base 10) random number and not getting any 7s, 8s or 9s. | Can a SHA-1 hash be purely numeric? | [
"",
"php",
"algorithm",
"theory",
"sha1",
""
] |
I would like to find a javascript parser that can handle and evaluate simple expressions. The parser should be able to evaluate the regular mathematical expressions, and support custom functions with parameters. It also has to support strings handling. String concatenation with || operator support is preferred, but it is okay if + will do the trick.
Examples of an expression that should be handled by the parser:
3 \* (2 + 1) - 1
2 \* func(2, 2)
func('hello world', 0, 5) || ' you'
Has anyone implemented such a thing or where can I find something similar? | I have a modified version of an [ActionScript parser](http://www.undefined.ch/mparser/index.html) (written in AS, not parses AS) that supports custom functions, but not strings. It would probably be easy to add string support though. I'll upload it somewhere so you can get it at ~~<http://silentmatt.com/parser2.js>~~ <http://silentmatt.com/parser3.js>.
**Edit:** I added basic support for strings pretty easily. It doesn't support escape sequences and toJSFunction doesn't work, but it only took a few minutes to get it working. Changing the concatenation operator to "||" should be pretty easy too.
Here's how you would evaluate your example expressions:
```
js> var parser = new Parser();
js> parser.parse("3 * (2 + 1) - 1").evaluate();
8
js> parser.parse("2 * func(2; 2)").evaluate({ func:Math.pow });
8
js> function substr(s, start, end) { return s.substring(start, end); }
js> parser.parse("func('hello world'; 0; 5) + ' you'").evaluate({ func:substr });
hello you
```
I don't remember why I used semicolons as argument separators; I think it has something to do with differentiating between functions and built-in "operator" functions.
**Another edit:**
I've been playing with this a little, and now there's a version with better string support at <http://silentmatt.com/parser3.js> (toJSFunction works, and you can use standard JavaScript escape sequences). It also uses commas to separate arguments for all functions and `||` as the string concatenation operator instead of `+`, which only does addition. | Try math.js:
<http://mathjs.org>
Comes with an extensive and easy to use parser, which also supports assignment and usage of variables and functions like in your example expression. Integrates seamlessly with "native" JavaScript: you can get and set variables and functions from the Parsers scope.
Your example code would be evaluated as:
```
var parser = math.parser();
parser.set('func', function () {
// ... do something ...
});
parser.evaluate('3 * (2 + 1) - 1');
parser.evaluate('2 * func(2, 2)');
parser.evaluate('func("hello world", 0, 5) + " you"');
```
Functions can also be defined in the parser itself (currently only single-line functions):
```
parser.evaluate('function f(x, y) = x ^ y');
parser.evaluate('f(2, 3)'); // 8
``` | Javascript parser for simple expression | [
"",
"javascript",
"parsing",
"expression",
"evaluation",
""
] |
I have an application that may receive data via various methods and in various formats. I have pluggable receivers that somehow acquire the data (e. g. by polling a mailbox, listening for HTTP requests, watch the content of a directory etc.), associate it with a MIME type and then pass it on wrapped like this:
```
public class Transmission {
private String origin; // where the data came from
private String destination; // where the data was sent to
private String mime; // the MIME type of the data
private BLOB data; // this is what I need an appropriate type for
}
```
Further down the line, the data is processed by specialized handlers according to the value of the `mime` field. I'm expecting things like ZIP files, Excel documents, SOAP, generic XML, plain text and more. At this point, the code should be agnostic as to what's in the data. What is an appropriate type for the `data` field? `Object`? `InputStream`? `Byte[]`? | Multiple Possibilities:
* byte[]
+ the most direct way
* [ByteBuffer](http://java.sun.com/j2se/1.4.2/docs/api/java/nio/ByteBuffer.html)
+ flexible
+ has random access and bulk operations
+ has operations for duplicating, slicing, etc
+ preferable if IO/Network intensive (NIO)
* [InputStream](http://java.sun.com/javase/6/docs/api/java/io/InputStream.html)
+ allows pipelining if done right
+ has no support of random access or bulk operations.
+ Not as flexible as the ByteBuffer.
I would not use Blob, because putting DB-related stuff into our main model seems strange. | I would go with either `byte[]` or `InputStream`, preferring the stream since it is more flexible. You can use a `ByteArrayInputStream` to feed it an array of bytes, if need be. But you can't do it the other way around.
There is also the benefit of memory efficiency, since the stream can handle large chunks of external data without much memory. If you use `byte[]` you need to load all the data to memory. In other words, the stream is lazy. | Which type do I use to represent an arbitrary blob in Java? | [
"",
"java",
"data-modeling",
""
] |
In situations where two interfaces apply to an object, and there are two overloaded methods that differ only by distinguishing between those interfaces, which method gets called?
In code.
```
interface Foo {}
interface Bar {}
class Jaz implements Foo, Bar {}
void DoSomething(Foo theObject)
{
System.out.println("Foo");
}
void DoSomething(Bar theObject)
{
System.out.println("Bar");
}
Jaz j = new Jaz();
DoSomething(j);
```
Which method will get called? DoSomething(Foo) or DoSomething(Bar)? Neither is more specific than the other, and I see no reason why one should be called instead of the other, except that one is specified first/last.
EDIT:
And with this type of code is it possible to force one or the other method? | I'm pretty sure the above won't compile. `DoSomething(j)` is an ambiguous call and will result in an error.
To get it to compile, you'd have to specifically cast `j` as a `Foo` or `Bar` when you call `DoSomething`, for example `DoSomething((Foo)j)`. | This should be a compiler error.
This works:
```
DoSomething((Foo)j);
DoSomething((Bar)j);
``` | Ambiguous Polymorphism? | [
"",
"java",
"oop",
"polymorphism",
""
] |
```
function procLogin($username,$password){
$query = "SELECT *
FROM members
WHERE login = '".mysql_escape_string($username)."'
AND passwd = '".mysql_escape_string($password)."'";
$result = mysql_query($query);
//$values = array();
while($row = mysql_fetch_array($result))
{
return 'gg';
return(array($row['member_id']));
}
}
```
Not able to get the userlevel field.... nor anything.... | return(array($row['member\_id']));
Looks wrong - it should be:
return($row['member\_id']);
You shouldn't need to define the array in the return like that.
You also use mysql\_fetch\_array () which returns as a numerical index - the function you probably want is mysql\_fetch\_assoc which is much nicer to work with as it returns the values with the keys as the column name rather than a numerical index.
Here's it again with a few tidy ups:
```
function procLogin($username,$password){
$query = "SELECT *
FROM members
WHERE login = '".mysql_escape_string($username)."'
AND passwd = '".mysql_escape_string($password)."'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row['member_id'] > 0)
{
return ($row['member_id']);
}
else
{
return false;
}
}
``` | Not sure exactly what your question is, but one problem is that you're `return`ing from within this while loop:
```
while($row = mysql_fetch_array($result))
{
return 'gg';
return(array($row['member_id']));
}
```
In fact, you're returning **twice** from within the loop... so the `procLogin()` function will always return a value of "gg", unless something goes wrong with your SQL query.
In general, you should avoid `return` statements within any loop, as it creates confusion and can lead to unexpected results. | PHP login return values | [
"",
"php",
""
] |
I'm using the following code to get an array with all sub directories from a given path.
```
String[] subDirs = path.split(File.separator);
```
I need the array to check if certain folders are at the right place in this path.
This looked like a good solution until findBugs complains that File.separator is used as a regular expression. It seems that passing the windows file separator to a function that is building a regex from it is a bad idea because the backslash being an escape character.
How can I split the path in a cross platform way without using File.separator?
Or is code like this okay?
```
String[] subDirs = path.split("/");
``` | Use `path.getParentFile()` repeatedly to get all components of a path.
Discouraged way would be to `path.replaceAll("\\", "/").split("/")`. | ### Literalizing pattern strings
Whenever you need to literalize an arbitrary`String` to be used as a regex pattern, use [`Pattern.quote`](http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#quote%28java.lang.String%29):
From the API:
> `public static String quote(String s)`
>
> Returns a literal pattern `String` for the specified `String`. This method produces a `String` that can be used to create a `Pattern` that would match the string `s` as if it were a literal pattern.
> Metacharacters or escape sequences in the input sequence will be given no special meaning.
>
> **Parameters:** `s` - The string to be literalized
> **Returns:** A literal string replacement
This means that you can do the following:
```
String[] subDirs = path.split(Pattern.quote(File.separator));
```
---
### Literalizing replacement strings
If you need to literalize an arbitrary replacement `String`, use [`Matcher.quoteReplacement`](http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#quoteReplacement%28java.lang.String%29).
From the API:
> `public static String quoteReplacement(String s)`
>
> Returns a literal replacement `String` for the specified `String`. This method produces a `String` that will work as a literal replacement `s` in the `appendReplacement` method of the `Matcher` class. The `String` produced will match the sequence of characters in `s` treated as a literal sequence. Slashes (`'\'`) and dollar signs (`'$'`) will be given no special meaning.
>
> **Parameters:** `s` - The string to be literalized
> **Returns:** A literal string replacement
This quoted replacement `String` is also useful in `String.replaceFirst` and `String.replaceAll`:
> Note that backslashes (`\`) and dollar signs (`$`) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Use `Matcher.quoteReplacement` to suppress the special meaning of these characters, if desired.
---
### Examples
```
System.out.println(
"O.M.G.".replaceAll(".", "!")
); // prints "!!!!!!"
System.out.println(
"O.M.G.".replaceAll(Pattern.quote("."), "!")
); // prints "O!M!G!"
System.out.println(
"Microsoft software".replaceAll("so", "$0")
); // prints "Microsoft software"
System.out.println(
"Microsoft software".replaceAll("so", Matcher.quoteReplacement("$0"))
); // prints "Micro$0ft $0ftware"
``` | How to split a path platform independent? | [
"",
"java",
"regex",
"file",
"cross-platform",
""
] |
I have a C# application, and I want to run a function which is defined in text to take one parameter of class A and return a double.
Parameter "A" will be some structured data, and the function will be a formula upon A.
(Imagine A had properties num1, num2, and one formula was defined to return the average, another arbitrarily to return num1 \* 2).
As such, I want to load my function definition from a text source, compile them in some manner, and execute them.
In terms of the structure of the code, I do suppose I could inject the body of the function to be a member function of an arbitrary class, or if I can compile a delegate and then execute it passing a parameter context that would be sufficient also.
What is the way to go about this? | [Use the .Net CodeDOM to compile C# On the Fly](http://blogs.crsw.com/spence/articles/1595.aspx) | I would suggest using an expression parser where you can enter an excel like expression, and includes all basic functions (statistical, string manipulation, math/trig). I've used [CalcEngine](http://www.codeproject.com/Articles/246374/A-Calculation-Engine-for-NET) for a similar requirement with good results. You can extend it with custom functions. | Compiling and running C# code programmatically | [
"",
"c#",
""
] |
I am trying to change the class of a element with Javascript using the below code:
```
parent.document.getElementById('<?php echo $markid ?>').class = 'unlistened';
```
Not having much luck though. How do I do this properly? | .className rather than .class | Use `.className` instead of `.class`
Class is a reserved word in JS so it's changed to className. A few other HTML attributes are changed in a similar way. "for" changes to "htmlFor" *for* instance. | changing class of a <span> element with JavaScript | [
"",
"javascript",
"css",
"dom",
""
] |
How can i return my output in ArrayCollection?
```
values = array();
while($row = mysql_fetch_array($result))
{
$values[] = array(mysql_num_rows($result),$row['userlevel'],$row['email'],$row['member_id']);
}
return $values;
```
I need the output as ArrayCollection | PHP has no such thing as an ArrayCollection as far as I'm aware.
From a quick Google search it seem like this is more about ActionScript/Flex. [This page](http://wadearnold.com/blog/flash/amfphp/amfphp-arraycollection) has some examples of how to get an ArrayCollection from a PHP array. Not sure if it's what you're looking for though. | `ArrayCollection` is part of [Collections](https://www.doctrine-project.org/projects/collections.html), a Doctrine project.
There is no published documentation but the available methods can be seen in the [`ArrayCollection` class](https://github.com/doctrine/collections/blob/master/lib/Doctrine/Common/Collections/ArrayCollection.php) itself. | ArrayCollection in PHP | [
"",
"php",
"doctrine-orm",
""
] |
I have an inline member function defined under class MyClass
```
int MyClass::myInlineFunction();
```
This function is called from several places in my code.
There are two ways to call this function
Case 1: Using this every time the function is called.
```
mobj->myInlineFunction() ;
```
Case 2: Assign the result of this function to a variable and use it for subsequent accesses
```
var = mobj->myInlineFunction() ;
```
Which one should be preferred?? | Case 2 can give you a lot of performance, if the function does something that takes some time.
Choose it if
* you do not need side effects of the function to happen
* the function would always the return the same result in that context | The decision on whether to hold onto a return value or to recall the function again, should not be based on whether the function is inlined or not - as this is an implementation detail that may change over the lifetime/evolution of the class. As a rule of thumb I would always hang onto the return value if it does not make the code too complicated, as you do not know as a user of a class, what the cost of the function is - and what is cheap today could be expensive tomorrow. So I would go with Case 2. | Calling inline functions C++ | [
"",
"c++",
"inline-method",
""
] |
Normally I would go:
```
bgwExportGrid.RunWorkerCompleted += ReportManager.RunWorkerCompleted;
```
The ReportManager class is a static class containing the event handler I want to use.
```
public static class ReportManager
{
public static void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
...
}
}
```
Now I have created a BackgroundWorker and want to attach the RunWorkerCompleted event as defined in ReportManager. However ReportManager cannot be referenced as otherwise a cyclic reference happens therefore reflection is needed.
Any help would be greatly appreciated.
I've looked at the following but haven't gotten very far:
```
Assembly assem = Utils.GetAssembly("WinUI.Reporting.Common.dll");
Type reportManagerType = assem.GetModule("WinUI.Reporting.Common.dll").GetType("WinUI.Reporting.Common.ReportManager");
EventInfo evWorkerCompleted = reportManagerType.GetEvent("RunWorkerCompleted");
Type tDelegate = evWorkerCompleted.EventHandlerType;
``` | I think your code would be easier to maintain in the future if you would instead abtract the interface out of the ReportManager into an interface that both assemblies can reference. But, if that is not an option for you, I think that you are trying to achieve something like this:
```
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
AttachEventHandler(backgroundWorker1,
Type.GetType("WindowsFormsApplication1.EventHandlers"),
"RunWorkerCompleted");
backgroundWorker1.RunWorkerAsync();
}
private void AttachEventHandler(BackgroundWorker bgw, Type targetType,
string eventHandlerMethodName)
{
object targetInstance = Activator.CreateInstance(targetType);
bgw.RunWorkerCompleted +=
(RunWorkerCompletedEventHandler)Delegate.CreateDelegate(
typeof(RunWorkerCompletedEventHandler),
targetInstance, eventHandlerMethodName);
}
}
public class EventHandlers
{
public void RunWorkerCompleted(object sender,
System.ComponentModel.RunWorkerCompletedEventArgs e)
{
// do something
}
}
}
```
Note how there is no "hard" reference between `Form1` and the `EventHandlers` class, so that could be any other class residing in any other assembly; the event handler is created and attached based on the name of the type and the name of the method (which, naturally, must have the correct signature). | Updated answer:
```
Assembly assem = Utils.GetAssembly("WinUI.Reporting.Common.dll");
Type reportManagerType = assem.GetModule("WinUI.Reporting.Common.dll").GetType("WinUI.Reporting.Common.ReportManager");
// obtain the method info
MethodInfo mi = reportManagerType.GetMethod("RunWorkerCompleted",
BindingFlags.Static | BindingFlags.Public);
// create a delegate that we can further register with the event
Delegate handler = Delegate.CreateDelegate(reportManagerType , mi);
// get the event info from the export grid object
EventInfo evWorkerCompleted = bgwExportGrid.GetType().GetEvent("RunWorkerCompleted");
// invoke the event
evWorkerCompleted.AddEventHandler(bgwExportGrid, handler);
``` | How to add a BackgroundWorker RunWorkerCompleted event through reflection? | [
"",
"c#",
"reflection",
"backgroundworker",
""
] |
I currently represent my Business Layer and Data Layer in a single project in my application. I have very good separation of concerns between the two sets of classes. However, My Data Layer classes take as parameters and return my business objects. So I will have code that loosely resembles (please don't be too critical of this code, my production code doesn't look much like this):
```
//business class fragment
public bool Save()
{
if(this.IsValid)
{
//DataProvider is one of many data access classes that implement an IDataProvider interface. Switched elsewhere in the class. This allows switching of Database providers, xml, etc.
DataProvider.Save(this);
return true;
}
return false;
}
public List<MyBusinessObject> GetObjectsByCriteria(string criteria)
{
return DataProvider.GetMyBusinessObjectsByCriteria(criteria);
}
```
I don't want my business classes to have to deal with DataSets any more than I like having my Data Layer classes deal with Business Classes.
I have read up a lot on Data Access Objects, or Data Transfer Objects to possibly solve this problem, but the this seems like an anti-pattern case for those patterns.
What can I do? How to I elegantly achieve complete separation of these two layers of my application? | This is a more general problem than just how to separate Domain Model from Data Access. The same problem occurs when you attempt to separate your Application Logic from your Domain model, your Presentation Model from Application Logic and so forth.
The common solution is a technique called Dependency Injection (DI). Some people also refer to it as Inversion of Control (IoC).
The seminal text on the subject was Martin Fowler's article [Inversion of Control Containers and the Dependency Injection pattern](http://martinfowler.com/articles/injection.html), but we have come a long way since then, so be sure to examine some more recent texts as well.
You can implement DI manually, like [described in this blog post](http://blogs.msdn.com/ploeh/archive/2007/05/30/CodeAsDependencyConfiguration.aspx), or you can let a DI Container (i.e. a framework) do the work for you.
Common DI Container are:
* [Windsor](http://www.castleproject.org/container/index.html)
* [StructureMap](http://structuremap.sourceforge.net/Default.htm)
* [Spring.NET](http://springframework.net/)
* [Unity](http://msdn.microsoft.com/en-us/library/dd203104.aspx) | I don't think you can have the two completely separated, but you can ensure that the dependency isn't bi-directional.
I think it's important to define a couple of things:
1. model objects (e.g., Person, Address, Order, etc.)
2. persistence layer (e.g., DAOs, repositories, etc.)
3. service layer (interfaces whose methods map to use cases, know about units of work, etc.)
4. web or view layer (controllers/pages for web apps, widgets for desktop).
The persistence, service, and view layers know about the model objects; the model objects are oblivious to the layer they're in.
The dependencies for the layers are unidirectional and flow back to front:
* persistence->model
* service->model, persistence
* view->model, service
You unit test from back to front, because the dependencies make it easy to mock.
It's impossible to have NO dependencies, but you should design them so there are no cycles.
The only class with **no** dependencies is one that is called by no one and never calls another class. It's neither useful nor a worthwhile design goal. | How can I completely separate my Business and Data Layers? | [
"",
"c#",
"design-patterns",
""
] |
I make an AJAX request to see if a sesion variable has been set. I make a GET request to this script:
```
<?php session_start();
while(true){
if(isset($_SESSION['screen_name'])){
return true;
break;
}
}
?>
```
Clearly there are problems with this script and I wanted to solve these problems such as the continuous checking and waste of resources.
**Scenario**: I am trying to implement the oAuth method that [twitgoo](http://www.twitgoo.com) have used. You click "sign in" and then a window pops up for you to sign in to twitter. If you are successful, twitter redirects to a call back URL (which I guess sets session info) and the window is closed. Once this is done your message is posted to twitter. I am trying to achieve this and I am nearly there but I am unsure of my script above.
I would appreciate any help in making this script **not so wasteful** and if you have a **better implementation**, I would love to hear it.
Thanks all
## Update
I have been give two good options which do you think is more efficient between:
1) Polling the server every few seconds using JS instead of the while loop eating up CPU cycles
2) Keep the while loop but "ease up" on the level of checking meaning no more http requests will be wasted | This is a PHP script? Is there any condition that may change the state of `$_SESSION['screen_name']` other than a page refresh/new poll, i.e. a **restart of the script** in the first place?
The `$_SESSION` variable depends on the request. It's not going to change while the script runs, unless changed by the script. All this script does is either return `true` if the condition is met, or loop until the timeout is hit. The condition is either true on the first try or never will be. | Unfortunately, all you've created here is an infinite loop. If `$_SESSION['screen_name']` isn't set the first time through, it's never, ever going to be set. Once you've loaded a PHP script, the environment variables will not change. You will never receive another session cookie, nor will any of $\_GET, $\_POST, $\_SESSION, etc. ever be modified, unless you do it explicitly inside the script, or the script ends and you make another request.
My suggestion here would be something like this:
```
if(isset($_SESSION['screen_name'])){
return true;
break;
}
else {
//output JSON encoded error message
}
```
If you exit your script when the required session variable isn't set and send a response back to the browser, then the browser can decide what to do. Perhaps make another request, maybe wait ten seconds, maybe load a login dialog. | How to solve a while true loop as it is expensive and Risky | [
"",
"php",
"security",
"performance",
"oauth",
""
] |
To fullfill a requirement I have to show a tooltip manually for 30 seconds. According to msdn I just have to use the "Show" method.
```
toolTip.Show(QuestionHelpText, btnHelp, 30000);
```
But I only get the standard tooltip behavior, meaning that the message appears half a second after my click (only because the mouse pointer is still over the button). I tried some variations like
```
toolTip.Show(QuestionHelpText, btnHelp);
```
but still, nothing happens.
Does anybody have an idea why that is?
Thanks | I know a simple workaround
Put a lable (let's name it **labelHelp**) with empty text near your button
The following code should work
```
private void btnHelp_Click(object sender, EventArgs e)
{
toolTip.Show(QuestionHelpText, labelHelp, 3000);
}
``` | Where is "toolTip" declared?
MSDN doesn't indicate (on the [ToolTip.Show Method documentation](http://msdn.microsoft.com/en-us/library/y8k201a3(VS.85).aspx)) that the Show method is a blocking call, so if you're declaring toolTip in a method and then pretty much straight afterwards exiting the method then toolTip will have fallen out of scope, causing it to not render or disappear. | C# Tooltip not appearing on "Show" | [
"",
"c#",
"winforms",
"tooltip",
""
] |
What would be the best way and more idiomatic to break a string into two at the place of the last dot? Basically separating the extension from the rest of a path in a file path or URL. So far what I'm doing is Split(".") and then String.Join(".") of everything but the last part. Sounds like using a bazooka to kill flies. | If you want performance, something like:
```
string s = "a.b.c.d";
int i = s.LastIndexOf('.');
string lhs = i < 0 ? s : s.Substring(0,i),
rhs = i < 0 ? "" : s.Substring(i+1);
``` | You could use **Path.GetFilenameWithoutExtension()**
or if that won't work for you:
```
int idx = filename.LastIndexOf('.');
if (idx >= 0)
filename = filename.Substring(0,idx);
``` | Best way to break a string on the last dot on C# | [
"",
"c#",
"string",
""
] |
Thank you one and all for your patience and help. I am completely restating the question because it is getting quite long from all my revisions.
I have an PHP MVC framework with 4 entry points:
from the root:
index.php
index-ajax.php
admin/index.php
admin/index-ajax.php
I needed a .htcaccess file that would take any request and rewrite it to the corresponding file based on the url. The long url would be index.php?rt=cms/view/15 and I wanted it to be index/cms/view/15. That part is pretty much done except for one gotcha.
Here is my .htaccess file now:
```
# htaccess file for framework - GOOD
Options +FollowSymLinks
# Turn on the mod_rewrite engine - GOOD
RewriteEngine On
# Hide indexes - GOOD
Options -Indexes
# If a file is not one of these, continue processing. - GOOD
RewriteRule \.(css|js|jpg|jpeg|png|gif|ico)$ - [L]
# RewriteRules for folder index files
#RewriteRule ^(index)?(.php)?$ index.php [L] - GOOD
#RewriteRule ^admin(/?)(index)?(.php)?$ admin/index.php [L] - GOOD
# RewriteRules for admin folder arguements - going from more specific to less
RewriteRule ^admin/ajax/[A-Za-z0-9-_/]*$ admin/index-ajax.php?rt=$1 [L]
RewriteRule ^admin/[A-Za-z0-9-_/]*$ admin/index.php?rt=$1 [L]
# RewriteRule for root ajax file
RewriteRule ^ajax/[A-Za-z0-9-_/]*$ index-ajax.php?rt=$1 [L]
# RewriteRule for root file - by here, it is not ajax or admin related, so only
# possible option left if the root index file
RewriteRule ^[A-Za-z0-9-_/]*$ index.php?rt=$1 [L]
```
I have made a simple site with two folders - 'root' and 'root/admin', and inside of each of those a css,images, and javascript folder with some dummy content. There is an index.php and index-ajax.php file inside of 'root' and 'root/admin' that simple outputs whatever the url argument is and uses a css, js, and image file from each of the folders.
The problem I have now is that if I do a url like index/blah or /admin/index/blah, then the page presents right and the argument is right. However, when I do a url like index/blah/view or admin/index/blah/view then the arguement is right (?rt=blah/view) but the page presents wrong because the css/js/images file go to index/blah/[css] instead of index/[css].
Any ideas on how to handle this? I allowed css/js/image files to go through as is via the .htaccess so there would be less work there. | So the images/css/etc break because you're using a relative URL in the HTML, and now that you're going more nested they're breaking? With some other MVC setups I encountered, there's usually a "root path" variable of some sort, set by the Controller based on the request URL, and used by the View component to prefix all paths to assets like images/styles/scripts.
That turns your .htaccess problem into a Controller/PHP problem, which if that's an acceptable solution for you, would involve your Controller doing something like exploding the request URL on "/"s, counting the number of resulting pieces, and constructing a relative URL from the result.
I did a similar thing for a custom MVC setup I did; check out <http://avogadro.ws/hosted/skel/public/results/school-1> and look at the head source for the CSS locations. The CSS for that page is actually at the <http://avogadro.ws/hosted/skel/> level, which the Controller builds into a relative string. | Are you sure that everything should be handled by index.php? What about static files such as images/css etc.?
Here is an alternative method which may interest you. You can forward any URL which does not already exist as a file or directory to your index.php file and then parse the URL there, e.g. [domain.com]/cms/view/15 would be rewritten to [domain.com]/index.php/cms/view/15 . You need to have the apache directive AcceptPathInfo set to On for this work.
**.htaccess:**
```
RewriteEngine On
#check url is not a valid file
RewriteCond %{REQUEST_FILENAME} !-f
#check url is not a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
#rewite anything left
RewriteRule ^(.*)$ index.php/$1 [L]
```
**index.php**
```
$path = trim($_SERVER['PATH_INFO'], '/');
$pathParts = explode('/', $path);
if (isset($pathParts[0])) {
$com = $pathParts[0];
} else {
$com = 'defaultcom';
}
//$com[1] will be 'view' if supplied
//$com[2] will be 15 if supplied
```
I like this approach because you are not forced to define and understand the URL in the apache configuration, but you can do most of the work in PHP.
**Edit**
You could use this as your .htaccess instead, this would redirect any request with an extension not in the list to your PHP script. The RewriteCond should stop requests to the admin folder from being rewritten.
```
RewriteEngine On
#don't rewrite admin
RewriteCond %{REQUEST_URI} ^admin/
#rewrite anything with a file extension not in the list
RewriteRule !\.(js|gif|jpg|png|css|ico)$ /index.php [L]
``` | URL Rewriting Help | [
"",
"php",
"apache",
"mod-rewrite",
"url-rewriting",
""
] |
When the Client tries to connect to a disconnected IP address, there is a long timeout over 15 seconds... How can we reduce this timeout? What is the method to configure it?
The code I'm using to set up a socket connection is as following:
```
try
{
m_clientSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(serverIp);
int iPortNo = System.Convert.ToInt16(serverPort);
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
m_clientSocket.Connect(ipEnd);
if (m_clientSocket.Connected)
{
lb_connectStatus.Text = "Connection Established";
WaitForServerData();
}
}
catch (SocketException se)
{
lb_connectStatus.Text = "Connection Failed";
MessageBox.Show(se.Message);
}
``` | I solved the problem by using Socket.ConnectAsync Method instead of Socket.Connect Method.
After invoking the Socket.ConnectAsync(SocketAsyncEventArgs), start a timer (timer\_connection), if time is up, check whether socket connection is connected (if(m\_clientSocket.Connected)), if not, pop up timeout error.
```
private void connect(string ipAdd,string port)
{
try
{
SocketAsyncEventArgs e=new SocketAsyncEventArgs();
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(serverIp);
int iPortNo = System.Convert.ToInt16(serverPort);
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
//m_clientSocket.
e.RemoteEndPoint = ipEnd;
e.UserToken = m_clientSocket;
e.Completed+=new EventHandler<SocketAsyncEventArgs>(e_Completed);
m_clientSocket.ConnectAsync(e);
if (timer_connection != null)
{
timer_connection.Dispose();
}
else
{
timer_connection = new Timer();
}
timer_connection.Interval = 2000;
timer_connection.Tick+=new EventHandler(timer_connection_Tick);
timer_connection.Start();
}
catch (SocketException se)
{
lb_connectStatus.Text = "Connection Failed";
MessageBox.Show(se.Message);
}
}
private void e_Completed(object sender,SocketAsyncEventArgs e)
{
lb_connectStatus.Text = "Connection Established";
WaitForServerData();
}
private void timer_connection_Tick(object sender, EventArgs e)
{
if (!m_clientSocket.Connected)
{
MessageBox.Show("Connection Timeout");
//m_clientSocket = null;
timer_connection.Stop();
}
}
``` | I found this. Simpler than the accepted answer, and works with .NET Framework v2
```
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect using a timeout (5 seconds)
IAsyncResult result = socket.BeginConnect( sIP, iPort, null, null );
bool success = result.AsyncWaitHandle.WaitOne( 5000, true );
if ( socket.Connected )
{
socket.EndConnect( result );
}
else
{
// NOTE, MUST CLOSE THE SOCKET
socket.Close();
throw new ApplicationException("Failed to connect server.");
}
//...
``` | How to configure socket connect timeout | [
"",
"c#",
"sockets",
"timeout",
""
] |
This code used to return my local ip address as 192.xxx.x.xxx but now it is returning 127.0.0.1 . Please help me why the same code is returning different value. Is there something that I need to watch at linux OS.
```
import java.util.*;
import java.lang.*;
import java.net.*;
public class GetOwnIP
{
public static void main(String args[]) {
try{
InetAddress ownIP=InetAddress.getLocalHost();
System.out.println("IP of my system is := "+ownIP.getHostAddress());
}catch (Exception e){
System.out.println("Exception caught ="+e.getMessage());
}
}
}
``` | 127.0.0.1 is the loopback adapter - it's a perfectly correct response to the (somewhat malfomed) question "what is my IP address?"
The problem is that there are *multiple* correct answers to that question.
EDIT: The docs for `getLocalHost` say:
> If there is a security manager, its
> checkConnect method is called with the
> local host name and -1 as its
> arguments to see if the operation is
> allowed. If the operation is not
> allowed, an InetAddress representing
> the loopback address is returned.
Is it possible that the change in behaviour is due to a change in permissions?
EDIT: I believe that `NetworkInterface.getNetworkInterfaces` is what you need to enumerate all the possibilities. Here's an example which doesn't show virtual addresses, but works for "main" interfaces:
```
import java.net.*;
import java.util.*;
public class Test
{
public static void main(String[] args)
throws Exception // Just for simplicity
{
for (Enumeration<NetworkInterface> ifaces =
NetworkInterface.getNetworkInterfaces();
ifaces.hasMoreElements(); )
{
NetworkInterface iface = ifaces.nextElement();
System.out.println(iface.getName() + ":");
for (Enumeration<InetAddress> addresses =
iface.getInetAddresses();
addresses.hasMoreElements(); )
{
InetAddress address = addresses.nextElement();
System.out.println(" " + address);
}
}
}
}
```
(I'd forgotten just how awful the `Enumeration<T>` type is to work with directly!)
Here are the results on my laptop right now:
```
lo:
/127.0.0.1
eth0:
/169.254.148.66
eth1:
eth2:
ppp0:
/10.54.251.111
```
(I don't think that's giving away any *hugely* sensitive information :)
If you know which network interface you want to use, call `NetworkInterface.getByName(...)` and then look at the addresses for that interface (as shown in the code above). | When you use InetAddress.getLocalHost() you are not guaranteed to get a particular interface, ie. you could receive the loopback (127) interface or a connected one.
In order to ensure you always get an external interface, you should use the java.net.NetworkInterface class. The static getByName(String) class will give you the interface with the defined name (such as "eth0"). Then you can use the getInetAddresses() function to obtain the IP addresses (could be just one) bound to that interface.
```
NetworkInterface ni = NetworkInterface.getByName("eth1");
ni.getInetAddresses();
``` | IP Address not obtained in java | [
"",
"java",
""
] |
```
while (list($task_id, $parent_id, $task) = mysqli_fetch_array($r, MYSQLI_NUM))
``` | it's a loop through a result set, with a compressed conversion from a mysql result row to individual variables
the long way would be:
```
while($row=mysqli_fetch_array($result)){
$task_id = $row[0];
$parent_id = $row[1];
$task = $row[2];
// Do something with the row data
}
```
the relevant pages in the PHP doc are:
Convert an array to a set of variables: <http://php.net/list>
Fetching a row of a mysqli result object: <http://php.net/manual/en/mysqli-result.fetch-array.php> | It fetches a row (from a MySQL query) into the array with the columns `task_id`, `parent_id`, and `task` until there are no more rows to fetch. The `list()` function converts these columns into the `$task_id`, `$parent_id`, and `$task` variables for use in the `while` loop.
In other words: It iterates through a rowset. | What does this code do? | [
"",
"php",
"mysql",
"arrays",
"list",
""
] |
### Premise
This problem has a known solution (shown below actually), I'm just wondering if anyone has a more elegant algorithm or any other ideas/suggestions on how to make this more readable, efficient, or robust.
### Background
I have a list of sports competitions that I need to sort in an array. Due to the nature of this array's population, 95% of the time the list will be pre sorted, so I use an improved bubble sort algorithm to sort it (since it approaches O(n) with nearly sorted lists).
The bubble sort has a helper function called CompareCompetitions that compares two competitions and returns >0 if comp1 is greater, <0 if comp2 is greater, 0 if the two are equal. The competitions are compared first by a priority field, then by game start time, and then by Home Team Name.
The priority field is the trick to this problem. It is an int that holds a positve value or 0. They are sorted with 1 being first, 2 being second, and so on with the exception that 0 or invalid values are always last.
e.g. the list of priorities
0, 0, 0, 2, 3, 1, 3, 0
would be sorted as
1, 2, 3, 3, 0, 0, 0, 0
The other little quirk, **and this is important to the question,** is that 95% of the time, priority will be it's default 0, because it is only changed if the user wants to manually change the sort order, which is rarely. So the most frequent case in the compare function is that priorities are equal and 0.
### The Code
This is my existing compare algorithm.
```
int CompareCompetitions(const SWI_COMPETITION &comp1,const SWI_COMPETITION &comp2)
{
if(comp1.nPriority == comp2.nPriority)
{
//Priorities equal
//Compare start time
int ret = comp1.sStartTime24Hrs.CompareNoCase(comp2.sStartTime24Hrs);
if(ret != 0)
{
return ret; //return compare result
}else
{
//Equal so far
//Compare Home team Name
ret = comp1.sHLongName.CompareNoCase(comp2.sHLongName);
return ret;//Home team name is last field to sort by, return that value
}
}
else if(comp1.nPriority > comp2.nPriority)
{
if(comp2.nPriority <= 0)
return -1;
else
return 1;//comp1 has lower priority
}else /*(comp1.nPriority < comp2.nPriority)*/
{
if(comp1.nPriority <= 0)
return 1;
else
return -1;//comp1 one has higher priority
}
}
```
### Question
How can this algorithm be improved?
And more importantly...
Is there a better way to force 0 to the back of the sort order?
I want to emphasize that this code seems to work just fine, but I am wondering if there is a more elegant or efficient algorithm that anyone can suggest. Remember that nPriority will almost always be 0, and the competitions will usually sort by start time or home team name, but priority must ***always*** override the other two. | Isn't it just this?
```
if (a==b) return other_data_compare(a, b);
if (a==0) return 1;
if (b==0) return -1;
return a - b;
``` | You can also reduce some of the code verbosity using the trinary operator like this:
```
int CompareCompetitions(const SWI_COMPETITION &comp1,const SWI_COMPETITION &comp2)
{
if(comp1.nPriority == comp2.nPriority)
{
//Priorities equal
//Compare start time
int ret = comp1.sStartTime24Hrs.CompareNoCase(comp2.sStartTime24Hrs);
return ret != 0 ? ret : comp1.sHLongName.CompareNoCase(comp2.sHLongName);
}
else if(comp1.nPriority > comp2.nPriority)
return comp2.nPriority <= 0 ? -1 : 1;
else /*(comp1.nPriority < comp2.nPriority)*/
return comp1.nPriority <= 0 ? 1 : -1;
}
```
See?
This is much shorter and in my opinion easily read.
I know it's not what you asked for but it's also important. | Custom sorting, always force 0 to back of ascending order? | [
"",
"c++",
"sorting",
""
] |
I created a class that's something like this:
```
public class MovieTheaterList
{
public DateTime Date { get; private set; }
public int NumTheaters { get; private set; }
public Theater[] Theaters { get; private set; }
}
public class Theater
{
public string Name;
}
```
I want to be able to add items to the Theaters array of the MovieTheaterList class, but when I try to access it, it is showing up as an IEnumerable type and there is no Add() method?
I'm used to using arrays in structs and classes in C/C++, but how can I add a new item to the array in .NET 3.5? | Expose Theaters as an IList, not an array, and you'll be able to add / remove items from it.
e.g.
```
public class MovieTheaterList
{
// don't forget to initialize the list backing your property
private List<Theater> _theaterList = new List<Theater>();
public DateTime Date { get; private set; }
public int NumTheaters { get; private set; }
// set is unnecessary, since you'll just be adding to / removing from the list, rather than replacing it entirely
public IList<Theater> Theaters { get { return _theaterList; } }
}
``` | How about having the MovieTheatreClass extend a Generic List, for this functionality.
```
public class MovieTheatreList : List<Theatre>
{
public DateTime Date { get; private set; }
}
public class Theatre
{
public string Name;
}
```
This way, you get all the built in stuff of the List (like Count instead of having a separate NumOfTheatres property to maintain). | Class Array with [] and IEnumerable | [
"",
"c#",
".net",
"arrays",
".net-3.5",
""
] |
My PHP script generates a table with rows which can optionaly be edited or deleted. There is also a possibilety to create a new Row.
I am having a hard time to figure out how to update the HTML rows which are generated through PHP and inserted via jQuery. After the update it must be still editable. The HTML is generated into a div.
1. jQuery (insert generated HTML/wait for action)
2. PHP (generate html)
3. Go back to step 1)
***(EDIT: Corrected an error and changed script to answer)***
**PHP**
```
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME, $dbh) or die("Could not select printerweb");
$action = $_POST['action'];
$name = $_POST['name'];
$id = $_POST['id'];
if ($action == "new") {
mysql_query("INSERT INTO place (id, name) VALUES (NULL, $name)");
}
elseif ($action == "edit") {
mysql_query("UPDATE place SET name = $name WHERE id = $id");
}
elseif ($action == "delete") {
mysql_query("DELETE FROM place WHERE id = $id");
}
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=" . $row["id"] . " class=inputfield_td><input class=inputfield_place type=text value=" . $row["name"] . " /></td><td class=place_name>" . $row["name"] . "</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
```
**JS**
```
$(function() {
$.ajax({
url: "place/place_list.php",
cache: false,
success: function(html) {
$("#place_container").append(html);
}
});
$(".edit").live("click", function() {
$(this).css("display", "none").prevAll(".place_name").css("display", "none").prevAll(".inputfield_td").css("display", "block").nextAll(".cancel").css("display", "block").nextAll(".save").css("display", "block").prevAll(".inputfield_td").css("display", "block");
});
$(".cancel").live("click", function() {
$(this).css("display", "none").prevAll(".edit").css("display", "block").prevAll(".place_name").css("display", "block").prevAll(".inputfield_td").css("display", "none").nextAll(".save").css("display", "none");
});
$(".save").live("click", function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display", "none").prevAll(".cancel").css("display", "none").prevAll(".edit").css("display", "block").prevAll(".place_name").css("display", "block").prevAll(".inputfield_td").css("display", "none");
alert("save name: " + myvariable1 + " save id: " + myvariable2);
});
$(".delete").live("click", function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
alert(myvariable3);
});
$(".new").live("click", function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place/place_list.php", {
action: "new",
name: "" + myvariable4 + ""
});
});
});
``` | place all your event-handlers outside the ajax function and use the `live()` method instead. And you need to include what data to send when using ajax. From [visualjquery](http://visualjquery.com/):
```
$(function() {
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$(".edit").live("click", function() {
//event handler code here
});
//more event handlers
});
``` | I think you are not getting click events for editing, deleting etc. after new rows from php are appended to the div.
Try using jquery live plugin to bind click events as and when new stuff is created. Please refer to [this](https://stackoverflow.com/questions/626736/jquery-not-triggering-on-appended-item) question dealing with similar problem. | How to update rows in jQuery with PHP and HTML | [
"",
"php",
"jquery",
"mysql",
"html",
"row",
""
] |
I'm trying to code a page where you can post a comment without reloading the whole page. The comments are displayed using a Repeater control. The template looks like this:
```
<asp:UpdatePanel runat="server" ID="commentsUpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<!-- Comments block -->
<div class="wrapper bloc content">
<h3><img src="img/comments.png" alt="Comments" /> Comments</h3>
<p><asp:Label ID="viewImageNoComments" runat="server" /></p>
<asp:Repeater ID="viewImageCommentsRepeater" runat="server">
<HeaderTemplate>
<div class="float_box marge wrapper comments">
</HeaderTemplate>
<ItemTemplate>
<div class="grid_25">
<span class="user"><%#Eval("username")%></span><br />
<span style="font-size:x-small; color:#666"><%#Eval("datetime") %></span>
</div>
<div class="grid_75">
<p align="justify"><%#Eval("com_text") %></p>
</div>
</ItemTemplate>
<FooterTemplate>
</div>
</FooterTemplate>
</asp:Repeater>
</div>
<!-- Post comment block -->
<div class="wrapper bloc content">
<h3><a id="post_comment" name="post_comment"><img src="img/comment_edit.png" alt="Comments" /></a> Post
a comment</h3>
<p class="description">Please be polite.</p>
<p>
<asp:Label ID="postCommentFeedback" runat="server" />
</p>
<table border="0">
<tr>
<td valign="top">
<asp:TextBox id="postCommentContent" runat="server" TextMode="MultiLine"
MaxLength="600" Columns="50" Rows="15" Width="400px" />
</td>
<td valign="top">
<span style="font-size:x-small">BBCode is enabled. Usage :<br />
<b>bold</b> : [b]bold[/b]<br />
<i>italic</i> : [i]italic[/i]<br />
<span class="style1">underline</span> : [u]underline[/u]<br />
Link : [url=http://...]Link name[/url]<br />
Quote : [quote=username]blah blah blah[/quote]</span>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="postCommentButton" runat="server" Text="Submit"
onclick="postCommentButton_Click" />
</td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
```
The postCommentButton\_Click() function works just fine - clicking "Submit" will make the post. However, I need to completely reload the page in order to see new comments - the post the user just made will not show until then. I Databind the Repeater in Page\_Load() after a (!isPostBack) check.
The postCommentButton\_Click() function looks like this:
```
protected void postCommentButton_Click(object sender, EventArgs e)
{
// We check if user is authenticated
if (User.Identity.IsAuthenticated)
{
// Attempt to run query
if (Wb.Posts.DoPost(postCommentContent.Text, Request.QueryString["imageid"].ToString(), User.Identity.Name, Request.UserHostAddress))
{
postCommentFeedback.Text = "Your post was sucessful.";
postCommentContent.Text = "";
}
else
{
postCommentFeedback.Text = "There was a problem with your post.<br />";
}
}
// CAPTCHA handling if user is not authenticated
else
{
// CAPTCHA
}
}
```
In my case, we do see postCommentFeedback.Text refreshed, but, again, not the content of the repeater which should have one more post.
What is it I'm missing? | You should DataBind in the Page\_Load within a !IsPostBack as you are. You should ALSO databind in your Click event.
```
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
this.DataBind();
}
}
protected void MyButton_Click(object sender, EventArgs e)
{
//Code to do stuff here...
//Re DataBind
this.DataBind();
}
public override void DataBind()
{
//Databinding logic here
}
``` | Instead of making your datasource a MySqlDataReader, have your reader populate a BindingList or something like that. Keep that in session and do your databind every non-postback and click. When your user posts, you can either add it to the list and wait for something to tell it to save that, but it makes more sense in the context of posting comments to save their post to your db and redo your datapull and stomp over your BindingList and re-Databind.
Also, personal peeve: I dislike <%#Eval....%>. Code in your page is usually a bad sign. Try using the Repeater.ItemDataBound Event
<http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemdatabound.aspx> | Refreshing a Repeater control in an UpdatePanel with ASP.NET | [
"",
"c#",
"asp.net",
"updatepanel",
"repeater",
""
] |
> **Possible Duplicate:**
> [Writing “unit testable” code?](https://stackoverflow.com/questions/1007458/writing-unit-testable-code)
I am new to unit testing. Today on SO I found an answer to a question about [interfaces in c#](https://stackoverflow.com/questions/1035632/what-are-some-advantages-to-using-an-interface-in-c). That got me thinking about best practices for building an applications that's testable by design.
I use interfaces very lightly in the main application that I work on. That's made it very difficult to test because I have no way of injecting test data into most classes as each class relies directly upon other classes, and thus the other classes implementations.
So my question is, for a C# application, how would you design your classes and implementations, and what tools would you use to ensure that methods and classes can be independently unit tested by supplying test data for each method or class.
EDIT: Specifically, if you look at the question I linked to, the answer uses this:
IWidget w = ObjectFactory.GetInstance();
I never used a class/object factory, so I'm curious how that works and how it would be implemented. | [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) is the solution you are looking for. The general problem has to do with where your dependencies are created. Normally, when writing an object-oriented program, the natural instinct is to create your dependencies directly using the new keyword at the location you need your dependencies. Sometimes you may create long-lived dependencies in a constructor.
To make your classes more unit testable, you need to "invert" that norm, and create your dependencies externally (or create a factory/provider/context that can in turn be injected and used to create instances of other dependencies), and "inject" those dependencies into your class. The two most common mechanisms of injection are either as parameters to a constructor, or with properties with setters. By externalizing dependency management in this way, you are easily able to create mocked versions of those dependencies and pass those in, allowing you to test your units of code in full isolation from the rest of your application.
To support dependency injection and make it easier to manage Inversion of Control (IoC) containers have appeared. An IoC container is a framework that allows you to configure dependency graphs independently of the classes that participate in in those graphs. Once a dependency graph is configured (usually rooted at the single key class of interest), you can easily create instances of your objects at runtime without having to worry about manually creating all of the required dependencies as well. This helps in creating very loosely coupled, flexible code that is easy to reconfigure. An example of a very good IoC container is [Castle Windsor](http://www.castleproject.org/container/index.html), which provides a very rich framework for wiring up classes via dependency injection.
A very simple example of Dependency Injection would be something like the following:
```
interface ITaskService
{
void SomeOperation();
}
interface IEntityService
{
Entity GetEntity(object key);
Entity Save(Entity entity);
}
class TaskService: ITaskService
{
public TaskService(EntityServiceFactory factory)
{
m_factory = factory;
}
private EntityServiceFactory m_factory; // Dependency
public void SomeOperation() // Method must be concurrent, so create new IEntityService each call
{
IEntityService entitySvc = m_factory.GetEntityService();
Entity entity = entitySvc.GetEntity(...);
// Do some work with entity
entitySvc.Save(entity);
}
}
class EntityServiceFactory
{
public EntityServiceFactory(RepositoryProvider provider)
{
m_provider = provider;
}
private RepositoryProvider m_provider; // Dependency
public virtual IEntityService GetEntityService()
{
var repository = m_provider.GetRepository<Entity>();
return new EntityService(repository);
}
}
class EntityService: IEntityService
{
public EntityService(IEntityRepository repository)
{
m_repository = repository;
}
private IEntityRepository m_repository; // Dependency
public Entity GetEntity(object key)
{
if (key == null) throw new ArgumentNullException("key");
// TODO: Check for cached entity here?
Entity entity = m_repository.GetByKey(key);
return entity;
}
public Entity Save(Entity entity)
{
if (entity == null) throw new ArgumentNullException(entity);
if (entity.Key == null)
{
entity = m_repository.Insert(entity);
}
else
{
m_repository.Update(entity);
}
return entity;
}
}
class RepositoryProvider
{
public virtual object GetRepository<T>()
{
if (typeof(T) == typeof(Entity))
return new EntityRepository();
else if (...)
// ... etc.
}
}
interface IEntityRepository
{
Entity GetByKey(object key);
Entity Insert(Entity entity);
void Update(Entity entity);
}
class EntityRepository: IEntityRepository
{
public Entity GetByKey(object key)
{
// TODO: Load up an entity from a database here
}
public Entity Insert(Entity entity)
{
// TODO: Insert entity into database here
}
public void Update(Entity entity)
{
// TODO: Update existing entity in database here
}
}
``` | [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) is a great principle that allows you to create tests easily by defining [mock objects](http://en.wikipedia.org/wiki/Mock_object) where needed.
Basically the idea is that you pass in any dependency to an object, it doesn't create its own objects to operate on. | How to design an application such that it's easily testable using unit testing? | [
"",
"c#",
"unit-testing",
"design-patterns",
"interface",
""
] |
I have spent most of my web-development career in the Microsoft camp, but for different reasons I am trying to look at options.
Some years back I did a bit of Java/Struts development in eclipse, which was nice for its time but my memories of it are not close to what Visual Studio delivers today.
Some of the strengths of the MS stack as I see it are:
* Ease of use. Free tools (express
editions), easy to set up, easy to deploy, loads of components and
support, even for cutting edge
features like ajax and jQuery.
* Intellisense, so that the API
reference is there as you need it.
* Size of the community. Things like www.asp.net,
with the free video tutorials,
samples, documentation etc. Free,
official and reliably updated
information from MSDN.
* Enterprise scalable and decent
performance.
* Fully object-oriented, (semi)compiled
languages, allowing for sound design,
patterns and practices.
There are of course weaknesses as well, like:
* Pricing, once you go live with
anything semi-serious.
* Vendor lock-in.
* Total lack of cross-platform support.
I have spent some time this evening trying to get a grip on how things are outside of the microsoft world, and
I have found loads of PHP frameworks, Ruby on Rails and relatives, several Java frameworks and a few very odd alternatives.
Some of these seem very interesting, so I would like to hear from actual developers using the different frameworks, and try to find out how they compare to what MS has at the moment.
Which framework are you using, why is it great, what could be better and what kind of sites have you built using it?
Jeff & co made most of Stack Overflow in a few months using ASP.NET MVC. If you had to do the same using a non-MS framework and tools, what would you pick and why? | If I wanted to go opensource I would go with:
RAD web development: [tomcat](http://tomcat.apache.org) running [Railo](http://www.getrailo.com/index.cfm/products/railo-open-source/), a Java based open source CFML implementation because CFML is a good RAD tool. Railo performs well, is capable of clustering, is able to be extended through editing the source or adding your own extensions.
DB: [MySQL](http://www.mysql.com) for a DB backend because it performs well and just works.
IDE: - [Eclipse](http://www.eclipse.org/) + [CFEclipse](http://www.cfeclipse.org) because that is what's available, although I want some improvements. Since CFML is a dynamic language you don't have Intellisense, just context help for the api.
OS: Any opensource unix based OS. Probably [Ubuntu](http://www.ubuntu.com/).
MVC Frameworks: [Mach-II](http://www.mach-ii.com) or [Model-Glue](http://www.model-glue.com/) because I'm familiar with them, although I'm open to checking out [ColdBox](http://www.coldboxframework.com). | We have a pretty heavy investment in the Microsoft framework at the office and so I'm mostly doing ASP.NET MVC stuff now. If I were to pick an alternative at this point, I'd probably go with RubyOnRails. It has a very clean MVC implementation -- playing around with it made it pretty easy to get started with ASP.NET MVC when it came along. There's also a lot going on with improving testability -- particularly natural language-like testing frameworks coming out of the RoR camp with Cucumber, et. al. All the investment in testing makes TDD/BDD much more natural in that framework. | Non-Windows RAD Web development | [
"",
"java",
"asp.net",
"ruby-on-rails",
""
] |
I want to iterate through a table/view and then kick off some process (e.g. run a job, send an email) based on some criteria.
My arbitrary constraint here is that I want to do this inside the database itself, using T-SQL on a stored proc, trigger, etc.
Does this scenario require cursors, or is there some other native T-SQL row-based operation I can take advantage of? | Your best bet is a cursor. SQL being declarative and set based, any 'workaround you may find that tries to force SQL to do imperative row oriented operations is unreliable and may break. Eg. the optimizer may cut out your 'operation' from the execution, or do it in strange order or for an unexpected number of times.
The general bad name cursors get is when they are deployed instead of set based operations (like do a computation and update, or return a report) because the developer did not found a set oriented way of doing the same functionality. But for non-SQL operations (ie. launch a process) they are appropriate.
You may also use some variations on the cursor theme, like client side iterating through a result set. That is very similar in spirit to a cursor, although not using explicit cursors. | The standard way to do this would be SSIS. Just use an Execute SQL task to get the rows, and a For Each task container to iterate once per row. Inside the container, run whatever tasks you like, and they'll have access to the columns of each row. | SQL Server - standard pattern for doing row by row operations on a table/view | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
How do I know if PHP is compiled with SQLite support? If it's not, and I don't have the privileges to change it, what alternatives do I have to read an SQLite database besides access to php-sqlite3 functions? | I see that you specifically ask for SQLite v.3 support, so what you have to check is `PDO` and `PDO_sqlite` support. The native `php_sqlite` extension only supports SQLite v.2 in PHP 5 to 5.2. PHP 5.3 has a native `php_sqlite3` extension, but I guess this is not your case, as it has been released just yesterday.
I believe you're out of luck if your setup doesn't include that, as the suggested PEAR MDB2 is just an abstraction layer over existing drivers, it does not substitute them. | [`phpinfo();`](http://www.php.net/phpinfo) should tell you what's compiled in. Execute that:
```
<?php
phpinfo();
?>
```
and look for sqlite within the HTML output. | PHP with sqlite3 support | [
"",
"php",
"sqlite",
""
] |
I have a table with 12 timestamp columns and 3 other fields.
I can't change the field type on the timestamp columns.
I need to display all 15 fields to the user as m/d/y. Is there a way to format them all at the same time without having to apply DATE\_FORMAT to each one?
I'd rather not have to do
```
SELECT DATE_FORMAT(field, '%c/%e/%y') AS field
```
for each one if possible.
I'm using mySQL & PHP and I don't care where the conversion happens. | You can write a simple date conversion routine in php such as this:
```
function mysql2table($date) {
$new = explode("-",$date);
$a=array ($new[2], $new[1], $new[0]);
return $n_date=implode("-", $a);
}
```
Which I stole from here: <http://www.daniweb.com/code/snippet736.html#>
Then simply loop through your SQL column results checking if the value is a date and converting it. | Have you considered using a database layer like MDB2 or PDO, which can convert the types for you? MDB2 has a date type, that displays YYYY-MM-DD format but could easily be turned into m/d/y with strftime and strtotime.
An example of using MDB2:
```
$dsn = "mysql://user@pass/db"; (not sure about DSN format, you might have to poke the MDB2 documentation)
$connection = MDB2::connect ($dsn);
$connection->loadModule ("Extended");
$rows = $connection->getAll ("your query", array ('date', ...), $parameters, array (paramater-types), MDB2_FETCHMODE_OBJECT);
if (MDB2_Driver_Common::isError ($rows)) throw new Exception ("Error!");
else { foreach ($rows as $row) { ...Do something... } }
```
You can find more documentation about using MDB in this way at [MDB2 on InstallationWiki](http://www.installationwiki.org/MDB2#Shortcuts_for_Retrieving_Data). Also there you'll find a list of MDB2 datatypes and what they are mapped to for display values. Also, [Docs for MDB2\_Extended](http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Extended.html) will be a good source of info.
Edit: Obviously you'll have to use strftime and strtotime on each row separately. If you switch `MDB2_FETCHMODE_OBJECT` to `MDB2_FETCHMODE_ORDERED` or `MDB2_FETCHMODE_ASSOC` above, you can probably use a foreach loop to run strftime and strtotime on all of the rows that need to be reformatted. | Formating multiple mySQL date fields at the same time | [
"",
"php",
"mysql",
""
] |
I'm developing/testing a package in my local directory. I want to import it in the interpreter (v2.5), but sys.path does not include the current directory. Right now I type in `sys.path.insert(0,'.')`. Is there a better way?
Also,
```
from . import mypackage
```
fails with this error:
```
ValueError: Attempted relative import in non-package
``` | You can use relative imports only from in a module that was in turn imported as part of a package -- your script or interactive interpreter wasn't, so of course `from . import` (which means "import from the same package I got imported from") doesn't work. `import mypackage` will be fine once you ensure the parent directory of `mypackage` is in `sys.path` (how you managed to get your current directory *away* from `sys.path` I don't know -- do you have something strange in site.py, or...?)
To get your current directory back into `sys.path` there is in fact no better way than putting it there. | See the documentation for sys.path:
<http://docs.python.org/library/sys.html#sys.path>
To quote:
> If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first.
So, there's no need to monkey with sys.path if you're starting the python interpreter from the directory containing your module.
Also, to import your package, just do:
```
import mypackage
```
Since the directory containing the package is already in sys.path, it should work fine. | Import python package from local directory into interpreter | [
"",
"python",
""
] |
I have a method:
```
public void StoreUsingKey<T>(T value) where T : class, new() {
var idModel = value as IIDModel;
if (idModel != null)
Store<T>(idModel);
AddToCacheUsingKey(value);
}
```
that I would like to optionally call the following method, based on the `value` parameter's implementation of `IIDModel`.
```
public void Store<T>(T value) where T : class, IIDModel, new() {
AddModelToCache(value);
}
```
Is there a way to tell `Store<T>` that the `value` parameter from `StoreUsingKey<T>` implements `IIDModel`? Or am I going about this the wrong way?
Rich
**Answer**
Removing the `new()` constraint from each method allows the code to work. The problem was down to me trying to pass off an interface as an object which can be instantiated. | Removing the `new()` constraint from each method allows the code to work. The problem was down to me trying to pass off an interface as an object which can be instantiated. | You already are. By putting the IIDModel constraint on the Store<T> method, you're guaranteeing, that the value parameter implements IIDModel.
Oh, ok I see what you're saying now. How about this:
```
public void StoreUsingKey<T>(T value) where T : class, new() {
if (idModel is IIDModel)
Store<T>((IIDModel)idModel);
AddToCacheUsingKey(value);
}
```
**Edit yet again:** Tinister is right. This by itself won't do the trick. However, if your Store method looks like what [Joel Coehoorn posted](https://stackoverflow.com/questions/1132178/detecting-interfaces-in-generic-types/1132220#1132220), then it should work. | Detecting Interfaces in Generic Types | [
"",
"c#",
"generics",
"interface",
"constraints",
""
] |
Is there a way to require that a class have a particular abstract member? Something like this:
```
public interface IMaxLength
{
public static uint MaxLength { get; }
}
```
Or perhaps this:
```
public abstract class ComplexString
{
public abstract static uint MaxLength { get; }
}
```
I'd like a way enforce that a type (either through inheritance or an interface?) have a static member. Can this be done? | You could create a custom attribute that allows enforcing the requirement as a runtime guarantee. This is not a fully complete code sample (you need to call VerifyStaticInterfaces in your application startup, and you need to fill in the marked TODO) but it does show the essentials.
I'm assuming you're asking this so you can guarantee successful reflection-based calls to named methods.
```
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = true)]
internal sealed class StaticInterfaceAttribute : Attribute
{
private readonly Type interfaceType;
// This is a positional argument
public StaticInterfaceAttribute(Type interfaceType)
{
this.interfaceType = interfaceType;
}
public Type InterfaceType
{
get
{
return this.interfaceType;
}
}
public static void VerifyStaticInterfaces()
{
Assembly assembly = typeof(StaticInterfaceAttribute).Assembly;
Type[] types = assembly.GetTypes();
foreach (Type t in types)
{
foreach (StaticInterfaceAttribute staticInterface in t.GetCustomAttributes(typeof(StaticInterfaceAttribute), false))
{
VerifyImplementation(t, staticInterface);
}
}
}
private static void VerifyInterface(Type type, Type interfaceType)
{
// TODO: throw TypeLoadException? if `type` does not implement the members of `interfaceType` as public static members.
}
}
internal interface IMaxLength
{
uint MaxLength
{
get;
}
}
[StaticInterface(typeof(IMaxLength))]
internal class ComplexString
{
public static uint MaxLength
{
get
{
return 0;
}
}
}
``` | This is impossible. Because abstract and virtual method calls are stored in an *object* though its virtual function pointer table, there is no way that you can enforce any interface requirement on its non-instance members. Calling a static member has no object bound to it, therefore there is no virtual pointer table available.
This isn't a limitation, its just how it is. There is no reason why this would ever be necessary or useful. If you want to enforce an interface, you must do it though instance members. | c#: Inherited/interface static member? | [
"",
"c#",
"oop",
"inheritance",
"interface",
"static",
""
] |
lets say we have a link
```
<a href="/something" target="_new">blah</a>
```
and now i want a button to do the same thing as the link does, without using jquery.
does anyone have experience with something like that?
**edit:**
This needs to be a link that uses target="\_new" because doing that instead of a straight popup is a workaround for some problems IE6 has with opening downloads in popups.
In short: i have a very good reason for using a link, but i started out with a button, so it would be good to not have to style my link to look like button if i can do something with javascript. | No scripting required:
```
<html>
<body>
<form method="get" action="http://stackoverflow.com" target="_blank">
<div><button type="submit">Click me</button></div>
</form>
</body>
</html>
``` | Try using [window.open()](http://www.google.com/search?client=safari&rls=en-us&q=window.open&ie=UTF-8&oe=UTF-8) You may experience problems with pop-up blockers in browsers. | mimic target="_new" for a button | [
"",
"javascript",
"html",
""
] |
Suppose `myapp/foo.py` contains:
```
def info(msg):
caller_name = ????
print '[%s] %s' % (caller_name, msg)
```
And `myapp/bar.py` contains:
```
import foo
foo.info('Hello') # => [myapp.bar] Hello
```
I want `caller_name` to be set to the `__name__` attribute of the calling functions' module (which is 'myapp.foo') in this case. How can this be done? | Check out the inspect module:
`inspect.stack()` will return the stack information.
Inside a function, `inspect.stack()[1]` will return your caller's stack. From there, you can get more information about the caller's function name, module, etc.
See the docs for details:
<http://docs.python.org/library/inspect.html>
Also, Doug Hellmann has a nice writeup of the inspect module in his PyMOTW series:
<http://pymotw.com/2/inspect/index.html#module-inspect>
EDIT: Here's some code which does what you want, I think:
```
import inspect
def info(msg):
frm = inspect.stack()[1]
mod = inspect.getmodule(frm[0])
print '[%s] %s' % (mod.__name__, msg)
``` | Confronted with a similar problem, I have found that **sys.\_current\_frames()** from the sys module contains interesting information that can help you, without the need to import inspect, at least in specific use cases.
```
>>> sys._current_frames()
{4052: <frame object at 0x03200C98>}
```
You can then "move up" using f\_back :
```
>>> f = sys._current_frames().values()[0]
>>> # for python3: f = list(sys._current_frames().values())[0]
>>> print f.f_back.f_globals['__file__']
'/base/data/home/apps/apricot/1.6456165165151/caller.py'
>>> print f.f_back.f_globals['__name__']
'__main__'
```
For the filename you can also use f.f\_back.f\_code.co\_filename, as suggested by Mark Roddy above. I am not sure of the limits and caveats of this method (multiple threads will most likely be a problem) but I intend to use it in my case. | Get __name__ of calling function's module in Python | [
"",
"python",
"stack-trace",
"introspection",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.