Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have an HTML table that looks like this:
```
-------------------------------------------------
|Column 1 |Column 2 |
-------------------------------------------------
|this is the text in column |this is the column |
|one which wraps |two test |
-------------------------------------------------
```
But I want it to hide the overflow. The reason here is that the text contains a link to more details, and having the "wrapping" wastes lots of space in my layout. It should like this (without increasing the widths of the columns or the table, because they'll go off the screen/create a horizontal scrollbar otherwise):
```
-------------------------------------------------
|Column 1 |Column 2 |
-------------------------------------------------
|this is the text in column |this is the column |
-------------------------------------------------
```
I've tried lots of different CSS techniques to try to get this, but I can't get it to turn out right. Mootables is the only thing I've found that does this: <http://joomlicious.com/mootable/>, but I can't figure out how they do it. Does anyone know how I can do this with my own table using CSS and/or Javascript, or how Mootables does it?
Sample HTML:
```
<html><body>
<table width="300px">
<tr>
<td>Column 1</td><td>Column 2</td>
</tr>
<tr>
<td>this is the text in column one which wraps</td>
<td>this is the column two test</td>
</tr>
</table></body></html>
``` | Use the CSS property [white-space: nowrap](http://www.w3schools.com/cssref/pr_text_white-space.asp) and [overflow: hidden](http://www.w3schools.com/cssref/pr_pos_overflow.asp) on your td.
## Update
Just saw your comment, not sure what I was thinking, I've done this so many times I forgot how I do it. This is approach that works well in most browsers for me... rather than trying to constrain the td, I use a div inside the td that will handle the overflow instance. This has a nice side effect of being able to add your padding, margins, background colors, etc. to your div rather than trying to style the td.
```
<html>
<head>
<style>
.hideextra { white-space: nowrap; overflow: hidden; text-overflow:ellipsis; }
</style>
</head>
<body>
<table style="width: 300px">
<tr>
<td>Column 1</td><td>Column 2</td>
</tr>
<tr>
<td>
<div class="hideextra" style="width:200px">
this is the text in column one which wraps</div></td>
<td>
<div class="hideextra" style="width:100px">
this is the column two test</div></td>
</tr>
</table>
</body>
</html>
```
As a bonus, IE will place an ellipsis in the case of an overflow using the browser-specific text-overflow:ellipsis style. There is a way to [do the same in FireFox](http://www.jide.fr/emulate-text-overflowellipsis-in-firefox-with-css) automatically too, but I have not tested it myself.
## Update 2
I started using [this truncation code](http://mattsnider.com/css/css-string-truncation-with-ellipsis/) by Justin Maxwell for several months now which works properly in FireFox too. | This trick here is using the esoteric `table-layout:fixed` rule
This CSS ought to work against your sample HTML:
```
table {table-layout:fixed}
td {overflow:hidden; white-space:nowrap}
```
You also ought to specify explicit column widths for the `<td>`s.
The `table-layout:fixed` rule says "The cell widths of this table depend on what I say, not on the actual content in the cells". This is useful normally because the browser can begin displaying the table after it has received the first `<tr>`. Otherwise, the browser has to receive the entire table before it can compute the column widths. | CSS/Javascript to force html table row on a single line | [
"",
"javascript",
"html",
"css",
""
] |
I need to use C++ to read in text with spaces, followed by a numeric value.
For example, data that looks like:
```
text1
1.0
text two
2.1
text2 again
3.1
```
can't be read in with 2 `"infile >>"` statements. I'm not having any luck with `getline`
either. I ultimately want to populate a `struct` with these 2 data elements. Any ideas? | The standard IO library isn't going to do this for you alone, you need some sort of simple parsing of the data to determine where the text ends and the numeric value begins. If you can make some simplifying assumptions (like saying there is exactly one text/number pair per line, and minimal error recovery) it wouldn't be too bad to getline() the whole thing into a string and then scan it by hand. Otherwise, you're probably better off using a regular expression or parsing library to handle this, rather than reinventing the wheel. | Why? You can use getline providing a space as line separator. Then stitch extracted parts if next is a number. | Reading a file of mixed data into a C++ string | [
"",
"c++",
"stl",
""
] |
I am writing a crawler in Python, in order to make Ctrl+C not to cause my crawler to start over in next run, I need to save the processing deque in a text file (one item per line) and update it every iteration, the update operation needs to be super fast. In order not to reinvent the wheel, I am asking if there is an established module to do this? | As an alternative, you could set up an exit function, and pickle the deque on exit.
[Exit function](http://docs.python.org/library/sys.html#sys.exitfunc)
[Pickle](http://docs.python.org/library/pickle.html) | You should be able to use [pickle](http://docs.python.org/library/pickle.html) to serialize your lists. | Save a deque in a text file | [
"",
"python",
"web-crawler",
""
] |
What is the point of having a dynamic class on which you can call methods that may, or may not be there? | The point is that you'll usually be confident that the method will be present (or handled dynamically - e.g. a `FindByAuthor` method in a "book repository" class which is translated into an appropriate SQL query) but that you don't know the static type - or where the interfaces are fairly weakly typed (e.g. the Office COM APIs).
I wouldn't expect dynamic typing to be useful *very* often in C# - but when it's handy, I suspect it'll be very, very handy. | Primarily it allows C# 4 to interop much better with objects provided by the DLR using languages like Python. It also allows much easier interop with typical COM objects without the need to create interop assemblies. | C# 4.0 Dynamic features | [
"",
"c#",
""
] |
How do you apply 'or' to all values of a list in Python? I'm thinking something like:
```
or([True, True, False])
```
or if it was possible:
```
reduce(or, [True, True, False])
``` | The built-in function `any` does what you want:
```
>>> any([True, True, False])
True
>>> any([False, False, False])
False
>>> any([False, False, True])
True
```
`any` has the advantage over `reduce` of shortcutting the test for later items in the sequence once it finds a true value. This can be very handy if the sequence is a generator with an expensive operation behind it. For example:
```
>>> def iam(result):
... # Pretend this is expensive.
... print "iam(%r)" % result
... return result
...
>>> any((iam(x) for x in [False, True, False]))
iam(False)
iam(True)
True
>>> reduce(lambda x,y: x or y, (iam(x) for x in [False, True, False]))
iam(False)
iam(True)
iam(False)
True
```
If your Python's version doesn't have `any()`, `all()` builtins then they are easily implemented as [Guido van Rossum suggested](http://www.artima.com/weblogs/viewpost.jsp?thread=98196):
```
def any(S):
for x in S:
if x:
return True
return False
def all(S):
for x in S:
if not x:
return False
return True
``` | No one has mentioned it, but "`or`" is available as a function in the operator module:
```
from operator import or_
```
Then you can use `reduce` as above.
Would always advise "`any`" though in more recent Pythons. | How do you apply 'or' to all values of a list in Python? | [
"",
"python",
"list",
"reduce",
""
] |
Is there a way to monitor a gmail account using imaplib without polling gmail each time I want to see if there is new mail. Or in other words, I just want the script to be notified of a new message so I can process it right away instead of any lag time between polls.
I see that the IMAP protocol supports this with the IDLE command, but I can't see anything documented with it in the imaplib docs, so any help with this would be great! | There isn't something in imaplib that does this, AFAIK (disclamer: I know very little about Python), however, it seems that someone has implemented an IDLE extension for Python which has the same interface as imaplib (which you can swap out with no changes to existing code, apparently):
<https://github.com/imaplib2/imaplib2> | Check out [ProcImap](http://packages.python.org/ProcImap/). It's a more abstract framework on top of libimap and libimap2, providing a nice solution to handle IMAP services. Looks like just the stuff you are looking for, and for me as well. I'm right having the same problem with you and just found ProcImap. Gonna try it for myself. | How do I enable push-notification for IMAP (Gmail) using Python imaplib? | [
"",
"python",
"gmail",
"imap",
""
] |
Sometimes I create some quick personal projects using [C#](http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29) with [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) or [WPF](http://en.wikipedia.org/wiki/Windows_Presentation_Foundation). I have noticed that managed applications can take 2x or 3x times longer to start compared with native applications.
I have written a "Quick Notes" application, however it isn't very "quick". :-(
What are some techniques to speed up the initialization of Windows Forms/WPF applications? | Check out [NGen](http://msdn.microsoft.com/en-us/magazine/cc163808.aspx)
Also, if you are loading lots of data on load, move it to another thread and show an indicator or something (while it's loading) so at least the form pops up quickly, even if it takes a little longer for the actual data to load. | .NET 3.5 SP1 does tend to make start up a little quicker. Also see a [series of blog posts](http://code.logos.com/blog/2008/09/displaying_a_splash_screen_with_c_introduction.html) on putting up a splash screen (in native C++) while starting the WPF application at the Logos Blog. | How to speed up the initialization of a .NET client application (Windows Forms or WPF)? | [
"",
"c#",
".net",
"wpf",
"winforms",
"winapi",
""
] |
I have taken an AI course, and the teacher asked us to implement a game that makes use of one of the AI algorithms. Here is where I need a bit of help:
* I don't know to what kind of games each algorithm is applied
* if you could just give an example of a game or game type and the algorithm it uses, I would appreciate it
I don't need any coding help, I can manage that (my language of choice is Java). I only need a little help on selecting an algorithm. | In adjunct to Ben's answer, a good combo is alpha-beta pruning along with a game like connect 4. The heuristic for something like tic-tac-toe is too simple, and for chess, too complex. But connect 4 or a similiar "middle of the road" game can be an excellent place to see how the heuristic makes a big difference in both efficiency and quality, and it's also complex enough to even get some "niche" heuristics that can win some scenarios over other, generally better heuristics. The rules of connect 4 in particular are simple enough that it's very easy to come up with your own successful heuristics to see these things in action.
Another common AI to play with is A\* for pathfinding, such as unit travel in an RTS or sandbox environment. | [Alpha-beta pruning](http://en.wikipedia.org/wiki/Alpha_beta_pruning) is a good one for game trees in general, and turn-based games like chess and tic-tac-toe in particular. | I'm learning AI, what game could I implement to put it to practice? | [
"",
"java",
"algorithm",
"artificial-intelligence",
"game-engine",
""
] |
I'm not familiar with ASP, but am helping someone out with their website as a side project. I am trying to call Apache FOP (a java application) from ASP using VB. I have seen simple examples using the GetObject('java:...') constuct, but I don't know how to pass and retrieve binary data from a java object.
Ideally, I would do this all in memory--I would prefer to not have to write my data to disk, call FOP on that file (which will read, and then write a new file), and then re-read the data off of disk. The site isn't *that* busy so I could do this, but it just doesn't seem efficient. | I figured out a workaround. This is for IIS running on a Win 2k3 Server--older versions will be much easier.
First I created a subdirectory off the main site (for security purposes) and attached a new application pool to that directory. The new application pool needs to run as Local System. I couldn't get fop.bat to work, even running as local system, but I could call java, so I put the entire fop commandline into my asp script, similar to this snippet:
```
Dim shell, foppath, workpath
Set shell = Server.CreateObject("WScript.Shell")
foppath = Server.MapPath("/fop/")
workpath = Server.MapPath("/tmp/")
shell.CurrentDirectory = foppath
Dim commandline
commandline = "java -Denv.windir=C:\WINDOWS -cp """
'set classpath
commandline = commandline & foppath & "\build\fop.jar;"
commandline = commandline & foppath & "\build\fop-sandbox.jar;"
commandline = commandline & foppath & "\build\fop-hyph.jar;"
commandline = commandline & foppath & "\lib\xml-apis-1.3.04.jar;"
commandline = commandline & foppath & "\lib\xml-apis-ext-1.3.04.jar;"
commandline = commandline & foppath & "\lib\xercesImpl-2.7.1.jar;"
commandline = commandline & foppath & "\lib\xalan-2.7.0.jar;"
commandline = commandline & foppath & "\lib\serializer-2.7.0.jar;"
commandline = commandline & foppath & "\lib\batik-all-1.7.jar;"
commandline = commandline & foppath & "\lib\xmlgraphics-commons-1.3.1.jar;"
commandline = commandline & foppath & "\lib\avalon-framework-4.2.0.jar;"
commandline = commandline & foppath & "\lib\commons-io-1.3.1.jar;"
commandline = commandline & foppath & "\lib\commons-logging-1.0.4.jar;"
commandline = commandline & foppath & "\lib\jai_imageio.jar;"
commandline = commandline & foppath & "\lib\fop-hyph.jar;"
commandline = commandline & """ org.apache.fop.cli.Main "
commandline = commandline & workpath & "/file.fo "
commandline = commandline & workpath & "/file.pdf "
Dim ResultCode
ResultCode = Shell.Run(commandline,,True) ' True = Wait for FOP to finish
```
Afterwards, I make sure I cleanup my temp files, etc. Perhaps not the most elegant solution, but given the need, I'm sure it will work for a long time. | I wouldn't worry about efficiency until I had observed a problem and measurements told me that the FOP solution was the culprit.
I'd propose an asynch call to a web service. Sent a message containing the XML input stream and the XSL-T stylesheet. Have the service write the PDF to its local disk. Add a mailbox to your UI to alert users when the PDF was ready to be picked up. Click on the link, and the PDF is streamed to the browser. The user can view or save to their local disk as they wish.
Asynch is good in this case because you don't know how long the transform might take. Why make the user wait? Let them check back later. An AJAX call to check for the new PDF would be elegant. | How can I call java from asp? | [
"",
"java",
"asp-classic",
"vbscript",
""
] |
I'm guessing there's something really basic about C# inheritance that I don't understand. Would someone please enlighten me? | Sometimes, when subclassing, you want to restrict the conditions required to create an instance of the class.
Let me give you an example. If classes did inherit their superclass constructors, all classes would have the parameterless constructor from `Object`. Obviously that's not correct. | If you think about what would happen if constructors **were** inherited, you should start to see the problem.
As [nearly every type in .NET inherits from Object](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/not-everything-derives-from-object) (which has a parameterless constructor), that means almost every type that you create would be forced to have a parameterless constructor. But there are **many** types where a parameterless constructor doesn't make sense.
There would also be a problem with versioning. If a new version of your base type appears with a new constructor, you would automatically get a new constructor in your derived type. This would be a bad thing, and a specific instance of the [fragile base class](https://en.wikipedia.org/wiki/Fragile_base_class) problem.
There's also a more philosophical argument. Inheritance is about type responsibilities (this is what I do). Constructors are about type collaboration (this is what I need). So inheriting constructors would be mixing type responsibility with type collaboration, whereas those two concepts should really remain separate. | Why are constructors not inherited in C#? | [
"",
"c#",
"oop",
"inheritance",
"constructor",
""
] |
I have a problem drawing something quickly in .NET. I don't think that any thing in particular should take much time, but on every machine I've tried it on, I get serious issues. This is implemented in vs2008 .NET, using C# (with some stuff in C++, but nothing relevant to the drawing).
I have three screens, and the user should be able to toggle between them with no lag. On the first screen, there are four buttons, eight user controls consisting of two buttons and 6 labels each, a text field, and a dropdown box. I don't think of it as being that much.
On the second screen, I have four labels, six buttons, and two controls that have six buttons, one opengl drawing context, and about ten labels each.
On the third screen, I have one opengl context and 10 buttons.
Flipping from any screen to any screen takes literally about a second. For instance, if I flip from the second screen to the first, the entire application blanks out, showing the background screen, and then the first screen is drawn. Many times, a screen is drawn piecemeal, as if the machine were deliberately handcrafting delicate and delicious letters in a factory in Sweden and then shipping each one individually to my screen. I exaggerate, and I want to make that clear, because I don't think Swedes are as slow as this redraw.
The first and second screen are drawn in memory, and stored there, with just a '.Hide()' and '.Show()' to make them appear and disappear. Double buffering doesn't seem to matter. The third screen is drawn anew each time, and appears to take the same amount of time to draw as the first and second.
Any thoughts? What could be going on? How can I track it down?
Thanks!
Edit: I should add that any C++ processing and the like happens in its own thread. There is the occasional MethodInvoke to draw the results of the operation to the screen, but this problem happens without calling any functions, just by pressing buttons to go from one screen to the next. | In addition to the profiler that was mentioned, you might also turn off your OpenGL contexts. If you notice a speed-up, then you'll know it's your graphics stuff, and you can focus your optimisations accordingly.
Points awarded for Swedish humour. | > How can I track it down?
dotTrace - <http://www.jetbrains.com/profiler/> | .NET C# drawing slowly | [
"",
"c#",
".net",
"drawing",
"performance",
""
] |
How do I use the `json_encode()` function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object? | ```
$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
```
The function `json_encode` needs PHP >= 5.2 and the **php-json** package - as mentioned [here](https://stackoverflow.com/questions/7318191/enable-json-encode-in-php)
Modern PHP versions support [mysqli\_fetch\_all()](https://php.net/mysqli_fetch_all) function that will get your array in one go
```
$result = mysqli_query($conn, "SELECT ...");
$rows = mysqli_fetch_all($result); // list arrays with values only in rows
// or
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC); // assoc arrays in rows
print json_encode($rows);
``` | If you need to put selected rows in a distinct element of returned json, you can do it like this: first, get the `$rows` array like in the accepted answer and then put it in another array like this
```
print json_encode(['object_name' => $rows]);
``` | JSON encode MySQL results | [
"",
"php",
"mysql",
"json",
""
] |
So I have this app that checks for updates on the server getting a JSON response, each new update is put at the top of my list on a new div that is added via insertBefore using javascript.
All works just fine, but i'd like to add an animation effect when the div is added, i.e. "slowly" move the existing divs down, and add the new one at the top, Any pointers on how to do that ?
The application actually runs in facebook not using the iframe, I tried to use jquery but it does not seem to work on facebook, and looking at the code modifications that FB do, I assume other frameworks will have a similar problem. | Since you are looking to do it yourself you'll need to use setTimeout to repeatedly change the height of your div. The basic, quick and dirty code looks something like this:
```
var newDiv;
function insertNewDiv() {
// This is called when you realize something was updated
// ...
newDiv = document.createElement('div');
newDiv.style.height = "0px";
document.body.appendChild(newDiv);
setTimeout(slideInDiv, 0);
}
function slideInDiv(){
newDiv.style.height = newDiv.clientHeight + 10 + "px"; // Slowly make it bigger
if (newDiv.clientHeight < 100){
setTimeout(slideInDiv, 40); // 40ms is approx 25 fps
} else {
addContent();
}
}
function addContent(){
newDiv.innerHTML = "Done!";
}
```
Note that you may wish to make your animation code more general (pass in the ID, a callback function, etc) but for a basic animation this should get you started. | In jQuery, you can do the following:
```
$(myListItem).hide().slideDown(2000);
```
Otherwise, roll out a custom animation, using setTimeout and some CSS modifications. Here's a messy one I whipped up in a few minutes:
```
function anim8Step(height)
{
var item = document.getElementById('anim8');
item.style.height = height + 'px';
}
function anim8()
{
var item = document.getElementById('anim8');
var steps = 20;
var duration = 2000;
var targetHeight = item.clientHeight;
var origOverflow = item.style.overflow;
item.style.overflow = 'hidden';
anim8Step(0);
for(var i = 1; i < steps; ++i)
setTimeout('anim8Step(' + (targetHeight * i / steps) + ');', i / steps * duration);
setTimeout('var item = document.getElementById(\'anim8\'); item.style.height = \'auto\'; item.style.overflow = \'' + origOverflow + '\';', duration);
}
```
(I'm not so good at Javascript, so I'm sorry it's a mess.)
Basically, you set the overflow of the li (#anim8) to hidden so the contents don't overlap other elements' contents. Then, you set the height to 0 and increase it over time to the clientHeight. Then, you set the overflow back to whatever it was (this step probably isn't really needed) and remove the height attribute (just in case). | Animated insertBefore in javascript | [
"",
"javascript",
"user-interface",
"animation",
""
] |
How do you rename a table in [SQLite](http://en.wikipedia.org/wiki/SQLite) 3.0? | ```
ALTER TABLE `foo` RENAME TO `bar`
```
[SQLite Query Language: ALTER TABLE](http://www.sqlite.org/lang_altertable.html) | The answer remains to use "ALTER TABLE". But the main documentation page on this topic is pretty thick. What is needed is a simple example of how that works. You can find that here: <https://www.sqlitetutorial.net/sqlite-alter-table/>
To be precise, in the most basic case it looks like this:
```
ALTER TABLE existing_table
RENAME TO new_table;
```
I am not sure if the dot notation works, but I assume that the following is also correct:
```
ALTER TABLE existing_database.existing_table
RENAME TO new_database.new_table;
```
If you have spaces in the name, then you need to backticks that are included in the first accepted answer... so you may need something like this if you have spaces.
```
ALTER TABLE `existing databasename`.`existing tablename`
RENAME TO `newer databasename`.`newer tablename`;
``` | How to rename a table in SQLite 3.0? | [
"",
"sql",
"database",
"sqlite",
"rename",
"table-rename",
""
] |
I'm trying to unit test some code that looks like this:
```
def main():
parser = optparse.OptionParser(description='This tool is cool', prog='cool-tool')
parser.add_option('--foo', action='store', help='The foo option is self-explanatory')
options, arguments = parser.parse_args()
if not options.foo:
parser.error('--foo option is required')
print "Your foo is %s." % options.foo
return 0
if __name__ == '__main__':
sys.exit(main())
```
With code that looks like this:
```
@patch('optparse.OptionParser')
def test_main_with_missing_p4clientsdir_option(self, mock_optionparser):
#
# setup
#
optionparser_mock = Mock()
mock_optionparser.return_value = optionparser_mock
options_stub = Mock()
options_stub.foo = None
optionparser_mock.parse_args.return_value = (options_stub, sentinel.arguments)
def parser_error_mock(message):
self.assertEquals(message, '--foo option is required')
sys.exit(2)
optionparser_mock.error = parser_error_mock
#
# exercise & verify
#
self.assertEquals(sut.main(), 2)
```
I'm using [Michael Foord's Mock](http://www.voidspace.org.uk/python/mock.html), and nose to run the tests.
When I run the test, I get:
```
File "/Users/dspitzer/Programming/Python/test-optparse-error/tests/sut_tests.py", line 27, in parser_error_mock
sys.exit(2)
SystemExit: 2
----------------------------------------------------------------------
Ran 1 test in 0.012s
FAILED (errors=1)
```
The problem is that OptionParser.error does a sys.exit(2), and so main() naturally relies on that. But nose or unittest detects the (expected) sys.exit(2) and fails the test.
I can make the test pass by adding "return 2" under the parser.error() call in main() and removing the sys.exit() call from parser\_error\_mock(), but I find it distasteful to modify the code under test to allow a test to pass. Is there a better solution?
**Update**: [df](https://stackoverflow.com/users/3002/df)'s answer works, although the correct call is "self.assertRaises(SystemExit, sut.main)".
Which means the test passes whatever the number is in the sys.exit() in parser\_error\_mock(). Is there any way to test for the exit code?
BTW, the test is more robust if I add:
```
self.assertEquals(optionparser_mock.method_calls, [('add_option', ('--foo',), {'action': 'store', 'help': 'The foo option is self-explanatory'}), ('parse_args', (), {})])
```
at the end.
**Update 2**: I can test for the exit code by replacing "self.assertRaises(SystemExit, sut.main)" with:
```
try:
sut.main()
except SystemExit, e:
self.assertEquals(type(e), type(SystemExit()))
self.assertEquals(e.code, 2)
except Exception, e:
self.fail('unexpected exception: %s' % e)
else:
self.fail('SystemExit exception expected')
``` | As noted in my updates to my question, I had to modify [dF](https://stackoverflow.com/users/3002/df)'s answer to:
```
self.assertRaises(SystemExit, sut.main)
```
...and I came up with a few longer snippet to test for the exit code.
[Note: I accepted my own answer, but I will delete this answer and accept [dF](https://stackoverflow.com/users/3002/df)'s if he updates his.] | Will this work instead of `assertEquals`?
```
self.assertRaises(SystemExit, sut.main, 2)
```
This should catch the `SystemExit` exception and prevent the script from terminating. | How do I mock the Python method OptionParser.error(), which does a sys.exit()? | [
"",
"python",
"unit-testing",
"mocking",
"optparse",
""
] |
I'm writing a JavaSCript class that has a method that recursively calls itself.
```
Scheduler.prototype.updateTimer = function () {
document.write( this._currentTime );
this._currentTime -= 1000;
// recursively calls itself
this._updateUITimerHandler = window.setTimeout( arguments.callee , 1000 );
}
```
Property description:
```
_currentTime: the currentTime of the timer in miliseconds.
_updateUITimerHandler: stores the reference so can be used later with clearTimeout().
```
my problem is where I'm using recursion with setTimeout(). I know setTimeout() will accept some string to execute, or a reference to a function. since this function is method of an object, I don't know how to call it from outside. so I used the second format of setTimeout() and passed in a reference to the method itself. but it does not work. | Try this:-
```
Scheduler.prototype.startTimer = function() {
var self = this;
function updateTimer() {
this._currentTime -= 1000;
self.hTimer = window.setTimeout(updateTimer, 1000)
self.tick()
}
this.hTimer = window.setTimeout(updateTimer, 1000)
}
Scheduler.prototype.stopTimer = function() {
if (this.hTimer != null) window.clearTimeout(this.hTimer)
this.hTimer = null;
}
Scheduler.prototype.tick = function() {
//Do stuff on timer update
}
``` | Well the first thing to say is that if you're calling setTimeout but not changing the interval, you should be using setInterval.
edit (update from comment): you can keep a reference from the closure if used as a class and setInterval/clearInterval don't require re-referencing.
edit2: it's been pointed out that you wrote calle*e* which will work quite correctly and 100% unambiguously.
Out of completeness, this works:
```
function f()
{
alert('foo');
window.setTimeout(arguments.callee,5000);
}
f();
```
so I tried out document.write instead of alert and that is what appears to be the problem. doc.write is fraught with problems like this because of opening and closing the DOM for writing, so perhaps what you needed is to change the innerHTML of your target rather than doc.write | how to write a recursive method in JavaScript using window.setTimeout()? | [
"",
"javascript",
"recursion",
""
] |
I have problem with starting processes in impersonated context in ASP.NET 2.0.
I am starting new Process in my web service code. IIS 5.1, .NET 2.0
```
[WebMethod]
public string HelloWorld()
{
string path = @"C:\KB\GetWindowUser.exe";
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory = Path.GetDirectoryName(path);
startInfo.FileName = path;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.ErrorDialog = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
Process docCreateProcess = Process.Start(startInfo);
string errors = docCreateProcess.StandardError.ReadToEnd();
string output = docCreateProcess.StandardOutput.ReadToEnd();
}
```
The "C:\KB\GetWindowUser.exe" is console application containing following code:
```
static void Main(string[] args)
{
Console.WriteLine("Windows: " + WindowsIdentity.GetCurrent().Name);
}
```
When I invoke web service without impersonation, everything works fine.
When I turn on impersonation, following error is written in "errors" variable in web service code:
Unhandled Exception: System.Security.SecurityException: Access is denied.\r\n\r\n at System.Security.Principal.WindowsIdentity.GetCurrentInternal(TokenAccessLevels desiredAccess, Boolean threadOnly)\r\n at System.Security.Principal.WindowsIdentity.GetCurrent()\r\n at ObfuscatedMdc.Program.Main(String[] args)\r\nThe Zone of the assembly that failed was:\r\nMyComputer
Impersonated user is local administrator and has access to C:\KB\GetWindowUser.exe executable.
When I specify window user explicitly in ProcesStartInfo properties Domain, User and Password, I got following message:
<http://img201.imageshack.us/img201/5870/pstartah8.jpg>
Is it possible to start process with different credentials than ASPNET from asp.net (IIS 5.1) ? | You have to put privileged code into the GAC (or run in Full trust).
The code in the GAC must assert the XXXPermission, where XXX is what ever permission you are requesting, be it impersonation, access to the harddrive or what have you.
You should revert the assert immediately afterwords.
You should make sure that the API on your DLL that you put in the GAC has no opportunities for abuse. For example, if you were writing a website for letting users backup the server via a command line application, your API should old expose a method like "BackUp()" and not "LaunchAribitraryProcess(string path)"
The web.config file must have impersonation set up as well, or you will run into NTFS permission problems as well as CAS.
Here is the [complete explanation](http://msdn.microsoft.com/en-us/library/aa302425.aspx). | You might also try wrapping your code inside
```
using (Impersonator person = new Impersonator("domainName", "userName",
"password")
{
// do something requiring special permissions
}
```
as mentioned in
<http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.windowsforms/topic62740.aspx> | Process start and Impersonation | [
"",
"c#",
".net",
"iis-5",
""
] |
I'm using C# with [.NET](http://en.wikipedia.org/wiki/.NET_Framework) 3.5. Is it possible to serialize a block of code, transmit it somewhere, deserialize it, and then execute it?
An example usage of this would be:
```
Action<object> pauxPublish = delegate(object o)
{
if (!(o is string))
{
return;
}
Console.WriteLine(o.ToString());
};
Transmitter.Send(pauxPublish);
```
With some remote program doing:
```
var action = Transmitter.Recieve();
action("hello world");
```
My end goal is to be able to execute arbitrary code in a different process (which has no prior knowledge of the code). | **YES!!!**
We have done this for a very real case of performance. Doing this at runtime or using a DSL was not an option due to performance.
We compile the code into an assembly, and rip the IL out of the method. We then get all the metadata associated with this method and serialize the whole mess via XML, compress it, and put it in our database.
At re-hydration time, we re-constitute the IL with the metadata using the **DynamicMethod** class, and execute it.
We do this because of speed. We have thousands of little blocks of code. Unfortunately, to compile a block of code and run it on the fly takes at least 250 ms, which is way too slow for us. We took this approach, and it is working REALLY well. At run-time, it takes an unmeasurable amount of time to reconstitute the method and run it.
Only thing to keep an eye on... Signed assemblies and Unsigned assemblies cannot mix the serialized method data. | You could try to use [IronPython](http://en.wikipedia.org/wiki/IronPython) in your project. It's [trivial](http://www.python.org/doc/2.5.2/ref/exec.html) to do what you are asking in Python. The Python code could call your C# methods. As for security, you could execute the code in a restricted environment of some kind (one example is [RestrictedPython](http://pypi.python.org/pypi/RestrictedPython/)). | Is it possible to serialize a C# code block? | [
"",
"c#",
"serialization",
""
] |
I need a way of calling a web page from inside my .net appliction.
But i just want to send a request to the page and not worry about the response.
As there are times when the response can take a while so i dont want it to hang the appliction.
I have been trying in side the page\_load event
```
WebClient webC = new WebClient();
Uri newUri = new Uri("http://localhost:49268/dosomething.aspx");
webC.UploadStringAsync(newUri, string.Empty);
```
Even though its set to Async, it still seams to hang as the page wont finish rendering until the threads have finsished | Doak, Was almost there, but each time I put any of the request in a sepreate thread the page still wouldn't render until all the thread had finished running.
The best way I found was adjusting Doak's method, and just sticking a timeout in there and swallowing the error.
I know its a hack but it does work :P
```
WebRequest wr = WebRequest.Create("http://localhost:49268/dostuff.aspx");
wr.Timeout = 3500;
try
{
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
}
catch (Exception ex)
{
//We know its going to fail but that dosent matter!!
}
``` | This should work for you:
```
System.Net.WebClient client = new System.Net.WebClient();
client.DownloadDataAsync(new Uri("http://some.url.com/some/resource.html"));
```
The WebClient class has events for notifying the caller when the request is completed, but since you don't care there shouldn't be anything else to it. | Call a webpage from c# in code | [
"",
"c#",
"asp.net",
".net-2.0",
""
] |
I have an XML feed (which I don't control) and I am trying to figure out how to detect the volume of certain attribute values within the document.
I am also parsing the XML and separating attributes into Arrays (for other functionality)
Here is a sample of my XML
```
<items>
<item att1="ABC123" att2="uID" />
<item att1="ABC345" att2="uID" />
<item att1="ABC123" att2="uID" />
<item att1="ABC678" att2="uID" />
<item att1="ABC123" att2="uID" />
<item att1="XYZ123" att2="uID" />
<item att1="XYZ345" att2="uID" />
<item att1="XYZ678" att2="uID" />
</items>
```
I want to find the volume nodes based on each att1 value. Att1 value will change. Once I know the frequency of att1 values I need to pull the att2 value of that node.
I need to find the TOP 4 items and pull the values of their attributes.
All of this needs to be done in C# code behind.
If I was using Javascript I would create an associative array and have att1 be the key and the frequency be the value. But since I'm new to c# I don't know how to duplicate this in c#.
So I believe, first I need to find all unique att1 values in the XML. I can do this using:
```
IEnumerable<string> uItems = uItemsArray.Distinct();
// Where uItemsArray is a collection of all the att1 values in an array
```
Then I get stuck on how I compare each unique att1 value to the whole document to get the volume stored in a variable or array or whatever data set.
Here is the snippet I ended up using:
```
XDocument doc = XDocument.Load(@"temp/salesData.xml");
var topItems = from item in doc.Descendants("item")
select new
{
name = (string)item.Attribute("name"),
sku = (string)item.Attribute("sku"),
iCat = (string)item.Attribute("iCat"),
sTime = (string)item.Attribute("sTime"),
price = (string)item.Attribute("price"),
desc = (string)item.Attribute("desc")
} into node
group node by node.sku into grp
select new {
sku = grp.Key,
name = grp.ElementAt(0).name,
iCat = grp.ElementAt(0).iCat,
sTime = grp.ElementAt(0).sTime,
price = grp.ElementAt(0).price,
desc = grp.ElementAt(0).desc,
Count = grp.Count()
};
_topSellers = new SalesDataObject[4];
int topSellerIndex = 0;
foreach (var item in topItems.OrderByDescending(x => x.Count).Take(4))
{
SalesDataObject topSeller = new SalesDataObject();
topSeller.iCat = item.iCat;
topSeller.iName = item.name;
topSeller.iSku = item.sku;
topSeller.sTime = Convert.ToDateTime(item.sTime);
topSeller.iDesc = item.desc;
topSeller.iPrice = item.price;
_topSellers.SetValue(topSeller, topSellerIndex);
topSellerIndex++;
}
```
Thanks for all your help! | If you have the values, you should be able to use LINQ's GroupBy...
```
XDocument doc = XDocument.Parse(xml);
var query = from item in doc.Descendants("item")
select new
{
att1 = (string)item.Attribute("att1"),
att2 = (string)item.Attribute("att2") // if needed
} into node
group node by node.att1 into grp
select new { att1 = grp.Key, Count = grp.Count() };
foreach (var item in query.OrderByDescending(x=>x.Count).Take(4))
{
Console.WriteLine("{0} = {1}", item.att1, item.Count);
}
``` | Are you using .NET 3.5? (It looks like it based on your code.) If so, I suspect this is pretty easy with LINQ to XML and LINQ to Objects. However, I'm afraid it's not clear from your example what you want. Do all the values with the same att1 *also* have the same att2? If so, it's something like:
```
var results = (from element in items.Elements("item")
group element by element.Attribute("att1").Value into grouped
order by grouped.Count() descending
select grouped.First().Attribute("att2").Value).Take(4);
```
I haven't tested it, but I *think* it should work...
* We start off with all the item elements
* We group them (still as elements) by their att1 value
* We sort the groups by their size, descending so the biggest one is first
* From each group we take the first element to find its att2 value
* We take the top four of these results | Find frequency of values in an Array or XML (C#) | [
"",
"c#",
"xml",
"linq",
"linq-to-xml",
"frequency",
""
] |
I am using NetBeans for PHP 6.5.
In my code I frequently use the following type of command:
```
if (($row = $db->get_row($sql))) {
return $row->folder;
} else {
return FALSE;
}
```
Netbeans tells me that I should not be using assignments in the IF statement.
Why ? | They are not bad, but they can lead to dangerous mistakes.
In c like languages, where an assignment is an expression, (to support for example a=b=c=1;) a common error is:
```
if (a = 1) { .. }
```
But you wanted to have
```
if (a == 1) { .. }
```
Some developers have learned to type
```
if (1 == a) { .. }
```
To create an error if one '=' is forgotten. But I think that it does not improve the readability.
However modern compilers, give a warning if you write
```
if (a = 1) { .. }
```
which I think is a better solution. In that case you are forced to check if it was what you really meant. | It's probably trying to help you avoid the dreaded typo:
> ```
> if(a = b)
> //logic error
> ```
Although I would expect an enviroment smart enough to warn you about that, to also be smart enough to have "oh, don't worry about that case" conditions. | why are assignments in conditions bad? | [
"",
"php",
"coding-style",
""
] |
I work off of a multi-user Windows Server, and the rdpclip bug bites us all daily. We usually just open task manager and kill then restart rdpclip, but that's a pain in the butt. I wrote a powershell script for killing then restarting rdpclip, but no one's using it because it's a script (not to mention the execution policy is restricted for the box). I'm trying to write a quick and dirty windows app where you click a button to kill rdpclip and restart it. But I want to restrict it to the current user, and can't find a method for the Process class that does this. So far, here's what I have:
```
Process[] processlist = Process.GetProcesses();
foreach(Process theprocess in processlist)
{
if (theprocess.ProcessName == "rdpclip")
{
theprocess.Kill();
Process.Start("rdpclip");
}
}
```
I'm not certain, but I think that's going to kill all the rdpclip processes. I'd like to select by user, like my powershell script does:
```
taskkill /fi "username eq $env:username" /im rdpclip.exe
& rdpclip.ex
```
I suppose I could just invoke the powershell script from my executable, but that seems fairly kludgy.
Apologies in advance for any formatting issues, this is my first time here.
UPDATE: I also need to know how to get the current user and select only those processes. The WMI solution proposed below doesn't help me get that.
UPDATE2: Ok, I've figured out how to get the current user, but it doesn't match the process user over Remote Desktop. Anyone know how to get username instead of the SID?
Cheers,
fr0man | Ok, here's what I ended up doing:
```
Process[] processlist = Process.GetProcesses();
bool rdpclipFound = false;
foreach (Process theprocess in processlist)
{
String ProcessUserSID = GetProcessInfoByPID(theprocess.Id);
String CurrentUser = WindowsIdentity.GetCurrent().Name.Replace("SERVERNAME\\","");
if (theprocess.ProcessName == "rdpclip" && ProcessUserSID == CurrentUser)
{
theprocess.Kill();
rdpclipFound = true;
}
}
Process.Start("rdpclip");
if (rdpclipFound)
{
MessageBox.Show("rdpclip.exe successfully restarted"); }
else
{
MessageBox.Show("rdpclip was not running under your username. It has been started, please try copying and pasting again.");
}
}
``` | Instead of using GetProcessInfoByPID, I just grab the data from StartInfo.EnvironmentVariables.
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Security.Principal;
using System.Runtime.InteropServices;
namespace KillRDPClip
{
class Program
{
static void Main(string[] args)
{
Process[] processlist = Process.GetProcesses();
foreach (Process theprocess in processlist)
{
String ProcessUserSID = theprocess.StartInfo.EnvironmentVariables["USERNAME"];
String CurrentUser = Environment.UserName;
if (theprocess.ProcessName.ToLower().ToString() == "rdpclip" && ProcessUserSID == CurrentUser)
{
theprocess.Kill();
}
}
}
}
}
``` | How do you kill a process for a particular user in .NET (C#)? | [
"",
"c#",
".net",
"process",
""
] |
Given the following classes and controller action method:
```
public School
{
public Int32 ID { get; set; }
publig String Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street1 { get; set; }
public string City { get; set; }
public String ZipCode { get; set; }
public String State { get; set; }
public String Country { get; set; }
}
[Authorize(Roles = "SchoolEditor")]
[AcceptVerbs(HttpVerbs.Post)]
public SchoolResponse Edit(Int32 id, FormCollection form)
{
School school = GetSchoolFromRepository(id);
UpdateModel(school, form);
return new SchoolResponse() { School = school };
}
```
And the following form:
```
<form method="post">
School: <%= Html.TextBox("Name") %><br />
Street: <%= Html.TextBox("Address.Street") %><br />
City: <%= Html.TextBox("Address.City") %><br />
Zip Code: <%= Html.TextBox("Address.ZipCode") %><br />
Sate: <select id="Address.State"></select><br />
Country: <select id="Address.Country"></select><br />
</form>
```
I am able to update both the School instance and the Address member of the school. This is quite nice! Thank you ASP.NET MVC team!
However, how do I use jQuery to select the drop down list so that I can pre-fill it? I realize that I could do this server side but there will be other dynamic elements on the page that affect the list.
The following is what I have so far, and it does not work as the selectors don't seem to match the IDs:
```
$(function() {
$.getJSON("/Location/GetCountryList", null, function(data) {
$("#Address.Country").fillSelect(data);
});
$("#Address.Country").change(function() {
$.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) {
$("#Address.State").fillSelect(data);
});
});
});
``` | From [Google Groups](http://groups.google.com/group/jquery-en/browse_thread/thread/ba072168939b245a?pli=1):
> Use two backslashes before each special character.
>
> A backslash in a jQuery selector escapes the next character. But you need
> two of them because backslash is also the escape character for JavaScript
> strings. The first backslash escapes the second one, giving you one actual
> backslash in your string - which then escapes the next character for jQuery.
So, I guess you're looking at
```
$(function() {
$.getJSON("/Location/GetCountryList", null, function(data) {
$("#Address\\.Country").fillSelect(data);
});
$("#Address\\.Country").change(function() {
$.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) {
$("#Address\\.State").fillSelect(data);
});
});
});
```
Also check out [How do I select an element by an ID that has characters used in CSS notation?](https://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/) on the jQuery FAQ. | You can't use a jQuery id selector if the id contains spaces. Use an attribute selector:
```
$('[id=foo bar]').show();
```
If possible, specify element type as well:
```
$('div[id=foo bar]').show();
``` | How do I get jQuery to select elements with a . (period) in their ID? | [
"",
"javascript",
"jquery",
"jquery-selectors",
""
] |
I am making a game server for a turn based game. Not a web based server, but a process-based one. I want it to be scalable and I want the development process to go as smoothly as possible. I haven't used Java in forever and I need to brush up on my skills, so I really have no idea what is out there framework or tool-wise. Right now it looks like I am going to use [Terracotta](http://www.terracotta.org/web/display/orgsite/Home) due to its clustering capabilities. I was just wondering if anything besides this that would make developing a TCP based game server easier? | You might want to take a look at [Project Darkstar](http://www.projectdarkstar.com/). | Have a look at Marauroa. It is a client server framework for turn based games. There is even a MORPG based on it, with the turn time set down to only 300ms.
But it is not designed for cluster support.
<http://arianne.sf.net/wiki/index.php/Marauroa> | Good tools/frameworks to develop a game server in Java? | [
"",
"java",
"frameworks",
""
] |
I'm currently having a problem with a ShoppingCart for my customer.
He wants to be able to add Text between the CartItems so I was wondering if there is some way to still only have one List.
My solution would be to have two lists, one of type IList that gets iterated over when calculating Weight and overall Price of the Cart while having another IList that only exposes the necessary fields for displaying it in the ListView and that is a SuperType of CartItem. (But how do I then access additional fields for the listView, defaulting weight and price to 0 in the Description-Text-Class would break LSP).
But having two lists somehow feels a bit odd (and still gives me problems), so I was wondering if I could do some sort of a TypedList where I specify the Type of each item.
Any suggestions are welcome, I'm not really happy with both options. | Use an interface:
```
ICartListItem
```
And make your list be:
```
List<ICartListItem>
```
Now, create several types, have all of them implement this interface, and you can store them all safely in your list.
Alternatively, if you want there to be some default logic in a CartItem, use a base class instead of an interface. | You can make a class and, inside of that, define the properties of the required list type and then make a list of same class.
For example, if I wanted to make a list of `string`s and `bool`s, I would make two properties in one class and then make a list of that class. | List of two different Types in C# | [
"",
"c#",
"listview",
"list",
""
] |
I need to create a data transfer object, which I will use for storing the records retrieved from database. In this data transfer object, I need to declare a numeric field. For that which one is better - **int** or **Integer**
If I am defining the field as Integer, will there be any performance impact because of 'Integer' type if I am going to retrieve more than 2000 records from DB!?
Thanks in advance. | `Integer` is a better option, as it can handle `null`; for `int`, `null` would become `0`, silently, if `resultSet.getInt(..)` is used. Otherwise, it might throw some exception, something like, "Unable to set `null` to a primitive property".
Performance is of little concern here.
* if you choose `int`, you will end-up adding extra handling code; and that wouldn't benefit you much. Your code will not be clean and straight-forward, lot of boiler-plate code, and you wouldn't even gain performance.
* let me make it clear, for databases, null is not same as zero. Sometimes you end-up entering `0`, where `null` was intended. Imagine the case where user submitted a form, and doesn't supply any value for `int`. You will end up getting `0` by default. It makes sense, or does that really, when that field is `not null` in the database. | You should really make your decision based on- what you need your object to do, rather than the performance costs. Deciding based on performance should be done, once a speed issue has been identified with a profiler - the root of all evil and all that.
Look at some of the features of both and use that for your decision, e.g.
* `Integer` can be `null`, `int` cannot. So is the `int` in the *DB* a `Nullable` field?
* Do you need access to the `Integer` class methods?
* Are you doing arithmetic?
Personally, I always opt for the primitive over the wrapper. But that's just a preference thing, rather than based on any technical merit. | Which one to use, int or Integer | [
"",
"java",
"database",
"performance",
"types",
"primitive",
""
] |
I was wondering if anyone has a good solution to a problem I've encountered numerous times during the last years.
I have a shopping cart and my customer explicitly requests that it's order is significant. So I need to persist the order to the DB.
The obvious way would be to simply insert some OrderField where I would assign the number 0 to N and sort it that way.
But doing so would make reordering harder and I somehow feel that this solution is kinda fragile and will come back at me some day.
(I use C# 3,5 with NHibernate and SQL Server 2005)
Thank you | FWIW, I think the way you suggest (i.e. committing the order to the database) is not a bad solution to your problem. I also think it's probably the safest/most reliable way. | Ok here is my solution to make programming this easier for anyone that happens along to this thread. the trick is being able to update all the order indexes above or below an insert / deletion in one update.
Using a numeric (integer) column in your table, supported by the SQL queries
```
CREATE TABLE myitems (Myitem TEXT, id INTEGER PRIMARY KEY, orderindex NUMERIC);
```
To delete the item at orderindex 6:
```
DELETE FROM myitems WHERE orderindex=6;
UPDATE myitems SET orderindex = (orderindex - 1) WHERE orderindex > 6;
```
To swap two items (4 and 7):
```
UPDATE myitems SET orderindex = 0 WHERE orderindex = 4;
UPDATE myitems SET orderindex = 4 WHERE orderindex = 7;
UPDATE myitems SET orderindex = 7 WHERE orderindex = 0;
```
i.e. 0 is not used, so use a it as a dummy to avoid having an ambiguous item.
To insert at 3:
```
UPDATE myitems SET orderindex = (orderindex + 1) WHERE orderindex > 2;
INSERT INTO myitems (Myitem,orderindex) values ("MytxtitemHere",3)
``` | Best way to save a ordered List to the Database while keeping the ordering | [
"",
"c#",
"database",
"nhibernate",
"sql-order-by",
""
] |
I use `ftp_put / ftp_nb_put` to upload files from my PHP server to another machine. I am frequently (90% of the time) getting absurd error messages like:
```
Warning: ftp_nb_put(): 2 matches total
Warning: ftp_nb_put(): Transfer complete
Warning: ftp_nb_continue(): Opening BINARY mode data connection
```
Now errors like "no such directory" or "incorrect password" I could handle, but these "error message" seem to be completely pointless.
Google suggests this to be a Firewall/PASV-related problem. I have tried ftp\_pasv(), but to no avail. I have contacted my server admin, but so far he hasn't come up with anything either. | The messages where symptoms of some arcane networking problems the server had. PHP does not diagnose such problems correctly and outputs seemingly random snippets from the communication between servers.
Not actually a programming question, rather a "server fault" issue (or rather a "get a better webhoster" issue). | Well, since these are only warnings and you get the job done correctly, you can turn warnings off using ini\_set() or altering php.ini This won't solve anything but you surely won't get the errors :) | PHP/FTP ftp_put() throws weird error messages - what to do? | [
"",
"php",
"ftp",
""
] |
I've got some entities which have decimal properties on them. These entities' properties are displayed in multiple places throughout my UI.
Currently I'm finding myself doing:
```
litWeight.Text = person.Weight.ToString("0.00");
```
all over the place.
Now I know for a fact that in several instances, and am suspicious of many others that the client is likely to want the values to 3d.p. in the future.
Is there some pattern I can employ to handle the formatting of this Weight property (and other properties; not just decimals, perhaps dates etc.) so that I can have this formatting in a single place?
I know could use a formatstring in the webconfig, or write some extension methods in the UI but these don't seem very elegant solutions.
It would be nice to have some formatting objects which are tied to my entities, so its inherently obvious which formatter to use.
Thanks,
Andrew | The simplest solution would be to make a utility class with static methods that appropriately format different types of values and call them. For example:
```
litWeight.Text = Utility.FormatWeight(person.Weight);
``` | You could create a very basic user control - deriving from label or similar - that is responsible purely for displaying a weight string so you then have:
```
weightValue.DisplayValue(person.Weight);
```
and the setter formats the decimal as required. If this is used whenever you display a weight then you only have to alter the user control to change all displays of weight.
A basic version could be:
```
public void DisplayValue(decimal weight)
{
this.Text = weight.ToString("0.00");
}
``` | Abstracting UI data formatting | [
"",
"c#",
"asp.net",
"user-interface",
"design-patterns",
""
] |
I've been wanting to have a play with either Ruby or Python while at the same time I've been wanting to do a bit of Cocoa programming.
So I thought the best way to achieve both these goals is to develop something using either a Ruby or Python to Objective-C bridge (PyObjc or RubyCocoa).
I know that ideally to get the best learning experience I would learn each techonology independently but I don't have the time. :)
So my question is which is a more mature platform, PyObc or RubyCocoa, main things I am looking for:
1. Documentation of API
2. Tutorials
3. Tools
4. Supportive Community
5. Completness of Cocoa API avaialble through the bridge
Regarding point 5 I don't expect that the entire Cocoa API will be availble through either bridge but I need to have enough Cocoa APIs available to develop a functioning application. | I would echo Chris' assesment and will expand a bit on why you should learn Objective-C to learn Cocoa. As Chris says, Objective-C is the foundation and native language of Cocoa and many of its paradigms are inextricably linked with that lineage. In particular, selectors and dynamic message resolution and ability to modify classes at run time are required to implement Cocoa technologies such as Distributed Objects and bindings. Although these features are available in other dynamic languages such as Ruby and Python, there is enough of a mismatch in the language models that you will have to at least understand Objective-C to understand Cocoa. I suggest you take a look at this previous question for further discussion: [Do I have to learn Objective-C for professional Mac Development?](https://stackoverflow.com/questions/272660/do-i-have-to-learn-objective-c-for-professional-mac-development)
Fortunately, Objective-C is very easy to learn. I often tell people it will take them a day to learn Objective-C coming from C/C++/Java or LISP, Scheme, or any of the 'newer' dynamic languages such as Ruby and Python. In addition to expanding your mind a bit, you'll learn to at least read the code that is used in virtually all of the Cocoa documentation and examples.
As for Ruby vs. Python, the bridge capabilities are very similar. In fact, they both use Apple's [BridgeSupport](http://bridgesupport.macosforge.org/trac/) (shipped with Leopard) to provide the bridge description. Both are supported by Apple and ship with Leopard. It's a matter of personal taste which language you prefer. If you choose Ruby, I suggest you give [MacRuby](http://www.macruby.org/trac/wiki/MacRuby) a look. It's definitely the future of Ruby on OS X, as it reimplements the Ruby runtime on top of the Objective-C run time. This provides some nice performance and conceptual advantages (including integration with the Objective-C garbage collection system, a feature currently lacking in PyObjC which uses the native python gc). MacRuby also includes a custom parser that makes the syntax of bridged objective-c methods a little nicer. The downside of MacRuby is that it's not quite ready for production-level use at the time of this writing (June 2009). Since it sounds like this is a learning project for you, that's probably not an issue. | While you say you "don't have time" to learn technologies independently the fastest route to learning Cocoa will still be to learn it in its native language: Objective-C. Once you understand Objective-C and have gotten over the initial learning curve of the Cocoa frameworks you'll have a much easier time picking up either PyObjC or RubyCocoa. | PyObjc vs RubyCocoa for Mac development: Which is more mature? | [
"",
"python",
"ruby",
"cocoa",
"pyobjc",
"ruby-cocoa",
""
] |
Ever stumbled on a tutorial that you feel is of great value but not quite explained properly? That's my dilemma. I know [THIS TUTORIAL](http://www.tonymarston.net/php-mysql/backbuttonblues.html) has some value but I just can't get it.
1. Where do you call each function?
2. Which function should be called
first and which next, and which
third?
3. Will all functions be called in all files in an application?
4. Does anyone know of a better way cure the "Back Button Blues"?
I'm wondering if this will stir some good conversation that includes the author of the article. The part I'm particularly interested in is controlling the back button in order to prevent form duplicate entries into a database when the back button is pressed. Basically, you want to control the back button by calling the following three functions during the execution of the scripts in your application. In what order exactly to call the functions (see questions above) is not clear from the tutorial.
> All forwards movement is performed by
> using my scriptNext function. This is
> called within the current script in
> order to activate the new script.
>
> ```
> function scriptNext($script_id)
> // proceed forwards to a new script
> {
> if (empty($script_id)) {
> trigger_error("script id is not defined", E_USER_ERROR);
> } // if
>
> // get list of screens used in this session
> $page_stack = $_SESSION['page_stack'];
> if (in_array($script_id, $page_stack)) {
> // remove this item and any following items from the stack array
> do {
> $last = array_pop($page_stack);
> } while ($last != $script_id);
> } // if
>
> // add next script to end of array and update session data
> $page_stack[] = $script_id;
> $_SESSION['page_stack'] = $page_stack;
>
> // now pass control to the designated script
> $location = 'http://' .$_SERVER['HTTP_HOST'] .$script_id;
> header('Location: ' .$location);
> exit;
>
> } // scriptNext
> ```
>
> When any script has finished its
> processing it terminates by calling my
> scriptPrevious function. This will
> drop the current script from the end
> of the stack array and reactivate the
> previous script in the array.
>
> ```
> function scriptPrevious()
> // go back to the previous script (as defined in PAGE_STACK)
> {
> // get id of current script
> $script_id = $_SERVER['PHP_SELF'];
>
> // get list of screens used in this session
> $page_stack = $_SESSION['page_stack'];
> if (in_array($script_id, $page_stack)) {
> // remove this item and any following items from the stack array
> do {
> $last = array_pop($page_stack);
> } while ($last != $script_id);
> // update session data
> $_SESSION['page_stack'] = $page_stack;
> } // if
>
> if (count($page_stack) > 0) {
> $previous = array_pop($page_stack);
> // reactivate previous script
> $location = 'http://' .$_SERVER['HTTP_HOST'] .$previous;
> } else {
> // no previous scripts, so terminate session
> session_unset();
> session_destroy();
> // revert to default start page
> $location = 'http://' .$_SERVER['HTTP_HOST'] .'/index.php';
> } // if
>
> header('Location: ' .$location);
> exit;
>
> } // scriptPrevious
> ```
>
> Whenever a script is activated, which
> can be either through the scriptNext
> or scriptPrevious functions, or
> because of the BACK button in the
> browser, it will call the following
> function to verify that it is the
> current script according to the
> contents of the program stack and take
> appropriate action if it is not.
>
> ```
> function initSession()
> // initialise session data
> {
> // get program stack
> if (isset($_SESSION['page_stack'])) {
> // use existing stack
> $page_stack = $_SESSION['page_stack'];
> } else {
> // create new stack which starts with current script
> $page_stack[] = $_SERVER['PHP_SELF'];
> $_SESSION['page_stack'] = $page_stack;
> } // if
>
> // check that this script is at the end of the current stack
> $actual = $_SERVER['PHP_SELF'];
> $expected = $page_stack[count($page_stack)-1];
> if ($expected != $actual) {
> if (in_array($actual, $page_stack)) {// script is within current stack, so remove anything which follows
> while ($page_stack[count($page_stack)-1] != $actual ) {
> $null = array_pop($page_stack);
> } // while
> $_SESSION['page_stack'] = $page_stack;
> } // if
> // set script id to last entry in program stack
> $actual = $page_stack[count($page_stack)-1];
> $location = 'http://' .$_SERVER['HTTP_HOST'] .$actual;
> header('Location: ' .$location);
> exit;
> } // if
>
> ... // continue processing
>
> } // initSession
> ```
>
> The action taken depends on whether
> the current script exists within the
> program stack or not. There are three
> possibilities:
>
> * The current script is not in the $page\_stack array, in which case it is
> not allowed to continue. Instead it is
> replaced by the script which is at the
> end of the array.
> * The current script is in the
> $page\_stack array, but it is not the
> last entry. In this case all
> following entries in the array are
> removed.
> * The current script is the last entry
> in the $page\_stack array. This is
> the expected situation. Drinks all
> round! | That is a good discussion but more to the point you should be looking into Post Redirect Get (PRG) also known as "Get after Post."
<http://www.theserverside.com/patterns/thread.tss?thread_id=20936> | If you do not understand my article then you should take a close look at [figure 1](http://www.tonymarston.net/php-mysql/backbuttonblues.html#figure1) which depicts a typical scenario where a user passes through a series of screens – logon, menu, list, search, add and update. When I describe a movement of FORWARDS I mean that the current screen is suspended while a new screen is activated. This happens when the user presses a link in the current screen. When I describe a movement as BACKWARDS I mean that the user terminates the current screen (by pressing the QUIT or SUBMIT button) and returns to the previous screen, which resumes processing from where it left off. This may include incorporating any changes made in the screen which has just been terminated.
This is where maintaining a page stack which is independent of the browser history is crucial – the page stack is maintained by the application and is used to verify all requests. These may be valid as far as the browser is concerned, but may be identified by the application as invalid and dealt with accordingly.
The page stack is maintained by two functions:
* scriptNext() is used to process a
FORWARDS movement, which adds a new
entry at the end of the stack and
activates the new entry.
* scriptPrevious() is used to process
a BACKWARDS movement, which removes
the last entry from the stack and
re-activates the previous entry.
Now take the situation in the example where the user has navigated to page 4 of the LIST screen, gone into the ADD screen, then returned to page 5 of the LIST screen. The last action in the ADD screen was to press the SUBMIT button which used the POST method to send details to the server which were added to the database, after which it terminated automatically and returned to the LIST screen.
If you therefore press the BACK button while in page 5 of the LIST screen the browser history will generate a request for the last action on the ADD screen, which was a POST. This is a valid request as far as the browser is concerned, but is not as far as the application is concerned. How can the application decide that the request is invalid? By checking with its page stack. When the ADD screen was terminated its entry was deleted from the page stack, therefore any request for a screen which is not in the page stack can always be treated as invalid. In this case the invalid request can be redirected to the last entry in the stack.
The answers to your questions should therefore be obvious:
* Q: Where do you call each function?
* A: You call the scriptNext()
function when the user chooses to
navigate forwards to a new screen,
and call the scriptPrevious()
function when the user terminates
the current screen.
* Q: Which function should be called
first and which next, and which
third?
* A: Each function is called in
response to an action chosen by the
user, so only one function is used
at a time.
* Q: Will all functions be called in
all files in an application?
* A: All functions should be available
in all files in an application, but
only called when chosen by the user.
It you wish to see these ideas in action then you can download my [sample application](http://www.tonymarston.net/php-mysql/sample-application.html). | Curing the "Back Button Blues" | [
"",
"php",
"forms",
"button",
"back",
""
] |
After going through the Appendix A, "C# Coding Style Conventions" of the great book "Framework Design Guidelines" (2nd edition from November 2008), I am quite confused as to what coding style is Microsoft using internally / recommending.
The blog entry [A Brief History Of C# Style](http://blogs.msdn.com/sourceanalysis/archive/2008/05/25/a-difference-of-style.aspx) claims:
> In fact, the differences between the "StyleCop style" and the "Framework Design Guidelines style" are relatively minor
As I see it, the differences are quite pronounced. StyleCop says opening brace should be on a separate line, Framework Design Guidelines say it should be after the opening statement. StyleCop says all keywords are to be followed by a space, Framework Design Guidelines say 'get rid of all spaces' (even around binary operators).
I find this rule from the Framework Design Guidelines book especially ironic (page 366, 6th rule from the top):
> **Do not** use spaces before flow control statements
>
> ```
> Right: while(x==y)
> Wrong: while (x == y)
> ```
This is explicitely stating that the StyleCop style is **wrong** (space after the while keyword, spaces before and after the equality binary operator).
In the end, code formatted using the StyleCop style has quite a different "feel" from the one formatted using the Framework Design Guidelines style. By following the Framework Design Guidelines style, one would have to disable a bunch of the rules (AND there are no rules that check adherence to the Framework Design Guidelines style...).
Could somebody (MSFT insiders perhaps?) shed some light on this divergence?
How is your team dealing with this? Following StyleCop? Framework Design Guidelines? Ignoring style altogether? Baking your own style? | On a blog I read about this (I can't seem to find the url) it was stated:
the framework guidelines are based and evolved from C++ guideliness (they are all seasoned C++ developers) while the guidelines stylecop provides are more modern new C# only guideliness...
Both are fine, make a decision yourself... I personally use the StyleCop ones | This article by the stylecop team explains exactly what you're asking I think.
<http://blogs.msdn.com/sourceanalysis/archive/2008/05/25/a-difference-of-style.aspx>
And to answer the second part of your question, our team just started using StyleCop using all rules (some people pick and choose which ones to use). The only thing I don't like is the extra time it takes, but using a tool like StyleCopForResharper makes it go a lot faster. I used to get really annoyed when people wrote code that looked differently than I would have written it, but now that we use StyleCop, everyone's code looks identical. No more biting your lip about annoying things people do | How do you resolve the discrepancy between "StyleCop C# style" and "Framework Design Guidelines C# style"? | [
"",
"c#",
"coding-style",
"conventions",
"stylecop",
""
] |
I have a DataTable which is bound to a GridView. I also have a button that when clicked exports the DataTable to an Excel file. However, the following error is occuring:
ErrMsg = "Thread was being aborted."
Here is part of the code where the error is being thrown:
```
private static void Export_with_XSLT_Web(DataSet dsExport,
string[] sHeaders,
string[] sFileds,
ExportFormat FormatType,
string FileName)
{
try
{
// Appending Headers
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
if(FormatType == ExportFormat.CSV)
{
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AppendHeader("content-disposition",
"attachment;
filename=" + FileName);
}
else
{
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AppendHeader("content-disposition",
"attachment;
filename=" + FileName);
}
// XSLT to use for transforming this dataset.
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
CreateStylesheet(writer, sHeaders, sFileds, FormatType);
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
XmlDataDocument xmlDoc = new XmlDataDocument(dsExport);
//dsExport.WriteXml("Data.xml");
XslTransform xslTran = new XslTransform();
xslTran.Load(new XmlTextReader(stream), null, null);
using(StringWriter sw = new StringWriter())
{
xslTran.Transform(xmlDoc, null, sw, null);
//Writeout the Content
HttpContext.Current.Response.Write(sw.ToString());
writer.Close();
stream.Close();
HttpContext.Current.Response.End();
}
}
catch(ThreadAbortException Ex)
{
string ErrMsg = Ex.Message;
}
catch(Exception Ex)
{
throw Ex;
}
finally
{
}
}
```
After changing HttpContext.Current.Response.End to HttpContext.Current.ApplicationInstance.CompleteRequest, it now just goes to the finally block and I can't figure out what error message is being thrown. | The ThreadAbortException is thrown from the following line:
```
HttpContext.Current.Response.End();
```
Here's more [details](http://support.microsoft.com/kb/312629) and a workaround. | I tried using `HttpContext.Current.ApplicationInstance.CompleteRequest`. It did work but also exported the complete HTML Code of the page at the end of the downloaded file, which was undesirable.
```
Response.BuffferOutput = True;
Response.Flush();
Response.Close();
```
Then after a hell of effort, I bumped into the above code. And it works perfectly without any exception or undesirable code at the end of the downloaded file.
[Source](http://forums.asp.net/post/2270919.aspx "Source") | Thread was being aborted when exporting to excel? | [
"",
"c#",
"asp.net",
"exception",
""
] |
I am constantly forgetting what the special little codes are for formatting .NET strings. Either through ToString() or using String.Format(). Alignment, padding, month vs. minute (month is uppercase M?), abbreviation vs. full word, etc. I can never remember.
I have the same problem with regexes, but luckily there's [Expresso](http://www.ultrapico.com/Expresso.htm) to help me out. It's awesome.
Is there a tool like Expresso for experimenting with formatted strings on standard types like DateTime and float and so on? | PowerShell works great for testing format strings. From PowerShell you can load your assembly and work with the objects and methods you want to test. You could also just create a string on the command line and test out different formatting options.
You can use the static method from the string class:
```
$teststring = 'Currency - {0:c}. And a date - {1:ddd d MMM}. And a plain string - {2}'
[string]::Format($teststring, 160.45, Get-Date, 'Test String')
```
Or PowerShell has a built in format operator
```
$teststring = 'Currency - {0:c}. And a date - {1:ddd d MMM}. And a plain string - {2}'
$teststring -f 160.45, Get-Date, 'Test String'
``` | I just found this:
<http://rextester.com/>
Simply paste in your format string, and run the code.
It would also be simple enough to create a windows or console project that does exactly that. | Looking for a tool to quickly test C# format strings | [
"",
"c#",
"formatting",
"string",
""
] |
I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:
```
conn = sqlite3.connect("mydatabase.db")
```
* If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.
* If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.
Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas? | You can use consumer-producer pattern. For example you can create queue that is shared between threads. First thread that fetches data from the web enqueues this data in the shared queue. Another thread that owns database connection dequeues data from the queue and passes it to the database. | Contrary to popular belief, newer versions of sqlite3 **do** support access from multiple threads.
This can be enabled via optional keyword argument `check_same_thread`:
```
sqlite.connect(":memory:", check_same_thread=False)
``` | Python sqlite3 and concurrency | [
"",
"python",
"sqlite",
""
] |
In many places in our code we have collections of objects, from which we need to create a comma-separated list. The type of collection varies: it may be a DataTable from which we need a certain column, or a List<Customer>, etc.
Now we loop through the collection and use string concatenation, for example:
```
string text = "";
string separator = "";
foreach (DataRow row in table.Rows)
{
text += separator + row["title"];
separator = ", ";
}
```
Is there a better pattern for this? Ideally I would like an approach we could reuse by just sending in a function to get the right field/property/column from each object. | ```
// using System.Collections;
// using System.Collections.Generic;
// using System.Linq
public delegate string Indexer<T>(T obj);
public static string concatenate<T>(IEnumerable<T> collection, Indexer<T> indexer, char separator)
{
StringBuilder sb = new StringBuilder();
foreach (T t in collection) sb.Append(indexer(t)).Append(separator);
return sb.Remove(sb.Length - 1, 1).ToString();
}
// version for non-generic collections
public static string concatenate<T>(IEnumerable collection, Indexer<T> indexer, char separator)
{
StringBuilder sb = new StringBuilder();
foreach (object t in collection) sb.Append(indexer((T)t)).Append(separator);
return sb.Remove(sb.Length - 1, 1).ToString();
}
// example 1: simple int list
string getAllInts(IEnumerable<int> listOfInts)
{
return concatenate<int>(listOfInts, Convert.ToString, ',');
}
// example 2: DataTable.Rows
string getTitle(DataRow row) { return row["title"].ToString(); }
string getAllTitles(DataTable table)
{
return concatenate<DataRow>(table.Rows, getTitle, '\n');
}
// example 3: DataTable.Rows without Indexer function
string getAllTitles(DataTable table)
{
return concatenate<DataRow>(table.Rows, r => r["title"].ToString(), '\n');
}
``` | ```
string.Join(", ", Array.ConvertAll(somelist.ToArray(), i => i.ToString()))
``` | Join collection of objects into comma-separated string | [
"",
"c#",
".net",
".net-3.5",
""
] |
I'm busy writing a class that monitors the status of RAS connections. I need to test to make sure that the connection is not only connected, but also that it can communicate with my web service. Since this class will be used in many future projects, I'd like a way to test the connection to the webservice without knowing anything about it.
I was thinking of passing the URL to the class so that it at least knows where to find it. Pinging the server is not a sufficient test. It is possible for the server to be available, but the service to be offline.
How can I effectively test that I'm able to get a response from the web service? | You are right that pinging the server isn't sufficient. The server can be up, but the web service unavailable due to a number of reasons.
To monitor our web service connections, I created a IMonitoredService interface that has a method CheckService(). The wrapper class for each web service implements this method to call an innocuous method on the web service and reports if the service is up or not. This allows any number of services to be monitored with out the code responsible for the monitoring knowing the details of the service.
If you know a bit about what the web service will return from accessing the URL directly, you could try just using the URL. For example, Microsoft's asmx file returns a summary of the web service. Other implementations may behave differently though. | You could try the following which tests the web site's existence:
```
public static bool ServiceExists(
string url,
bool throwExceptions,
out string errorMessage)
{
try
{
errorMessage = string.Empty;
// try accessing the web service directly via it's URL
HttpWebRequest request =
WebRequest.Create(url) as HttpWebRequest;
request.Timeout = 30000;
using (HttpWebResponse response =
request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception("Error locating web service");
}
// try getting the WSDL?
// asmx lets you put "?wsdl" to make sure the URL is a web service
// could parse and validate WSDL here
}
catch (WebException ex)
{
// decompose 400- codes here if you like
errorMessage =
string.Format("Error testing connection to web service at" +
" \"{0}\":\r\n{1}", url, ex);
Trace.TraceError(errorMessage);
if (throwExceptions)
throw new Exception(errorMessage, ex);
}
catch (Exception ex)
{
errorMessage =
string.Format("Error testing connection to web service at " +
"\"{0}\":\r\n{1}", url, ex);
Trace.TraceError(errorMessage);
if (throwExceptions)
throw new Exception(errorMessage, ex);
return false;
}
return true;
}
``` | How do I test connectivity to an unknown web service in C#? | [
"",
"c#",
"web-services",
""
] |
I just stumbled across this bug in some legacy code:
```
class MyAPIHandler
{
private:
int handle;
public:
void MyApiHandler() // default constructor
{
handle = 42;
};
};
```
It compiles fine, with no warnings - but the behaviour wasn't what I intended, because the constructor name is misspelt. This by itself would have produced a warning about "function does not return a value", but I guess I was on autopilot and added a "void" return type to 'fix' this.
Now, the bugfix was easy, but my question is this:-
What techniques could I use to prevent this type of bug recurring?
Some languages require an explicit "constructor" keyword, which should make this problem obvious. Unit testing, obviously should also have caught it. What else can I do? | If you always use initialiser lists in your constructors:
```
MyApiHandler() // default constructor
: handle(42)
{
}
```
the misnamed constructor bug would be even more unlikely, and it's better [style](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10 "style") anyway.
**Edit**: thanks to commenter for the link | This shouldn't be much of a problem. Constructors don't have return values (not even void), so the compiler should be able to tell whether something is meant to be a constructor or a member function, and let you know if there's a problem. Obviously someone saw the compiler's error on that and chose the wrong solution (adding a return type instead of correcting the spelling). (EDIT: Sorry, didn't realize that you'd done that yourself.)
Personally, I always put the constructor(s) near the beginning of the the class's public section (before any member functions, but after public type definitions and constants), so a problem like that would be pretty obvious to me on re-reading the code. But conventions differ on that. | C++ Constructor coding errors | [
"",
"c++",
"constructor",
""
] |
Or, in other words, what is wrong with something like -
```
new Method[] {Vector.add(), Vector.remove()}
```
Eclipse keeps telling me that I need arguments. But I obviously don't want to call the methods, I just want to use them as objects! What to do? | this works, I can't help but wondering, what you're doing with this?
```
new Method[] {
Vector.class.getMethod("add", Object.class),
Vector.class.getMethod("remove", Object.class)
};
``` | First of all, you're making up syntax here. There's no "Vector.add()" in my javadocs.
You can do this:
```
Method [] methods = Vector.class.getMethods();
```
but you can't execute those methods. No closures or function objects here. | How to refer to Method objects in Java? | [
"",
"java",
"reflection",
"methods",
""
] |
How can I emulate classes (and namespaces) in JavaScript?
I need to create a JavaScript library and have limited experience with the language. I always thought that it had native support for classes, but it is less related to Java than I had assumed. It seems that everything in JavaScript is actually a function.
What I have found out so far makes a lot of sense with it being a dynamic weakly typed language, but this makes it a bit of a departure for people who are used to having a strongly typed language and using a compiler to spot our errors :)
I mainly work in C# and Java, and was hoping for something syntacticaly similar so the library would look familiar for our other C# developers that will have to maintain it.
I have the following sort of code which works, but I was wondering what other developer's takes would be on this. What are the alternatives? Is there a way that is better? Is there a way that is more readable?
I understand that what I want is something similar to C# or Java when I should just accept the fact that this **is JavaScript**, but my aim is to try to ease the learning curve for other developers by making it more familiar and intuitive for them.
```
//Perform the namespace setup (this will actually be done with checking
//in real life so we don't overwrite definitions, but this is kept short
//for the code sample).
var DoctaJonez = new function();
DoctaJonez.Namespace1 = new function();
/**
* Class description.
*/
DoctaJonez.Namespace1.SomeClass = function()
{
/**
* Public functions listed at the top to act like a "header".
*/
this.publicFunction = privateFunction;
/**
* Private variables next.
*/
var privateVariable;
/**
* Finally private functions.
*/
function privateFunction()
{
}
}
//Create an instance of the class
var myClass = new DoctaJonez.SomeClass();
//Do some stuff with the instance
myClass.publicFunction();
``` | * [3 ways to define a JavaScript class](http://www.phpied.com/3-ways-to-define-a-javascript-class/)
* [Object-oriented JavaScript](http://www.xml.com/pub/a/2006/06/07/object-oriented-javascript.html)
* [JavaScript Tutorial: Functions and Classes](http://www.webdevelopersjournal.com/articles/jsintro3/js_begin3.html) | For general understanding of OOP in JavaScript you can't do better than read [Douglas Crockford](http://javascript.crockford.com/):
* [Classical Inheritance in JavaScript](http://javascript.crockford.com/inheritance.html)
* [Prototypal Inheritance in JavaScript](http://javascript.crockford.com/prototypal.html)
* [Private Members in JavaScript](http://javascript.crockford.com/private.html)
For Dojo fans (and for general techniques) [Neil Roberts](http://someclosure.com/) has good articles:
* [Color by numbers: dojo.delegate](http://dojocampus.org/content/2008/03/20/color-by-numbers-dojodelegate/)
* [JavaScript Metaclass Programming](http://www.sitepen.com/blog/2008/03/18/javascript-metaclass-programming/)
Plain vanilla [dojo.declare()](http://docs.dojocampus.org/dojo/declare) is probably the most advanced OOP foundation in mainstream libraries around. I am biased, but don't take my word for it. Here are examples on how to use it.
A plain vanilla object:
```
// Let's define a super simple class (doesn't inherit anything).
dojo.declare("Person", null, {
// Class-level property
answer: 42,
// Class-level object property
name: {first: "Ford", last: "Prefect"},
// The constructor, duh!
constructor: function(age){
this.age = age; // instance-level property
},
// A method
saySomething: function(verb){
console.log("I " + verb + " " +
this.name.first + " " + this.name.last + "!" +
" -- " + this.answer);
},
// Another method
passportControl: function(){
console.log("I am " + this.age);
}
});
```
Example of use:
```
// A fan of Ford Perfect
var fan = new Person(18);
fan.saySomething("love"); // I love Ford Perfect! -- 42
fan.passportControl(); // I am 18
```
Single inheritance is easy:
```
// Let's create a derived class inheriting Person
dojo.declare("SuperAgent", Person, {
// Redefine class-level property
answer: "shaken, not stirred",
// Redefine class-level object property
name: {first: "James", last: "Bond"},
// The constructor
constructor: function(age, drink){
// We don't need to call the super class because
// it would be done automatically for us passing
// all arguments to it.
// At this point "age" is already assigned.
this.drink = drink; // Instance-level property
},
// Let's redefine the method
saySomething: function(verb){
// Let's call the super class first
this.inherited(arguments);
// Pay attention: no need for extra parameters, or any extra code,
// we don't even name the class we call --- it is all automatic.
// We can call it any time in the body of redefined method
console.log("Yeah, baby!");
},
shoot: function(){ console.log("BAM!!!"); }
});
```
Example of use:
```
// Let's create a James Bond-wannabe
var jb007 = new SuperAgent(45, "Martini");
jb007.saySomething("dig"); // I dig James Bond! -- shaken, not stirred
// Yeah, baby!
jb007.passportControl(); // I am 45
jb007.shoot(); // BAM!!!
// Constructors were called in this order: Person, SuperAgent
// saySomething() came from SuperAgent, which called Person
// passportControl() came from Person
// shoot() came from SuperAgent.
```
Mixins:
```
// Let's define one more super simple class
dojo.define("SharpShooter", null, {
// For simplicity no constructor
// One method to clash with SuperAgent
shoot: function(){
console.log("It's jammed! Shoot!");
}
});
```
Mixin-based multiple inheritance:
```
// Multiple inheritance
dojo.declare("FakeAgent", ["SuperAgent", "SharpShooter"], {
// Let's do it with no constructor
// Redefine the method
saySomething: function(verb){
// We don't call super here --- a complete redefinition
console.log("What is " + verb "? I want my " + this.drink + "!");
},
});
```
Example of use:
```
// A fake agent coming up
var ap = new FakeAgent(40, "Kool-Aid");
ap.saySomething("hate"); // What is hate? I want my Kool-Aid!
ap.passportControl(); // I am 40
ap.shoot(); // It's jammed! Shoot!
// Constructors were called in this order: Person, SuperAgent
// saySomething() came from FakeAgent
// passportControl() came from Person
// shoot() came from SharpShooter.
```
As you can see, `dojo.declare()` gives all necessities with a simple to use API: straight single inheritance, mixin-based multiple inheritance, automatic chaining of constructors, and no-hassle super methods. | How can I emulate "classes" in JavaScript? (with or without a third-party library) | [
"",
"javascript",
"oop",
""
] |
What is the benefit/downside to using a `switch` statement vs. an `if/else` in C#. I can't imagine there being that big of a difference, other than maybe the look of your code.
Is there any reason why the resulting IL or associated runtime performance would be radically different?
### Related: [What is quicker, switch on string or elseif on type?](https://stackoverflow.com/questions/94305/what-is-quicker-switch-on-string-or-elseif-on-type) | SWITCH statement only produces same assembly as IFs in debug or compatibility mode. In release, it will be compiled into jump table (through MSIL 'switch' statement)- which is O(1).
C# (unlike many other languages) also allows to switch on string constants - and this works a bit differently. It's obviously not practical to build jump tables for strings of arbitrary lengths, so most often such switch will be compiled into stack of IFs.
But if number of conditions is big enough to cover overheads, C# compiler will create a HashTable object, populate it with string constants and make a lookup on that table followed by jump. Hashtable lookup is not strictly O(1) and has noticeable constant costs, but if number of case labels is large, it will be significantly faster than comparing to each string constant in IFs.
To sum it up, if number of conditions is more than 5 or so, prefer SWITCH over IF, otherwise use whatever looks better. | In general (considering all languages and all compilers) a switch statement CAN SOMETIMES be more efficient than an if / else statement, because it is easy for a compiler to generate jump tables from switch statements. It is possible to do the same thing for if / else statements, given appropriate constraints, but that is much more difficult.
In the case of C#, this is also true, but for other reasons.
With a large number of strings, there is a significant performance advantage to using a switch statement, because the compiler will use a hash table to implement the jump.
With a small number of strings, the performance between the two is the same.
This is because in that case the C# compiler does not generate a jump table. Instead it generates MSIL that is equivalent to IF / ELSE blocks.
There is a "switch statement" MSIL instruction that when jitted will use a jump table to implement a switch statement. It only works with integer types, however (this question asks about strings).
For small numbers of strings, it's more efficient for the compiler to generate IF / ELSE blocks then it is to use a hash table.
When I originally noticed this, I made the assumption that because IF / ELSE blocks were used with a small number of strings, that the compiler did the same transformation for large numbers of strings.
This was WRONG. 'IMA' was kind enough to point this out to me (well...he wasn't kind about it, but he was right, and I was wrong, which is the important part)
I also made a bone headed assumption about the lack of a "switch" instruction in MSIL (I figured, if there was a switch primitive, why weren't they using it with a hash table, so there must not be a switch primitive.... ). This was both wrong, and incredibly stupid on my part. Again 'IMA' pointed this out to me.
I made the updates here because it's the highest rated post, and the accepted answer.
However,I've made it Community Wiki because I figure I don't deserve the REP for being wrong. If you get a chance, please up vote 'ima''s post. | Is there any significant difference between using if/else and switch-case in C#? | [
"",
"c#",
".net",
"switch-statement",
""
] |
I am struggling with something that I think should be easily (ish). I have a windows form and a flowgridlayout panel at the bottom of the form. Inside this form I dynamically populate it with X number of User Controls. The controls are all the same type.
The goal is when the user hoovers the mouse over the user control it opens another form and positions it where the mouse is. When mouse leaves the form the opened form disappears.
This almost works great. The problem is when the User Control has anything like a label or text box inside it. It is considered to have left the UC so the form disappears.
My thought was then to use the X and Y to tell if it is inside the UC but I can not figure this out.
Can I ask:
1) What is the best approach to this?
2) How can I code it, as the UC's are dynamic I can not know exactly where they will be.
Thanks
**EDIT**
I am trying to figure out the mouse pointers but not getting there. The code below is within the UC SmallTagBox\_MouseLeave event:
```
Point loc = this.Location;
Point p = this.PointToScreen(this.Location);
Point p2 = this.PointToScreen(this.Parent.Location);
Point ms = MousePosition;
Rectangle screenBounds = new Rectangle(this.PointToScreen(this.Location), this.Size);
if (!screenBounds.Contains(ms))
{
thw.Close();
thw = null;
}
```
* loc {X = 275 Y = 3} System.Drawing.Point
* p {X = 808 Y = 908} System.Drawing.Point
* p {X = 808 Y = 908} System.Drawing.Point
* p2 {X = 545 Y = 1542} System.Drawing.Point
* ms {X = 574 Y = 914} System.Drawing.Point
* screenBounds {X = 808 Y = 908 Width = 62 Height = 29} System.Drawing.Rectangle
I do not understand how p2 (its parent) can have a greater Y value relative to the screen. | Hooking all the controls MouseEnter and MouseLeave events, then figuring out if it is still inside the form is pretty painful. A simple timer can get the job done too:
```
public partial class Form1 : Form {
private Timer mTimer;
public Form1() {
InitializeComponent();
mTimer = new Timer();
mTimer.Interval = 200;
mTimer.Tick += mTimer_Tick;
mTimer.Enabled = true;
}
private void mTimer_Tick(object sender, EventArgs e) {
if (!this.DesktopBounds.Contains(Cursor.Position)) this.Close();
}
}
``` | Idea 1) When the `MouseLeave` event fires, you can check the mouse coordinates (relative to screen) and check if they're still within the bounds of your usercontrol. If they are, it should be assumed that the mouse has to pass back through the control to get outside the bounds, and you can safely ignore the event this time.
Idea 2) Attach `MouseEnter` event handlers to the child controls. Then when the mouse enters one, you will know and can ignore the usercontrol's `MouseLeave` event. Then when the child's `MouseLeave` event fires, check for the usercontrol's `MouseEnter` again. | Winform - determine if mouse has left user control | [
"",
"c#",
"winforms",
"user-controls",
"mouse",
""
] |
This is a Windows Console application (actually a service) that a previous guy built 4 years ago and is installed and running. I now need to make some changes but can't even build the current version! Here is the build output:
```
--------------------Configuration: MyApp - Win32 Debug--------------------
Compiling resources...
Compiling...
Main.cpp
winsock.cpp
Linking...
LINK : warning LNK4098: defaultlib "LIBCMTD" conflicts with use of other libs; use /NODEFAULTLIB:library
Main.obj : error LNK2001: unresolved external symbol _socket_dontblock
Debug/MyApp.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
MyApp.exe - 2 error(s), 1 warning(s)
--------------------------------------------------------------------------
```
If I use `/NODEFAULTLIB` then I get loads of errors. The code does not actually use `_socket_noblock` but I can't find anything on it on the 'net. Presumably it is used by some library I am linking to but I don't know what library it is in.
--- Alistair. | Sorry, this turns out to be an internal problem. A combination of a maverick coder 4 years ago and a rusty no-nothing (me!) now.
The code does not use `_socket_noblock` but it **does** use `socket_noblock` and I just need to link to one of our own libraries. | LNK4098 may not be a problem. For example, it can occur if you link against a release version of some library which uses static runtime linkage and causes LIBCMT (note the absense of "D" suffix) to be added to default libraries. Your application, being built in Debug config, uses LIBCMT**D**, thus the conflict. It may be actually safe, provided that you are not exchanging anything runtime-dependant with that library.
As for `_socket_noblock`, you can use some search utility (such as grep or find) to search for this string in .obj and .lib files. This way you will know which library references the symbol, which may be a starting point for discovering what dependencies that library has. | How to resolve this VC++ 6.0 linker error? | [
"",
"c++",
"windows",
"visual-c++-6",
"linker-errors",
"unresolved-external",
""
] |
I have two complex (i.e. objects with string, int, double, List and other home made data type) objects of the same type. I would like to compare the content of both of them to ensure that they are identical. Note: The object doesn't implement .Equals (I have no control on that) and doesn't implement IComparable.
Is there a generic way (reflection?) to compare the content of the two objects?
Thanks! | > > *Is there a generic way to compare the content of the two objects?*
Well yes, but generally that's known as the IComparable interface.
If you could descend from the class and create a child that implemented IComparable, that might be ideal. | I have created a class to perform a deep compare of .NET Objects. See:
<https://github.com/GregFinzer/Compare-Net-Objects> | Compare the content of two objects for equality | [
"",
"c#",
""
] |
I would like to pass a COM method as a function argument but I get this error (Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86):
error C3867: 'IDispatch::GetTypeInfoCount': function call missing argument list; use '&IDispatch::GetTypeInfoCount' to create a pointer to member
What am I missing?
Thank you very much.
```
#include <atlbase.h>
void update( HRESULT(*com_uint_getter)(UINT*), UINT& u )
{
UINT tmp;
if ( S_OK == com_uint_getter( &tmp ) ) {
u = tmp;
}
}
// only for compile purpose, it will not work at runtime
int main(int, char*[])
{
// I choose IDispatch::GetTypeInfoCount just for the sake of exemplification
CComPtr< IDispatch > ptr;
UINT u;
update( ptr->GetTypeInfoCount, u );
return 0;
}
``` | As [morechilli](https://stackoverflow.com/users/5427/morechilli) pointed out this is a C++ issue.
Here it is the solution, thanks to my colleague Daniele:
```
#include <atlbase.h>
template < typename interface_t >
void update( interface_t* p, HRESULT (__stdcall interface_t::*com_uint_getter)(UINT*), UINT& u )
{
UINT tmp;
if ( S_OK == (p->*com_uint_getter)( &tmp ) ) {
u = tmp;
}
}
// only for compile purpose, it will not work at runtime
int main(int, char*[])
{
// I choose IDispatch::GetTypeInfoCount just for the sake of exemplification
CComPtr< IDispatch > ptr;
UINT u;
update( ptr.p, &IDispatch::GetTypeInfoCount, u );
return 0;
}
``` | Looks like a straight c++ problem.
Your method expects a pointer to a function.
You have a member function - (which is different from a function).
Typically you will need to either:
1. Change the function that you want to pass to being static.
2. Change the type of pointer expected to a member function pointer.
The syntax for dealing with member function pointers is not the best...
A standard trick would be (1) and then pass the object this pointer explicitly
as an argument allowing you to then call non static members. | How to pass a COM method as a function argument? And Microsoft Compiler error C3867 | [
"",
"c++",
"com",
"function-pointers",
""
] |
I'm making a webpage with dynamic content that enters the view with AJAX polling. The page JS occasionally downloads updated information and renders it on the page while the user is reading other information. This sort of thing is costly to bandwidth and processing time. I would like to have the polling pause when the page is not being viewed.
I've noticed most of the webpages I have open spend the majority of their time minimized or in a nonviewed tab. I'd like to be able to pause the scripts until the page is actually being viewed.
I have no idea how to do it, and it seems to be trying to break out of the sandbox of the html DOM and reach into the user's system. It may be impossible, if the JS engine has no knowledge of its rendering environment. I've never even seen a different site do this (not that the user is intended to see it...)
So it makes for an interesting question for discussion, I think. How would you write a web app that is CPU heavy to pause when not being used? Giving the user a pause button is not reliable, I'd like it to be automatic. | Your best solution would be something like this:
```
var inactiveTimer;
var active = true;
function setTimer(){
inactiveTimer = setTimeOut("stopAjaxUpdateFunction()", 120000); //120 seconds
}
setTimer();
document.onmouseover = function() { clearTimeout ( inactiveTimer );
setTimer();
resumeAjaxUpdate();
}; //clear the timer and reset it.
function stopAjaxUpdateFunction(){
//Turn off AJAX update
active = false;
}
function resumeAjaxUpdate(){
if(active == false){
//Turn on AJAX update
active = true;
}else{
//do nothing since we are still active and the AJAX update is still on.
}
}
```
The stopAjaxUpdateFunction should stop the AJAX update progress. | How about setting an "inactivity timeout" which gets reset every time a mouse or keyboard event is received in the DOM? I believe this is how most IM programs decide that you're "away" (though they do it by hooking the input messages at the system-wide level) | How to know if a page is currently being read by the user with Javascript? | [
"",
"javascript",
"ajax",
""
] |
I have unevenly distributed data (wrt `date`) for a few years (2003-2008). I want to query data for a given set of start and end date, grouping the data by any of the supported intervals (day, week, month, quarter, year) in [PostgreSQL 8.3](https://www.postgresql.org/docs/8.3/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC).
The problem is that some of the queries give results continuous over the required period, as this one:
```
select to_char(date_trunc('month',date), 'YYYY-MM-DD'), count(distinct post_id)
from some_table
where category_id = 1
and entity_id = 77
and entity2_id = 115
and date <= '2008-12-06'
and date >= '2007-12-01'
group by date_trunc('month',date)
order by date_trunc('month',date);
to_char | count
------------+-------
2007-12-01 | 64
2008-01-01 | 31
2008-02-01 | 14
2008-03-01 | 21
2008-04-01 | 28
2008-05-01 | 44
2008-06-01 | 100
2008-07-01 | 72
2008-08-01 | 91
2008-09-01 | 92
2008-10-01 | 79
2008-11-01 | 65
(12 rows)
```
But some of them miss some intervals because there is no data present, as this one:
```
select to_char(date_trunc('month',date), 'YYYY-MM-DD'), count(distinct post_id)
from some_table
where category_id=1
and entity_id = 75
and entity2_id = 115
and date <= '2008-12-06'
and date >= '2007-12-01'
group by date_trunc('month',date)
order by date_trunc('month',date);
to_char | count
------------+-------
2007-12-01 | 2
2008-01-01 | 2
2008-03-01 | 1
2008-04-01 | 2
2008-06-01 | 1
2008-08-01 | 3
2008-10-01 | 2
(7 rows)
```
where the required resultset is:
```
to_char | count
------------+-------
2007-12-01 | 2
2008-01-01 | 2
2008-02-01 | 0
2008-03-01 | 1
2008-04-01 | 2
2008-05-01 | 0
2008-06-01 | 1
2008-07-01 | 0
2008-08-01 | 3
2008-09-01 | 0
2008-10-01 | 2
2008-11-01 | 0
(12 rows)
```
A count of 0 for missing entries.
I have seen earlier discussions on Stack Overflow but they don't solve my problem it seems, since my grouping period is one of (day, week, month, quarter, year) and decided on runtime by the application. So an approach like left join with a calendar table or sequence table will not help I guess.
My current solution to this is to fill in these gaps in Python (in a Turbogears App) using the calendar module.
Is there a better way to do this? | You can create the list of all first days of the last year (say) with
```
select distinct date_trunc('month', (current_date - offs)) as date
from generate_series(0,365,28) as offs;
date
------------------------
2007-12-01 00:00:00+01
2008-01-01 00:00:00+01
2008-02-01 00:00:00+01
2008-03-01 00:00:00+01
2008-04-01 00:00:00+02
2008-05-01 00:00:00+02
2008-06-01 00:00:00+02
2008-07-01 00:00:00+02
2008-08-01 00:00:00+02
2008-09-01 00:00:00+02
2008-10-01 00:00:00+02
2008-11-01 00:00:00+01
2008-12-01 00:00:00+01
```
Then you can join with that series. | This question is old. But since fellow users picked it as master for a new duplicate I am adding a proper answer.
### Proper solution
```
SELECT *
FROM (
SELECT day::date
FROM generate_series(timestamp '2007-12-01'
, timestamp '2008-12-01'
, interval '1 month') day
) d
LEFT JOIN (
SELECT date_trunc('month', date_col)::date AS day
, count(*) AS some_count
FROM tbl
WHERE date_col >= date '2007-12-01'
AND date_col <= date '2008-12-06'
-- AND ... more conditions
GROUP BY 1
) t USING (day)
ORDER BY day;
```
Use `LEFT JOIN`, of course.
[`generate_series()`](https://www.postgresql.org/docs/current/functions-srf.html) can produce a table of timestamps on the fly, and very fast. See:
* [Generating time series between two dates in PostgreSQL](https://stackoverflow.com/questions/14113469/generating-time-series-between-two-dates-in-postgresql/46499873#46499873)
It's typically faster to aggregate *before* you join. Related answer with test case in a fiddle:
* [PostgreSQL - order by an array](https://stackoverflow.com/questions/15664373/postgresql-order-by-an-array/15674585#15674585)
Cast the `timestamp` to `date` (`::date`) for a basic format. For more use [`to_char()`](https://www.postgresql.org/docs/current/functions-formatting.html).
`GROUP BY 1` is syntax shorthand to reference the first output column. Could be `GROUP BY day` as well, but that might conflict with an existing column of the same name. Or `GROUP BY date_trunc('month', date_col)::date` but that's too long for my taste.
Works with the available interval arguments for [`date_trunc()`](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC).
[`count()` never returns `NULL`](https://www.postgresql.org/docs/current/functions-aggregate.html) - `0` for no rows - but the `LEFT JOIN` does.
To return `0` instead of `NULL` in the outer `SELECT`, use `COALESCE(some_count, 0) AS some_count`. [The manual.](https://www.postgresql.org/docs/current/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL)
For a **more generic solution or arbitrary time intervals** see:
* [Best way to count rows by arbitrary time intervals](https://stackoverflow.com/questions/15576794/best-way-to-count-records-by-arbitrary-time-intervals-in-railspostgres/15577413#15577413) | How to return rows with 0 count for missing data? | [
"",
"python",
"database",
"postgresql",
"left-join",
"generate-series",
""
] |
Has anybody tried any Unit Test generators for .Net?
I assume although it won't be any substitute for any good unit test written by a person who has written the functionality, but I think it will take away some of work and be a starting point on which we can better the unit tests.
Thanks. | Unit test generation is the wrong way to perform unit testing. The proper way to do unit testing is to create test cases before you write functional code, then develop your code until the tests validate, this is know as TDD (Test Driven Development).
One of the key reasons unit test generation is a bad idea is because if there are any bugs in your existing code, the tests will be generated against those bugs, therefore if you fix them in the future, the bad tests will fail and you'll assume something is broken, when it's actually been fixed.
But since the code is written, it's now water under the bridge. And possible buggy unit tests are better than no unit tests at all. I've always preferred NUnit and there's a NUnit compatible test generator [here](http://www.kellermansoftware.com/p-30-nunit-test-generator.aspx) (very affordable). | Have you considered [Pex](http://research.microsoft.com/Pex/)? It's from Microsoft Research.
> Pex automatically produces a small
> test suite with high code coverage for
> a .NET program. To this end, Pex
> performs a systematic program analysis
> (using dynamic symbolic execution,
> similar to path-bounded
> model-checking) to determine test
> inputs for Parameterized Unit Tests.
> Pex learns the program behavior by
> monitoring execution traces. Pex uses
> a constraint solver to produce new
> test inputs which exercise different
> program behavior. | Unit test case generator | [
"",
"c#",
".net",
"unit-testing",
""
] |
Out of the following queries, which method would you consider the better one? What are your reasons (code efficiency, better maintainability, less WTFery)...
```
SELECT MIN(`field`)
FROM `tbl`;
SELECT `field`
FROM `tbl`
ORDER BY `field`
LIMIT 1;
``` | In the worst case, where you're looking at an unindexed field, using `MIN()` requires a single full pass of the table. Using `SORT` and `LIMIT` requires a filesort. If run against a large table, there would likely be a significant difference in percieved performance. As an anecdotal data point, `MIN()` took .36s while `SORT` and `LIMIT` took .84s against a 106,000 row table on my dev server.
If, however, you're looking at an indexed column, the difference is harder to notice (meaningless data point is 0.00s in both cases). Looking at the output of explain, however, it looks like `MIN()` is able to simply pluck the smallest value from the index ('Select tables optimized away' and 'NULL' rows) whereas the `SORT` and `LIMIT` still needs needs to do an ordered traversal of the index (106,000 rows). The actual performance impact is probably negligible.
It looks like `MIN()` is the way to go - it's faster in the worst case, indistinguishable in the best case, is standard SQL and most clearly expresses the value you're trying to get. The only case where it seems that using `SORT` and `LIMIT` would be desirable would be, as [mson](https://stackoverflow.com/users/36902/mson) mentioned, where you're writing a general operation that finds the top or bottom N values from arbitrary columns and it's not worth writing out the special-case operation. | ```
SELECT MIN(`field`)
FROM `tbl`;
```
Simply because it is ANSI compatible. Limit 1 is particular to MySql as TOP is to SQL Server. | MIN/MAX vs ORDER BY and LIMIT | [
"",
"sql",
"mysql",
""
] |
I have the source code of an application written in C++ and I just want to comment something using:
```
#ifdef 0
...
#endif
```
And I get this error
> error: macro names must be identifiers
Why is this happening? | The #ifdef directive is used to check *if a preprocessor symbol is defined.* The standard (`C11 6.4.2 Identifiers`) mandates that identifiers must not start with a digit:
```
identifier:
identifier-nondigit
identifier identifier-nondigit
identifier digit
identifier-nondigit:
nondigit
universal-character-name
other implementation-defined characters>
nondigit: one of
_ a b c d e f g h i j k l m
n o p q r s t u v w x y z
A B C D E F G H I J K L M
N O P Q R S T U V W X Y Z
digit: one of
0 1 2 3 4 5 6 7 8 9
```
The correct form for using the pre-processor to block out code is:
```
#if 0
: : :
#endif
```
You can also use:
```
#ifdef NO_CHANCE_THAT_THIS_SYMBOL_WILL_EVER_EXIST
: : :
#endif
```
but you need to be confident that the symbols will *not* be inadvertently set by code other than your own. In other words, don't use something like `NOTUSED` or `DONOTCOMPILE` which others may also use. To be safe, the `#if` option should be preferred. | Use the following to evaluate an expression (constant 0 evaluates to false).
```
#if 0
...
#endif
``` | Error: macro names must be identifiers using #ifdef 0 | [
"",
"c++",
"macros",
"c-preprocessor",
""
] |
In the context of C++ (not that it matters):
```
class Foo{
private:
int x[100];
public:
Foo();
}
```
What I've learnt tells me that if you create an instance of Foo like so:
```
Foo bar = new Foo();
```
Then the array x is allocated on the heap, but if you created an instance of Foo like so:
```
Foo bar;
```
Then it's created on the stack.
I can't find resources online to confirm this. | Given a slight modification of your example:
```
class Foo{
private:
int x[100];
int *y;
public:
Foo()
{
y = new int[100];
}
~Foo()
{
delete[] y;
}
}
```
Example 1:
```
Foo *bar = new Foo();
```
* x and y are on the heap:
* sizeof(Foo\*) is created on the stack.
* sizeof(int) \* 100 \* 2 + sizeof(int \*) is on the heap
---
Example 2:
```
Foo bar;
```
* x is on the stack, and y is on the heap
* sizeof(int) \* 100 is on the stack (x) + sizeof(int\*)
* sizeof(int) \* 100 is on the heap (y)
Actual sizes may differ slightly due to class/struct alignment depending on your compiler and platform. | Strictly speaking, according to the standard the object need not exist on a stack or heap. The standard defines 3 types of 'storage duration', but doesn't state exactly how the storage must be implemented:
1. static storage duration
2. automatic storage duration
3. dynamic storage duration
Automatic storage duration is typically (nearly always) implemented using the stack.
Dynamic storage duration is typically implemented using the heap (ultimately via `malloc()`), though this can be overridden even by the compiler's user.
Static storage duration is what it typically known as globals (or static storage).
The standard has this to say about these things (the following are excerpts form various bits of 3.7 - Storage Duration):
> Static and automatic storage durations
> are associated with objects introduced
> by declarations (3.1) and implicitly
> created by the implementation (12.2).
> The dynamic storage duration is
> associated with objects created with
> operator new (5.3.4).
>
> ...
>
> All objects which neither have dynamic
> storage duration nor are local have
> static storage duration. The storage
> for these objects shall last for the
> duration of the program (3.6.2,
> 3.6.3).
>
> ...
>
> Local objects explicitly declared auto
> or register or not explicitly declared
> static or extern have automatic
> storage duration. The storage for
> these objects lasts until the block in
> which they are created exits.
>
> ...
>
> Objects can be created dynamically
> during program execution (1.9), using
> new-expressions (5.3.4), and destroyed
> using delete-expressions (5.3.5). A C
> + + implementation provides access to, and management of, dynamic storage via
> the global allocation functions
> operator new and operator new[] and
> the global deallocation functions
> operator delete and operator delete[].
>
> ...
>
> The library provides default
> definitions for the global allocation
> and deallocation functions. Some
> global allocation and deallocation
> functions are replaceable (18.4.1)
And finally (regarding the array in your example class):
> 3.7.4 Duration of sub-objects [basic.stc.inherit]
>
> The storage duration of member subobjects, base class subobjects and array elements is that of their complete
> object (1.8). | Does this type of memory get allocated on the heap or the stack? | [
"",
"c++",
"memory-management",
"stack",
"heap-memory",
""
] |
I have some XML in an XmlDocument, and I want to display it on an ASP.NET page. (The XML should be in a control; the page will have other content.) Right now, we're using the Xml control for that. Trouble is, the XML displays with no indentation. Ugly.
It appears that I'm supposed to create an XSLT for it, but that seems kind of boring. I'd rather just throw it into a control and have it automagically parse the XML and indent correctly. Is there an easy way to do that? | You could try to use XmlWriter/XmlTextWriter, set the writer's Indentation property, write to a StringBuilder or MemoryStream, and output the result inside a <pre> tag | A quick (and dirty) way of doing this would be to use an IFrame.
In truth, an XSLT is the "ideal" way for formatting an XML for display. Another option would be to parse it manually for display.
To use an Iframe:
ASPX side:
```
< iframe runat="server" id="myXMLFrame" src="~/MyXmlFile.xml" /></pre>
```
Code Side:
```
myXMLFrame.src = Page.ResolveClientUrl("~/MyXmlFile.xml")
``` | Easiest way to display XML on an ASP.NET page | [
"",
"c#",
"asp.net",
"xml",
"vb.net",
""
] |
I think I am having a mental block but can someone please enlighten me on how to combine these two LINQ statements into one?
```
/// <summary>
/// Returns an array of Types that implement the supplied generic interface in the
/// current AppDomain.
/// </summary>
/// <param name="interfaceType">Type of generic interface implemented</param>
/// <param name="includeAbstractTypes">Include Abstract class types in the search</param>
/// <param name="includeInterfaceTypes">Include Interface class types in the search</param>
/// <returns>Array of Types that implement the supplied generic interface</returns>
/// <remarks>
/// History.<br/>
/// 10/12/2008 davide Method creation.<br/>
/// </remarks>
public static Type[] GetTypesImplementingGenericInterface(Type interfaceType, bool includeAbstractTypes, bool includeInterfaceTypes)
{
// Use linq to find types that implement the supplied interface.
var allTypes = AppDomain.CurrentDomain.GetAssemblies().ToList()
.SelectMany(s => s.GetTypes())
.Where(p => p.IsAbstract == includeAbstractTypes
&& p.IsInterface == includeInterfaceTypes);
var implementingTypes = from type in allTypes
from intf in type.GetInterfaces().ToList()
where intf.FullName != null && intf.FullName.Contains(interfaceType.FullName)
select type;
return implementingTypes.ToArray<Type>();
}
```
I am avoiding IsAssignableFrom as its seems to fail when not supplying the specific type of the generic interface therefore I believe using FullName caparison over IsAssignableFrom should suffice, for example:
```
namespace Davide
{
interface IOutput<TOutputType> { }
class StringOutput : IOutput<string> { }
}
```
typeof(IOutput<>).FullName will return "Davide+IOutput`1"
typeof(StringOutput).GetInterfaces()[0].FullName will return "Davide+IOutput`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
Therefore using FullName.Contains should suffice | After a short discussion with Jon Skeet and a bit more thought, I have posted the following answer. I altered the method to utilise GetGenericTypeDefinition rather than FullName.Contains, this would be a more robust solution. I also altered the LINQ query Where clauses for IsAbstract and IsInterface as these did not exclude types as expected. Thanks everyone for your feedback.
```
/// <summary>
/// Returns an array of Types that implement the supplied generic interface in the
/// current AppDomain.
/// </summary>
/// <param name="interfaceType">Type of generic interface implemented</param>
/// <param name="excludeAbstractTypes">Exclude Abstract class types in the search</param>
/// <param name="excludeInterfaceTypes">Exclude Interface class types in the search</param>
/// <returns>Array of Types that implement the supplied generic interface</returns>
/// <remarks>
/// History.<br/>
/// 11/12/2008 davide Created method.<br/>
/// 11/12/2008 davide Altered method to use a two LINQ query pass.<br/>
/// 11/12/2008 davide Altered method to use optimised combined LINQ query.<br/>
/// 12/12/2008 davide Altered method and replaced FullName criteria match with GetGenericTypeDefinition.<br/>
/// </remarks>
public static Type[] GetTypesImplementingGenericInterface(Type interfaceType, bool excludeAbstractTypes, bool excludeInterfaceTypes)
{
if (!interfaceType.IsGenericType)
{
throw new ArgumentException("Supplied interface is not a Generic type");
}
if (interfaceType.ContainsGenericParameters)
{
interfaceType = interfaceType.GetGenericTypeDefinition();
}
// Use linq to find types that implement the supplied generic interface.
var implementingTypes = from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where (type.IsAbstract != excludeAbstractTypes) || (!excludeAbstractTypes)
where (type.IsInterface != excludeInterfaceTypes) || (!excludeInterfaceTypes)
from intf in type.GetInterfaces()
where intf.IsGenericType && intf.GetGenericTypeDefinition() == interfaceType
select type;
return implementingTypes.ToArray<Type>();
}
``` | SelectMany translates to a second "from":
```
var implementors = from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.IsAbstract == includeAbstractTypes
where type.IsInterface == includeInterfaceTypes
from intf in type.GetInterfaces()
where intf.FullName != null &&
intf.FullName.Contains(interfaceType.FullName)
select type;
```
I've split conditions into multiple "where" clauses for subjective clarity, btw.
This compiles, but I haven't tested to see whether it actually works or not :) As another answer has shown, you could use "Any" with GetInterfaces() instead of the final "from" clause.
Note that there's no need to keep calling ToList() all over the place - LINQ is designed to be able to work on sequences throughout.
By the way, I'm not sure why you're going through type.GetInterfaces() to check. Is there anything different (and desirable) from that vs using [Type.IsAssignableFrom](http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx)? That would make it simpler:
```
var implementors = from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.IsAbstract == includeAbstractTypes
where type.IsInterface == includeInterfaceTypes
where interfaceType.IsAssignableFrom(type)
select type;
```
Do you actually have the same interface type name in a different assembly somewhere? | Combine two LINQ queries? | [
"",
"c#",
"linq",
""
] |
I'm working on an ASP .NET 2.0 site which uses a Web Application project file, and therefore compiles to a dll rather than deploying the source code as you do with the older style Web Site projects.
The site works fine on my test server (Windows Server 2003 R2, IIS6) when it runs in the root of a website. However I need to run it under a virtual directory instead. When I switch over to that, I get the following error on browsing to any of the pages in the site
CS1519: Invalid token ',' in class, struct, or interface member declaration
The error message goes onto tell me the line number and code file, however the code file is under the Temporary ASP .NET files folder and when I try to find it, it's not there.
As such I'm unable to work out which page is causing the issue although I suspect it could be the master page, if this error occurs on all pages. Has anyone else seen this before or found a solution? | Turns out the problem was related to inheriting the config settings of the site above mine in the virtual hierarchy.
That site uses a custom profile whose properties are defined under system.web, profile, properties in the config file. The type of one of the properties was specified in the "Namespace.ClassName, AssemblyName" format.
When I removed the ", AssemblyName" from the end, the issue resolved itself, because I'd got rid of the comma that was the invalid token.
I can only assume that, when ASP .NET compiles pages at runtime, it must have been compiling the profile class too, and using the property definitions in the config file during the code generation. | It sounds like you haven't set the virtual as an **application** in IIS, or it is running the wrong version of ASP.NET (i.e. 1.1, when it should be 2.0.blah).
The virtual should have the cog icon in the IIS view, and in the properties pane, must have an application name. | Resolving compiler error CS1519: Invalid token ',' in class, struct, or interface member declaration | [
"",
"c#",
".net",
"asp.net",
""
] |
I've run across an interesting PHP/SOAP error that has me stymied. After searching I have not found a plausible explanation, and I'd appreciate your help. Here's the background:
I have a site built in PHP/[CodeIgniter](http://codeigniter.com/) which uses SOAP to communicate over SSL with a back-end system provided by a third party (let's call them "Company X" to protect the innocent) not in my control. In the spirit of good MVC, I put the code specific to interacting with that data source in a separate model (`system/application/models/company_x.php`). I have been developing locally using MAMP on my Mac, and just about everything was relatively smooth through testing and development; including calling Company X's web service over SSL. I should probably mention that their web service had strange WSDL that PHP 5's SOAP didn't like. Things like required parameters that were not there. It's been a little odd to call SOAP methods very explicitly, but I got it going and it worked through testing. I even deployed it to a test site at [Mosso](http://www.mosso.com/), and I could have sworn that it worked for a time up there too.
Imagine my surprise when every call to the SOAP web service starting producing errors like the following:
```
A PHP Error was encountered
Severity: Warning
Message: SoapClient::__doRequest() [soapclient.--dorequest]:
WARNING: URL fopen access
Filename: models/company_x.php
Line Number: 86
```
The error logs didn't give any more information other than the full path to the model file on the server. It works locally, and I thought it worked on Mosso before. Maybe Mosso changed their settings, and disabled SOAP or something. A little `phpinfo()` later, and they have more than enough. I thought that maybe my Mac is more tolerant of the SSL certificate. After all, it's a GoDaddy \*.domain.com cert, maybe `fopen` is having trouble getting through. I whipped up a test file to connect over SSL, and put it on Mosso and it worked.
I'm wondering why is `fopen` access suddenly a problem for SOAP? What is it about Mosso that is making this difficult suddenly? Do I need to override some `php.ini` setting? Could it be, like is so often with unhelpful errors like this, something completely different?
**Update:** here is the configure command from phpinfo():
`'./configure' '--build=x86_64-redhat-linux-gnu' '--host=x86_64-redhat-linux-gnu' '--target=x86_64-redhat-linux-gnu' '--program-prefix=' '--prefix=/usr' '--exec-prefix=/usr' '--bindir=/usr/bin' '--sbindir=/usr/sbin' '--sysconfdir=/etc' '--datadir=/usr/share' '--includedir=/usr/include' '--libdir=/usr/lib64' '--libexecdir=/usr/libexec' '--localstatedir=/var' '--sharedstatedir=/usr/com' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--cache-file=../config.cache' '--with-libdir=lib64' '--with-config-file-path=/etc' '--with-config-file-scan-dir=/etc/php.d' '--disable-debug' '--with-pic' '--disable-rpath' '--without-pear' '--with-bz2' '--with-curl' '--with-exec-dir=/usr/bin' '--with-freetype-dir=/usr' '--with-png-dir=/usr' '--enable-gd-native-ttf' '--without-gdbm' '--with-gettext' '--with-gmp' '--with-iconv' '--with-jpeg-dir=/usr' '--with-openssl' '--with-png' '--with-pspell' '--with-expat-dir=/usr' '--with-pcre-regex=/usr' '--with-zlib' '--with-layout=GNU' '--enable-exif' '--enable-ftp' '--enable-magic-quotes' '--enable-sockets' '--enable-sysvsem' '--enable-sysvshm' '--enable-sysvmsg' '--enable-track-vars' '--enable-trans-sid' '--enable-yp' '--enable-wddx' '--with-kerberos' '--enable-ucd-snmp-hack' '--with-unixODBC=shared,/usr' '--enable-memory-limit' '--enable-shmop' '--enable-calendar' '--enable-dbx' '--enable-dio' '--with-ming' '--with-mime-magic' '--with-sqlite=shared' '--with-libxml-dir=/usr' '--with-xml' '--with-system-tzdata' '--with-apxs2=/usr/sbin/apxs' '--without-mysql' '--without-gd' '--without-odbc' '--disable-dom' '--disable-dba' '--without-unixODBC' '--disable-pdo' '--disable-xmlreader' '--disable-xmlwriter' '--disable-json'`
**Note**: My comment below that `phpinfo()` reports that furl is allowed; weird! | OK, a little update on this problem: the error *mysteriously* disappeared without any change from me. I will have to assume that there was some odd configuration error on Mosso that was silently fixed. It is also remotely possible that there was a problem with Company X's setup. That is the worst kind of fix IMO! Thanks anyway to everyone who looked in on this. | You might have this
<http://us.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen>
missing.
Remember, you can always use phpinfo() to visually compare the environment between machines. | I have a mysterious PHP SOAP error on my host, but can't duplicate locally | [
"",
"php",
"soap",
"codeigniter",
"mosso",
""
] |
Consider this sample code:
```
<div class="containter" id="ControlGroupDiv">
<input onbeforeupdate="alert('bingo 0'); return false;" onclick="alert('click 0');return false;" id="Radio1" type="radio" value="0" name="test" checked="checked" />
<input onbeforeupdate="alert('bingo 1'); return false;" onclick="alert('click 1');return false;" id="Radio2" type="radio" value="1" name="test" />
<input onbeforeupdate="alert('bingo 2'); return false;" onclick="alert('click 2');return false;" id="Radio3" type="radio" value="2" name="test" />
<input onbeforeupdate="alert('bingo 3'); return false;" onclick="alert('click 3');return false;" id="Radio4" type="radio" value="3" name="test" />
<input onbeforeupdate="alert('bingo 4'); return false;" onclick="alert('click 4');return false;" id="Radio5" type="radio" value="4" name="test" />
<input onbeforeupdate="alert('bingo 5'); return false;" onclick="alert('click 5');return false;" id="Radio6" type="radio" value="5" name="test" />
</div>
```
On FireFox 2 and 3, putting the `return false` on the click event of a radio button prevents the value of it and of all the other radio buttons in the group from changing. This effectively makes it read-only without disabling it and turning it gray.
On Internet Explorer, if another radio button is checked and you click on a different one in the group, the checked one clears before the click event fires on the one you clicked. However, the one you clicked on does not get selected because of the 'return false' on the click event.
[According to MSDN](http://msdn.microsoft.com/en-us/library/ms536913(VS.85).aspx), the [`onbeforeupdate`](http://msdn.microsoft.com/en-us/library/ms536908(VS.85).aspx) event fires on all controls in the control group before the click event fires and I assumed that was where the other radio button was being cleared. But if you try the code above, no alert is ever shown from the `onbeforeupdate` event - you just get the click event alert. Evidently that event is never getting fired or there isn't a way to trap it.
Is there any event you can trap that allows you to prevent other radio buttons in the group from clearing?
Note that this is a simplified example, we are actually using jQuery to set event handlers and handle this.
**Update:**
If you add this event to one of the radio buttons:
```
onmousedown="alert('omd'); return false;"
```
The alert box pops up, you close it, and the click event *never fires*. So we thought we had it figured out, but no, it couldn't be that easy. If you remove the alert and change it to this:
```
onmousedown="return false;"
```
It doesn't work. The other radio button clears and the click event on the button you clicked on fires. `onbeforeupdate` still never fires.
We thought it might be timing (that's always a theory even though it's rarely true), so I tried this:
```
onmousedown="for (i=0; i<100000; i++) {;}; return false;"
```
You click, it pauses for a while, then the other radio button clears and then the click event fires. Aaargh!
**Update:**
Internet Explorer sucks. Unless someone comes up with a good idea, we're abandoning this approach and going with the checkbox jQuery extension which does do what we want, but puts a heavier client-side script burden on the page and requires more recoding of the HTML because of the ASP.Net server control rendering and master-page name mangling. | None of these approaches worked - we wound up using the checkbox jQuery plug-in that replaces the checkboxes and radio buttons with shiftable images. That means that we can control the view of the disabled controls.
PITA but it works. | Yup, that's a strange bug. I did manage to cook up a workaround. I use a bit of Prototype to handle class names here. It works in IE and FF. You can probably shorten it up with a selector instead of a crude loop.
```
<form name="f1">
<input type=radio onmouseover="recordMe()" onclick="clickCheck();return false" checked value="A" name="r1" id="radio1" />
<input type=radio onmouseover="recordMe()" onclick="clickCheck();return false" value="B" name="r1" id="radio2" />
</form>
<script type="text/javascript">
function recordMe() {
for(var x=0;x<document.f1.r1.length;x++) {
if(document.f1.r1[x].checked) {
$(document.f1.r1[x].id).addClassName('radioChecked')
}
}
}
function clickCheck() {
for(var x=0;x<document.f1.r1.length;x++) {
if($(document.f1.r1[x].id).hasClassName('radioChecked')) {
$(document.f1.r1[x].id).checked=true
}
}
}
</script>
``` | Can You Trap These Radio Button Events On Internet Explorer? | [
"",
"javascript",
"jquery",
"html",
"internet-explorer",
""
] |
I have a thread that needs to be executed every 10 seconds. This thread contains several calls (12 - 15) to a database on another server. Additionally, it also accesses around 3 files. Consequently, there will be quite a lot of IO and network overhead.
What is the best strategy to perform the above?
One way would be to use the sleep method along with a while loop, but that would be a bad design.
Will a class similar to Timer be helpful in this case? Also, would it be better to create a couple of more threads (one for IO and one for JDBC), instead of having them run in one thread? | I find that a [ScheduledExecutorService](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html) is an excellent way to do this. It is arguably slightly more complex than a `Timer`, but gives more flexibility in exchange (e.g. you could choose to use a single thread or a thread pool; it takes units other than solely milliseconds).
```
ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor();
Runnable periodicTask = new Runnable() {
public void run() {
// Invoke method(s) to do the work
doPeriodicWork();
}
};
executor.scheduleAtFixedRate(periodicTask, 0, 10, TimeUnit.SECONDS);
``` | One option is to create a ScheduledExecutorService to which you can then schedule your job:
```
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
ex.scheduleWithFixedDelay(...);
```
If you did decide to have multiple threads, then you can create a ScheduledExecutorService with more threads (again, via the Executors class).
In terms of how many threads and what you put in each thread, in terms of performance, I'd say this depends on:
* for your particular application, can one thread genuinely "do work" while another one is waiting for I/O?
* would your multiple threads ultimately "thrash the same resource" (e.g. read from files in different locations on the same dsk) and thus slow one another down, or would they be simultaneously hitting different resources? | Running a Java Thread in intervals | [
"",
"java",
"multithreading",
"jdbc",
"timer",
""
] |
For my web application running on LAMP, I need to be able to deploy database migrations and code changes on multiple servers and be able to test deployment afterwards, all of this automatically done by scripts.
Currently I'm torn between using directly my build tool ([Phing](http://phing.info/trac/)) with some special deployment/test tasks, or shell scripts, or a scripting language like Ruby or Python.
The problem is that I feel that a build tool should be used to build, not to deploy. I also feel that shell scripts are hard to maintain and not very readable.
Do you have any good advice on this subject ? | For PHP projects, Phing is the way to go. Deployment is definitely one of its intended usage, considering that in PHP there isn't any "real" build process - as scripts are not compiled.
From the official site:
> If you find yourself writing custom
> scripts to handle the packaging,
> deploying, or testing of your
> applications, then we suggest looking
> at the Phing framework.
Phing can do everything shell/python/ruby scripts can do, and can be extended in PHP which is its major draw for PHP developers. Why would you want to use ruby/python if you are a PHP developer? | A lot of people [here on stackoverflow](https://stackoverflow.com/questions/tagged/capistrano) seem to really like [Capistrano](http://capistranorb.com/). | What tools/languages do you use for PHP web application deployment? | [
"",
"php",
"deployment",
"web-applications",
"build-process",
""
] |
(All of the following is to be written in Java)
I have to build an application that will take as input XML documents that are, potentially, very large. The document is encrypted -- not with XMLsec, but with my client's preexisting encryption algorithm -- will be processed in three phases:
First, the stream will be decrypted according to the aforementioned algorithm.
Second, an extension class (written by a third party to an API I am providing) will read some portion of the file. The amount that is read is not predictable -- in particular it is not guaranteed to be in the header of the file, but might occur at any point in the XML.
Lastly, another extension class (same deal) will subdivide the input XML into 1..n subset documents. It is possible that these will in some part overlap the portion of the document dealt with by the second operation, ie: I believe I will need to rewind whatever mechanism I am using to deal with this object.
Here is my question:
Is there a way to do this without ever reading the entire piece of data into memory at one time? Obviously I can implement the decryption as an input stream filter, but I'm not sure if it's possible to parse XML in the way I'm describing; by walking over as much of the document is required to gather the second step's information, and then by rewinding the document and passing over it again to split it into jobs, ideally releasing all of the parts of the document that are no longer in use after they have been passed. | Stax is the right way. I would recommend looking at [Woodstox](http://woodstox.codehaus.org/) | This sounds like a job for StAX ([JSR 173](http://jcp.org/en/jsr/detail?id=173)). StAX is a pull parser, which means that it works more or less like an event based parser like SAX, but that you have more control over when to stop reading, which elements to pull, ...
The usability of this solution will depend a lot on what your extension classes are actually doing, if you have control over their implementation, etc...
The main point is that if the document is very large, you probably want to use an event based parser and not a tree based, so you will not use a lot of memory.
Implementations of StAX can be found from SUN ([SJSXP](https://sjsxp.dev.java.net/)), [Codehaus](http://stax.codehaus.org/) or a few other providers. | Parsing very large XML documents (and a bit more) in java | [
"",
"java",
"xml",
"memory-management",
"streaming",
"sax",
""
] |
I understand that, if `S` is a child class of `T`, then a `List<S>` is **not** a child of `List<T>`. Fine. But interfaces have a different paradigm: if `Foo` implements `IFoo`, then why is a `List<Foo>` not (an example of) a `List<IFoo>`?
As there can be no actual class `IFoo`, does this mean that I would always have to cast each element of the list when exposing a `List<IFoo>`? Or is this simply bad design and I have to define my own collection class `ListOfIFoos` to be able to work with them? Neither seem reasonable to me...
What would be the best way of exposing such a list, given that I am trying to program to interfaces? I am currently tending towards actually storing my `List<Foo>` internally as a `List<IFoo>`. | Your `List<Foo>` is not a subclass if `List<IFoo>` because you cannot store an `MyOwnFoo` object in it, which also happens to be an `IFoo` implementation. ([Liskov substitution principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle))
The idea of storing a `List<IFoo>` instead of a dedicated `List<Foo>` is OK. If you need casting the list's contents to it's implementation type, this probably means your interface is not appropriate. | Here's an example of why you can't do it:
```
// Suppose we could do this...
public List<IDisposable> GetDisposables()
{
return new List<MemoryStream>();
}
// Then we could do this
List<IDisposable> disposables = GetDisposables();
disposables.Add(new Form());
```
At that point a list which was created to hold MemoryStreams now has a Form in it. Bad!
So basically, this restriction is present to maintain type safety. In C# 4 and .NET 4.0 there will be *limited* support for this (it's called *variance*) but it still won't support this particular scenario, for exactly the reasons given above. | Why can I not return a List<Foo> if asked for a List<IFoo>? | [
"",
"c#",
"generics",
"interface",
""
] |
I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.
Is there a function that can do this easily?
For example:
```
$string1 = "I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.";
$string2 = 100charfunction($string1);
print $string2
```
To get:
```
I am looking for a way to pull the first 100 characters from a string vari
``` | ```
$small = substr($big, 0, 100);
```
For [String Manipulation](https://www.php.net/manual/en/ref.strings.php) here is a page with a lot of function that might help you in your future work. | You could use substr, I guess:
```
$string2 = substr($string1, 0, 100);
```
or mb\_substr for multi-byte strings:
```
$string2 = mb_substr($string1, 0, 100);
```
You could create a function wich uses this function and appends for instance `'...'` to indicate that it was shortened. (I guess there's allready a hundred similar replies when this is posted...) | How do you pull first 100 characters of a string in PHP | [
"",
"php",
"string",
""
] |
I have a ASP.NET project, in which I have a method with 10 local variables. This method calls about 10 other methods. 3 of the called methods need all the variables. Is it considered good practice to turn all those variables into global members, and then they don't have to passed as parameters? | create a structure instead and pass the structure instead of passing those 10 parameters
Eg :
```
public struct user
{
public string FirstName;
public string LastName;
public string zilionotherproperties;
public bool SearchByLastNameOnly;
public datetime date1;
}
``` | If you want to pass complex state around, package it in an object - i.e.
```
public class Foo {
public string Key {get;set;}
public decimal Quantity {get;set;}
// etc
}
```
And have the methods accept this object as an argument. Then you just create an instance of this and pass it along.
Global is a big no-no; ASP.NET is highly threaded - this would be a nightmare. Per-request state is possible, but a bit messy. | Global member vs. passing parameters | [
"",
"c#",
""
] |
Is it possible to check who is entering your website in PHP. I have a web application ( written in PHP) that should only allow users entering from some particular websites. Is it possible to get the referral websites by examining the `_Request` object? If yes, how? | Yes, but keep in mind some proxies and other things strip this information out, and it can be easily forged. So never rely on it. For example, don't think your web app is secure from [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) because you check the referrer to match your own server.
```
$referringSite = $_SERVER['HTTP_REFERER']; // is that spelt wrong in PHP ?
```
If you want to only allow requests from a specific domain you'll need to parse some of the URL to get the top level domain. As I've learned more, this can be done with PHP's [parse\_url()](http://au.php.net/function.parse-url).
As [andyk](https://stackoverflow.com/users/26721/andyk) points out in the comments, you will also have to allow for www.example.com and example.com. | While you can look at `$_SERVER['HTTP_REFERER']` to get the referring site, don't bet the farm on it. The browser sets this header and it's easily spoofed.
If it's critical that only people coming from specific referrers view your site, don't use this method. You'll have to find another way, like basic auth, to protect your content. I'm not saying that you shouldn't use this technique, just keep in mind that it's not fool-proof.
BTW, you can also block referrers at the apache level [using mod\_rewrite](http://www.htaccess-guide.com/index.php?a=7). | Inspect the referrer in PHP | [
"",
"php",
"referrer",
""
] |
Is anyone out there using Drupal for large scale, business critical enterprise applications?
Does Drupal's lack of database transaction support dissuade potential users?
Are there any other lightweight web-frameworks based on dynamic languages that people are using for these types of apps? What about Java portals such as JBossPortal or Jetspeed as an alternative or a Drupal + J2EE hybrid architecture? | **Answer One: Yes**
* internet\_search://"drupal in the enterprise" <- use this exact phrase
* [Drupal "Success Stories"](http://drupal.org/success-stories)
* [Student Activities Supports 170 Drupal 6 Sites at Texas A&M](http://drupal.org/node/314624)
**Answer Two: It depends**
There are surely some who have concerns about this issue. Drupal's database support and schema have been subject to some scrutiny and criticism over its evolution. That is likely to diminish if some or all of the planned enhancements make it into Drupal 7. This is the one out of your three questions that cannot be easily and definitively answered by searching the internet.
* [Drupal 7 Database Plans](http://www.garfieldtech.com/blog/drupal-7-database-plans)
* [Drupal 7 Database Update](http://www.garfieldtech.com/blog/database-7-update)
**Answer Three:**
* [Open Source Content Management Systems](http://en.wikipedia.org/wiki/Category:Open_source_content_management_systems)
**Answer Four: (Update: 2010-02-03 11:25:04)**
* see also: <https://stackoverflow.com/questions/1715811> | I recommend against Drupal due to its inefficiency. Yes, it can do almost anything, but it does it slowly. For any but the simplest of sites, drupal will not build nearly as efficient a chain of queries and pages as a custom built site will. Something that can be done by hand with two SQL joins and a single PHP loop is likely to be handled by Drupal with five joins and a nested loop.
That said, I love Drupal and will continue using it in non-enterprise environments, and I cannot recommend any other CMS that does not have similar problems when presented with complex tasks. | Is Drupal ready for the enterprise? | [
"",
"php",
"drupal",
"jakarta-ee",
"comparison",
"enterprise",
""
] |
I'm working with some code (not mine I hasten to add, I don't trust this much at all) for a class which opens a socket, makes requests and listens for responses, which is throwing an exception in a way I can't comprehend when tested in xunit. I *assume* the same exception happens "live" but the class is referenced by a singleton so it is probably just hidden.
The problem manifests as "System.CannotUnloadAppDomainException: Error while unloading appdomain" in xunit and the inner exception is "System.ObjectDisposedException" thrown (essentially) inside the finaliser when closing the socket! There are no other reference to the socket which call close and dispose is protected on the Socket class so I'm not clear how else the object could be disposed.
Further, if I merely catch and absorb the ObjectDisposedException xunit terminates when it hits the line to close the listener thread.
**I just don't get how the Socket can be disposed before it's asked to close.**
My knowledge of sockets is only what I've learnt since finding this problem, so I don't know if I've provided everything SO might need. LMK if not!
```
public class Foo
{
private Socket sock = null;
private Thread tListenerThread = null
private bool bInitialised;
private Object InitLock = null;
private Object DeInitLock = null;
public Foo()
{
bInitialised = false;
InitLock = new Object();
DeInitLock = new Object();
}
public bool initialise()
{
if (null == InitLock)
return false;
lock (InitLock)
{
if (bInitialised)
return false;
sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 8);
sock.Bind( /*localIpEndPoint*/);
sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(mcIP));
tListenerThread = new Thread(new ThreadStart(listener));
tListenerThread.Start();
bInitialised = true;
return true;
}
}
~Foo()
{
if (bInitialised)
deInitialise();
}
private void deInitialise()
{
if (null == DeInitLock)
return;
lock (DeInitLock)
{
if (bInitialised)
{
sock.Shutdown(SocketShutdown.Both); //throws System.ObjectDisposedException
sock.Close();
tListenerThread.Abort(); //terminates xunit test!
tListenerThread = null;
sock = null;
bInitialised = false;
}
}
}
}
``` | If this object is eligible for garbage collection and there are no other references to the Socket, then the *socket's* finalizer may well run before your object's finalizer. I suspect that's what's happened here.
It's generally a bad idea (IMO) to do this much work in a finalizer. I can't remember the last time I implemented a finalizer at all - if you implement IDisposable, you should be fine unless you have *direct* references to unmanaged resources, which are almost always in the form of IntPtrs. Orderly shutdown should be the norm - a finalizer should only usually run if either the program is shutting down, or someone has forgotten to dispose of the instance to start with.
(I know you clarified at the start that this isn't your code - I just thought I'd explain why it's problematic. Apologies if you already knew some/all of this.) | Because of the way the garbage collector and finalizers work, finalizers must only be used if your class is the **direct** owner of an unmanaged resource such as a Window Handle, a GDI object, a global handle or any other kind of IntPtr.
**A finalizer must not try to dispose or even use a managed resource or you will risk calling a finalized or disposed object.**
I highly recommend you to read this [very important Microsoft article](http://msdn.microsoft.com/en-us/magazine/bb985010.aspx) for more detail on how garbage collection works. Also, this is the MSDN reference on [Implementing Finalize and Dispose to Clean Up Unmanaged Resources](http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx), look carefully for the recommendations at the bottom.
In a nutshell:
* If your object is holding an unmanaged resource, you should implement IDisposable and you must implement Finalizer.
* If your object is holding an IDiposable object, it should also implements IDisposable on it's own and dispose that object explicitly.
* If your object is holding both an unmanaged and a disposable, the finalizer must call two diferent version of Dispose, one that release disposable and unmanaged, the other only unmanaged. This is usually done using a Dispose(bool) function called by Dipose() and Finalizer().
* The Finalizer must never use any other resource than the unmanaged resource being released and self. Failing to do so will risk referencing collected or disposed objects, since an object is temporarily ressurected prior to finalization. | Problem disposing of socket / finalising twice? | [
"",
"c#",
"sockets",
"dispose",
"finalizer",
"xunit",
""
] |
If I wrap a SQLConnection in a Using, should I close it or does the end using handle it?
```
using cn as new system.data.sqlclient.sqlconnection()
cn.open
'{do a bunch of other stuff with commands and datareaders here}
cn.close 'Do I need this?
end using
``` | Exiting a using block calls .Dispose() on the object in question (`cn` in your example) which for a SqlConnection will close the connection and any open resources. | More precisely calling Dispose or Close will mark the underlying physical connection as "Not in use" - but doesn't really close it. A "Not in use" connection that isn't yet physically closed is thus available for pooling. Therefore - calling Dispose would return a connection to the connection pool. | Does End Using close an open SQL Connection | [
"",
".net",
"sql",
"sql-server",
"vb.net",
""
] |
Is there a quick and nice way using linq? | How about:
```
var most = list.GroupBy(i=>i).OrderByDescending(grp=>grp.Count())
.Select(grp=>grp.Key).First();
```
or in query syntax:
```
var most = (from i in list
group i by i into grp
orderby grp.Count() descending
select grp.Key).First();
```
Of course, if you will use this repeatedly, you could add an extension method:
```
public static T MostCommon<T>(this IEnumerable<T> list)
{
return ... // previous code
}
```
Then you can use:
```
var most = list.MostCommon();
``` | Not sure about the lambda expressions, but I would
1. Sort the list [O(n log n)]
2. Scan the list [O(n)] finding the longest run-length.
3. Scan it again [O(n)] reporting each number having that run-length.
This is because there could be more than one most-occurring number. | Find the most occurring number in a List<int> | [
"",
"c#",
"linq",
"list",
""
] |
In other words, can I do something like
```
for() {
for {
for {
}
}
}
```
Except N times? In other words, when the method creating the loops is called, it is given some parameter N, and the method would then create N of these loops nested one in another?
Of course, the idea is that there should be an "easy" or "the usual" way of doing it. I already have an idea for a very complicated one. | It sounds like you may want to look into [recursion.](http://en.wikipedia.org/wiki/Recursion) | jjnguy is right; recursion lets you dynamically create variable-depth nesting. However, you don't get access to data from the outer layers without a little more work. The "in-line-nested" case:
```
for (int i = lo; i < hi; ++i) {
for (int j = lo; j < hi; ++j) {
for (int k = lo; k < hi; ++k) {
// do something **using i, j, and k**
}
}
}
```
keeps the variables `i`, `j`, and `k` in scope for the innermost body to use.
Here's one quick hack to do that:
```
public class NestedFor {
public static interface IAction {
public void act(int[] indices);
}
private final int lo;
private final int hi;
private final IAction action;
public NestedFor(int lo, int hi, IAction action) {
this.lo = lo;
this.hi = hi;
this.action = action;
}
public void nFor (int depth) {
n_for (0, new int[0], depth);
}
private void n_for (int level, int[] indices, int maxLevel) {
if (level == maxLevel) {
action.act(indices);
} else {
int newLevel = level + 1;
int[] newIndices = new int[newLevel];
System.arraycopy(indices, 0, newIndices, 0, level);
newIndices[level] = lo;
while (newIndices[level] < hi) {
n_for(newLevel, newIndices, maxLevel);
++newIndices[level];
}
}
}
}
```
The `IAction` interface stipulates the role of a controlled action which takes an array of indices as the argument to its `act` method.
In this example, each instance of `NestedFor` is configured by the constructor with the iteration limits and the action to be performed by the innermost level. The parameter of the `nFor` method specifies how deeply to nest.
Here's a sample usage:
```
public static void main(String[] args) {
for (int i = 0; i < 4; ++i) {
final int depth = i;
System.out.println("Depth " + depth);
IAction testAction = new IAction() {
public void act(int[] indices) {
System.out.print("Hello from level " + depth + ":");
for (int i : indices) { System.out.print(" " + i); }
System.out.println();
}
};
NestedFor nf = new NestedFor(0, 3, testAction);
nf.nFor(depth);
}
}
```
and the (partial) output from its execution:
```
Depth 0
Hello from level 0:
Depth 1
Hello from level 1: 0
Hello from level 1: 1
Hello from level 1: 2
Depth 2
Hello from level 2: 0 0
Hello from level 2: 0 1
Hello from level 2: 0 2
Hello from level 2: 1 0
Hello from level 2: 1 1
Hello from level 2: 1 2
Hello from level 2: 2 0
Hello from level 2: 2 1
Hello from level 2: 2 2
Depth 3
Hello from level 3: 0 0 0
Hello from level 3: 0 0 1
Hello from level 3: 0 0 2
Hello from level 3: 0 1 0
...
Hello from level 3: 2 1 2
Hello from level 3: 2 2 0
Hello from level 3: 2 2 1
Hello from level 3: 2 2 2
``` | Is there any way to do n-level nested loops in Java? | [
"",
"java",
"recursion",
"loops",
"for-loop",
""
] |
I recently found LINQ and love it. I find lots of occasions where use of it is so much more expressive than the longhand version but a colleague passed a comment about me abusing this technology which now has me second guessing myself. It is my perspective that if a technology works efficiently and the code is elegant then why not use it? Is that wrong? I could spend extra time writing out processes "longhand" and while the resulting code may be a few ms faster, it's 2-3 times more code and therefore 2-3 times more chance that there may be bugs.
Is my view wrong? *Should* I be writing my code out longhand rather than using LINQ? Isn't this what LINQ was designed for?
Edit: I was speaking about LINQ to objects, I don't use LINQ to XML so much and I have used LINQ to SQL but I'm not so enamoured with those flavours as LINQ to objects. | I have to agree with your view - if it's more efficient to write and elegant then what's a few milliseconds. Writing extra code gives more room for bugs to creep in and it's extra code that needs to be tested and most of all it's extra code to maintain. Think about the guy who's going to come in behind you and maintain your code - they'll thank you for writing elegant easy to read code long before they thank you for writing code that's a few ms faster!
Beware though, this cost of a few ms could be significant when you take the bigger picture into account. If that few milliseconds is part of a loop of thousands of repetitions, then the milliseconds add up fast. | Yes you can love LINQ too much - [Single Statement LINQ RayTracer](http://tirania.org/blog/archive/2007/Nov-16.html)
Where do you draw the line? I'd say use LINQ as much as it makes the code simpler and easier to read.
The moment the LINQ version becomes more difficult to understand then the non-LINQ version it's time to swap, and vice versa. EDIT: This mainly applies to LINQ-To-Objects as the other LINQ flavours have their own benefits. | Where to draw the line - is it possible to love LINQ too much? | [
"",
"c#",
".net",
"vb.net",
"linq",
""
] |
Good morning, afternoon, evening or night (depending on your timezone).
This is just a general question about XML commenting within C#. I have never been very big into commenting my programs, I've always been more of a verbose variable/property/method namer and letting the code speak for itself. I do write comments if I'm coding something that is fairly confusing, but for the most part I don't write alot of comments.
I was doing some reading about XML comments in .NET, Sandcastle, and the help file builder on codeplex and it has taken me down the path of wanting to document my code and generate some nice, helpful documentation for those who have to dig into my code when I'm no longer here.
My question is about standards and conventions. Is there a guide to "good" XML commenting? Should you comment EVERY variable and property? EVERY method? I'm just basically looking for tips on how to write good comments that will be compiled by sandcastle into good documentation so other programmers don't curse my name when they end up having to work on my code.
Thank you in advance for your advice and suggestions,
Scott Vercuski | Personally, we make sure that every public and protected method has XML comments. It also will provide you with Intellisense, and not just end-user help documentation. In the past, we also have included it on privately scoped declarations, but do not feel it is 100% required, as long as the methods are short and on-point.
Don't forget that there are tools to make you XML commenting tasks easier:
* [GhostDoc](http://www.roland-weigelt.de/ghostdoc/) - Comment inheritance and templating add-in.
* [Sandcastle Help File Builder](http://www.codeplex.com/SHFB) - Edits the Sandcastle projects via a GUI, can be run from a command line (for build automation), and can edit MAML for help topics not derived from code. (The 1.8.0.0 alpha version is very stable and very improved. Have been using it for about a month now, over 1.7.0.0) | Comments are very often outdated. This always has been a problem. My rule of thumb : the more you need to work to update a comment, the faster that comment will be obsolete.
XML Comments are great for API development. They works pretty well with Intellisens and they can have you generate an HTML help document in no time.
But this is not free: maintaining them will be hard (look at any non-trivial example, you will understand what I mean), so they will tend to be outdated very fast. As a result, **reviewing XML Comments should be added to your code review as a mandatory check** and this check should be performed every time a file is updated.
Well, since it is expensive to maintain, since a lot of non private symbols (in non-API development) are used only by 1 or 2 classes, and since these symboles are often self-explanatory, I would never enforce a rule saying that every non-private symbol should be XML commented. **This would be overkill and conterproductive**. What you will get is what I saw at a lot of places : nearly empty XML Comments adding nothing to the symbole name. And code that is just a little less readable...
I think that the **very, very** important guide line about comments in normal (non-API) code should not be about **HOW they should be written** but about **WHAT they should contain**. A lot of developers still don't know **what** to write. A description of what should be commented, with examples, would do better for your code than just a plain : "Do use XML Comments on every non-private symbole.". | XML Commenting tips for C# programming | [
"",
"c#",
"documentation",
"documentation-generation",
"sandcastle",
"xml-comments",
""
] |
i have little problem with boost::asio library. My app receive and process data asynchronously, it create threads and run io\_service.run() on each of them.
```
boost::asio::io_service io;
boost::thread_group thread_pool;
...
int cpu_cnt = get_cpu_count();
for (int i = 0; i < cpu_cnt; ++i)
{
thread_pool.create_thread( boost::bind(&run_service, &io) );
}
void run_service(boost::asio::io_service* io)
{
try
{
io->run();//make fun
}
catch(const std::exception& e)
{ //process error
}
catch(...)
{ //process error
}
}
```
Time after time, my application receives message(across windows messaging system) from some supervisor application that checks is my program alive or not. If my application wont reply, it will be restarted. The tricky part here is to check, that threads is running and not deadlocked. I can post handler to io\_service like this:
```
io.post( &reply_to_supervisor );
```
but this method affects only one thread.
How can i check that all threads is running and not deadlocked? | I may be wrong, but would the use an io\_service per thread solve your problem?
Another idea: post `cpu_cnt` times `reply_to_supervisor` calls that use a little `sleep()` - not nice, but should work | This strikes me as an instance of the [Halting Problem](http://en.wikipedia.org/wiki/Halting_problem), but since you appear to be on Windows, you might want to look at Just Software Solution's [just::thread](http://www.stdthread.co.uk/) library. It is an implementation of the draft C++0x threading library, and has built-in deadlock detection in its own mutexes.
Ultimately though you are probably better off asking this question on the [asio mailing list](http://tenermerx.com/Asio/MailingList). The author of the library is quite helpful, and either he or some other hardcore asio user may be able to provide a better answer there. | How to detect deadlock whith Asio library? | [
"",
"c++",
"boost",
"boost-asio",
""
] |
I'm trying to figure out what the following line does exactly - specifically the %%s part?
```
cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (%%s, %%s)'%sourcedest, (self.tkt.id, n))
```
Any good mini-tutorial about string formatting and inserting variables into strings with Python? | The `%%` becomes a single `%`. This code is essentially doing two levels of string formatting. First the `%sourcedest` is executed to turn your code essentially into:
```
cursor.execute('INSERT INTO mastertickets (BLAH, FOO) VALUES (%s, %s)', (self.tkt.id, n))
```
then the db layer applies the parameters to the slots that are left.
The double-% is needed to get the db's slots passed through the first string formatting operation safely. | "but how should one do it instead?"
Tough call. The issue is that they are plugging in metadata (specifically column names) on the fly into a SQL statement. I'm not a big fan of this kind of thing. The `sourcedest` variable has two column names that are going to be updated.
Odds are good that there is only one (or a few few) pairs of column names that are actually used. My preference is to do this.
```
if situation1:
stmt= "INSERT INTO mastertickets (this, that) VALUES (?, ?)"
elif situation2:
stmt= "INSERT INTO mastertickets (foo, bar) VALUES (?, ?)"
else:
raise Exception( "Bad configuration -- with some explanation" )
cursor.execute( stmt, (self.tkt.id, n) )
```
When there's more than one valid combination of columns for this kind of thing, it indicates that the data model has merged two entities into a single table, which is a common database design problem. Since you're working with a product and a plug-in, there's not much you can do about the data model issues. | Newbie Python question about strings with parameters: "%%s"? | [
"",
"python",
"string",
""
] |
```
@Column(name="DateOfBirth")
private Date dateOfBirth;
```
I specifically need the above code to create a column named "DateOfBirth," instead Hibernate gives me a column named date\_of\_birth. How can I change this? Is there a web.xml property? I came across DefaultNamingStrategy and ImprovedNamingStrategy, but not sure how to specify one or the other. | Here is a possible workaround: if you name it `dateofbirth` the column in the DB would be named like that, but the attribute name should be the same.
Hibernate takes the camel case format to create/read database columns.
I've had this problem before. I worked with a legacy columns where there was no space in the column names "employeename", "employeerole", "departmentlocation". I hate it because all my beans properties had to be without camel case.
Database columns separated by "\_" will be used to properly camelCase as you have just seen. | Try putting this in
application.properties
```
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
``` | hibernate column name issues | [
"",
"java",
"hibernate",
"annotations",
""
] |
All of a sudden I start getting this error while trying to open 2 of some 10+ forms in my Window Forms application in designer.
To prevent possible data loss before loading the designer, the following errors must be resolved:
The key 'UserID' does not exist in the appSettings configuration section.
It used to work fine and I dont' remember doing significant changes to it.
The key, of course, is in the appSettings alright, and always was, and the application builds and executes as expected. Only design view for these 2 forms is unaccessible.
```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Server" value="MYSERVER" />
<add key="DataBase" value="MYDB" />
<add key="UserID" value="MYUSER" />
<add key="PassWord" value="MYPASS" />
</appSettings>
</configuration>
```
One of them is just a Form, the other is a UserControl. None of them inherits from abstract classes or anything like that. Rebuilding or restarting Visual Studio does not help so far.
Any ideas on fixing it? | And finally, here is what the designer REALLY was complaining about:
I had a call to a stored procedure right from the User Control's InitializeComponent().
While it may not be a good idea indeed (separate question material?), I have to say that the error was not presented to me in the best possible way... | Is it possible the config file was moved to a different folder or a new config file was introduced somewhere? | The key 'UserID' does not exist in the appSettings configuration section | [
"",
"c#",
"visual-studio-2008",
""
] |
I'm using a JComboBox with an ItemListener on it. When the value is changed, the itemStateChanged event is called twice. The first call, the ItemEvent is showing the original item selected. On the second time, it is showing the item that has been just selected by the user. Here's some tester code:
```
public Tester(){
JComboBox box = new JComboBox();
box.addItem("One");
box.addItem("Two");
box.addItem("Three");
box.addItem("Four");
box.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
System.out.println(e.getItem());
}
});
JFrame frame = new JFrame();
frame.getContentPane().add(box);
frame.pack();
frame.setVisible(true);
}
```
So when I changed the Combo box once from "One" to "Three" the console shows:
```
One
Three
```
Is there a way I can tell using the ItemEvent maybe, that it's the second item (ie. the user selected item)? And if someone can explain why it gets called twice, that would be nice too!
Thanks | Have a look at this source:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Tester {
public Tester(){
JComboBox box = new JComboBox();
box.addItem("One");
box.addItem("Two");
box.addItem("Three");
box.addItem("Four");
box.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
System.out.println(e.getItem() + " " + e.getStateChange() );
}
});
JFrame frame = new JFrame();
frame.getContentPane().add(box);
frame.pack();
frame.setVisible(true);
}
public static void main(String [] args) {
Tester tester = new Tester();
}
}
```
Use the getStateChange to determine if an item is selected or deselected | According to this [thread](http://forums.sun.com/thread.jspa?threadID=5262595&tstart=13094),
> It gets tripped when you leave one result and then called again when set to another result
>
> Don't listen for itemStateChanged. Use an ActionListener instead, which is good for handling events of the combo.
> You need a ItemStateListener if you need to separately handle deselection / selection depending on the item involved.
>
> Changing the state of the item within itemStateChanged causes itemStateChanged to be fired... this called "reentrance". | Why is itemStateChanged on JComboBox is called twice when changed? | [
"",
"java",
"swing",
"jcombobox",
"itemlistener",
""
] |
I did see the question about setting the proxy for the JVM but what I want to ask is how one can utilize the proxy that is already configured (on Windows).
Here is a demonstration of my issue:
> > 1. Go to your Control Panel->Java and set a proxy address.
> > 2. Run the following simple applet code (I'm using the Eclipse IDE):
```
import java.awt.Graphics;
import javax.swing.JApplet;
import java.util.*;
public class Stacklet extends JApplet {
private String message;
public void init(){
Properties props = System.getProperties();
message = props.getProperty("http.proxyHost", "NONE");
message = (message.length() == 0)? "NONE": message;
}
public void paint(Graphics g)
{
g.drawString(message, 20, 20);
}
}
```
The Applet displays "NONE" without regard to the settings you've placed in the Java Control Panel. What would be best would be if the Windows proxy settings (usually set in Internet Explorer) were what I could determine but doing an extra configuration step in the Java Control Panel would still be an acceptable solution.
Thanks! | It is possible to detect the proxy using the [ProxySelector](http://java.sun.com/j2se/1.5.0/docs/api/java/net/ProxySelector.html) class and assign the system proxy by assigning environment variables with the [setProperty method of the System class](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#setProperty(java.lang.String,%20java.lang.String)):
```
System.setProperty("java.net.useSystemProxies", "true");
System.out.println("detecting proxies");
List l = null;
try {
l = ProxySelector.getDefault().select(new URI("http://foo/bar"));
}
catch (URISyntaxException e) {
e.printStackTrace();
}
if (l != null) {
for (Iterator iter = l.iterator(); iter.hasNext();) {
java.net.Proxy proxy = (java.net.Proxy) iter.next();
System.out.println("proxy type: " + proxy.type());
InetSocketAddress addr = (InetSocketAddress) proxy.address();
if (addr == null) {
System.out.println("No Proxy");
} else {
System.out.println("proxy hostname: " + addr.getHostName());
System.setProperty("http.proxyHost", addr.getHostName());
System.out.println("proxy port: " + addr.getPort());
System.setProperty("http.proxyPort", Integer.toString(addr.getPort()));
}
}
}
``` | This might be a little late, but I ran into the same problem. The way I fixed it is by adding the following system property:
```
-Djava.net.useSystemProxies=true
```
Now, note that this property is set only once at startup, so it can't change when you run your application. From <https://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html#Proxies>:
> java.net.useSystemProxies (default: false) ... Note that this property
> is checked only once at startup. | Setting JVM/JRE to use Windows Proxy Automatically | [
"",
"java",
"proxy",
"jvm",
""
] |
```
include 'header.php';
// ... some code
header('Location:index.php');
exit;
```
The above code keeps giving me an issue with the redirect. The error is the following:
> Warning: Cannot modify header information - headers already sent by (output
> started at /Applications/MAMP/htdocs/testygubbins/OO/test/header.php:15) in
> /Applications/MAMP/htdocs/testygubbins/OO/test/form.php on line 16.
What should I be doing to make it work?
header.php code:
```
<?php
include 'class.user.php';
include 'class.Connection.php';
$date = date('Y-m-j');
?>
<html>
<head>
<link rel=StyleSheet href="css/style.css" type="text/css" media=screen>
<title>Test</title>
</head>
<body>
<div id="page">
``` | Look carefully at your includes - perhaps you have a blank line after a closing ?> ?
This will cause some literal whitespace to be sent as output, preventing you from making subsequent header calls.
Note that it is legal to leave the close ?> off the include file, which is a useful idiom for avoiding this problem.
*(EDIT: looking at your header, you need to avoid doing any HTML output if you want to output headers, or use output buffering to capture it).*
Finally, as the [PHP manual page for header](http://php.net/header) points out, you should really use full URLs to redirect:
> Note: HTTP/1.1 requires an absolute
> URI as argument to *Location:*
> including the scheme, hostname and
> absolute path, but some clients accept
> relative URIs. You can usually use
> $\_SERVER['HTTP\_HOST'],
> $\_SERVER['PHP\_SELF'] and dirname() to
> make an absolute URI from a relative
> one yourself: | Alternatively, not to think about a newline or space somewhere in the file, you can buffer the output. Basically, you call `ob_start()` at the very beginning of the file and `ob_end_flush()` at the end. You can find more details at [php.net ob-start function description](http://uk.php.net/ob-start).
**Edit:**
If you use buffering, you can output HTML before and after header() function - buffering will then ignore the output and return only the redirection header. | PHP Header location redirect is not working | [
"",
"php",
"http-headers",
""
] |
I'm attempting to use Assembly.GetType("MyCompany.Class1.Class2") to dynamically get a type from a string.
```
Assembly.GetType("MyCompany.Class1");
```
works as expected.
If I embed a class within another class such as:
```
namespace MyCompany
{
public class Class1
{
//.....
public class Class2
{
//.....
}
}
}
```
and try to get the type Class2
```
Assembly.GetType("MyCompany.Class1.Class2")
```
will return a null.
I'm using the .NET Frameworks 3.5 SP1
Does anyone know what I'm doing incorrectly and what I can do to fix this?
Thanks in advance
Kevin D. Wolf
Tampa, FL | You need the Plus sign to get Nested Classes to be mapped using Assembly.GeType.
```
Assembly.GetType("MyCompany.Class1+Class2");
``` | I think it's named MyComnpany.Class1+Class2.
If I run this code on a similar structure, that's what I see:
```
Assembly assem = Assembly.GetExecutingAssembly();
Type[] types = assem.GetTypes();
```
example Types to see the names. | Using Assembly.GetType("MyCompany.Class1.Class2") returns null | [
"",
"c#",
".net",
""
] |
I would like to set some vim options in one file in the comments section.
For example, I would like to set this option in one file
```
set syntax=python
```
The file does not have a .py extension and I am not interested in making my vim installation recognise all files with this extension as python files.
I know this can be done because I have seen it, but my googling for this has not yet been fruitful. | You're wanting a [modeline](http://vim.wikia.com/wiki/Modeline_magic) syntax, e.g.
```
# vim: set syntax=python:
```
See: [Modeline magic](http://vim.wikia.com/wiki/Modeline_magic) at Vim Wikia for more details. | I haven't used vim much, but I think what you want is to add a line like the following to the end of your file:
```
# vim: set syntax=python:
``` | How do you override vim options via comments in a python source code file? | [
"",
"python",
"vim",
""
] |
Is there any thing in PHP to create basic scaffold, like in Rails?
EDIT: I need something to prototype quickly.. | Some frameworks like [Symfony](http://www.symfony-project.org/book/1_0/14-Generators), [CakePHP](http://book.cakephp.org/view/105/Scaffolding), [Akelos](http://www.akelos.org/), [CodeIgniter](http://codeigniter.com/user_guide/general/scaffolding.html) and others have support for scaffolding.
However if you don't want to use a framework you can try [phpScaffold](https://github.com/tute/phpscaffold) which generates CRUD scaffold pages based on phpMyAdmin table exports... | I also wanted some fast prototyping, but I wanted it to generate the code, so it's easy to update it. I made many improvements on **phpScaffold** (HTML5, nice CSS, many models at once, etc) which are published on <http://github.com/tute/phpscaffold>. | Scaffolding for PHP | [
"",
"php",
"ruby-on-rails",
"scaffolding",
""
] |
I used to have a Tests folders in my main project where a unit test had this line of code:
```
Foo foo = new Foo(Environment.CurrentDirectory + @"\XML\FooData.xml" );
```
I have an XML directory in the Foo project that has a FooData.xml
In the post build event of my projects i have the following line
copy "$(ProjectDir)Foo\Currencies.xml" "$(TargetDir)\XML"
I now have broke all unit tests into another projects to separate them out and i now get the following error when running these unit tests.
***Could not find a part of the path 'C:\svncheckout\Foo.Tests\bin\Debug\XML\FooData.xml'*** | Rather than having a post-build step, can you not just make it a "content" item in Visual Studio, telling it to copy it to the target directory? I usually either do that, or make it an embedded resource and use streams and Assembly.GetManifestResourceStream. | I believe you need to update the post build event for the Foo.Tests project to be:
"$(ProjectDir)Foo.Test\Currencies.xml" "$(TargetDir)\XML" | Breaking out unit tests into another project | [
"",
"c#",
"unit-testing",
""
] |
So I'm trying to get rid of my std::vector's by using boost::ptr\_vector. Now I'm trying to remove an element from one, and have the removed element deleted as well. The most obvious thing to me was to do:
```
class A
{ int m; };
boost::ptr_vector<A> vec;
A* a = new A;
vec.push_back(a);
vec.erase(a);
```
But this won't even compile (see below for the full error message). I've tried the erase/remove idiom like I would on a std::vector but all the algorithms of boost::ptr\_vector turn out to be slightly different from those in std::vector.
So my questions:
* How do I remove a pointer from a ptr\_vector?
* Do I still need to manually delete() that element that I removed?
Compiler error:
```
1>------ Build started: Project: ptr_vector_test, Configuration: Debug Win32 ------
1>Compiling...
1>ptr_vector_test.cpp
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : error C2825: 'C': must be a class or namespace when followed by '::'
1> c:\users\rvanhout\svn\trunk\thirdparty\boost\mpl\eval_if.hpp(63) : see reference to class template instantiation 'boost::range_const_iterator<C>' being compiled
1> with
1> [
1> C=A *
1> ]
1> c:\users\rvanhout\svn\trunk\thirdparty\boost\range\iterator.hpp(63) : see reference to class template instantiation 'boost::mpl::eval_if_c<C,F1,F2>' being compiled
1> with
1> [
1> C=true,
1> F1=boost::range_const_iterator<A *>,
1> F2=boost::range_mutable_iterator<A *const >
1> ]
1> c:\users\rvanhout\svn\trunk\thirdparty\boost\ptr_container\detail\reversible_ptr_container.hpp(506) : see reference to class template instantiation 'boost::range_iterator<C>' being compiled
1> with
1> [
1> C=A *const
1> ]
1> c:\tmp\ptr_vector_test\ptr_vector_test.cpp(21) : see reference to function template instantiation 'boost::void_ptr_iterator<VoidIter,T> boost::ptr_container_detail::reversible_ptr_container<Config,CloneAllocator>::erase<A*>(const Range &)' being compiled
1> with
1> [
1> VoidIter=std::_Vector_iterator<void *,std::allocator<void *>>,
1> T=A,
1> Config=boost::ptr_container_detail::sequence_config<A,std::vector<void *,std::allocator<void *>>>,
1> CloneAllocator=boost::heap_clone_allocator,
1> Range=A *
1> ]
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : error C2039: 'const_iterator' : is not a member of '`global namespace''
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : error C2146: syntax error : missing ';' before identifier 'type'
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : error C2208: 'boost::type' : no members defined using this type
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : fatal error C1903: unable to recover from previous error(s); stopping compilation
1>Build log was saved at "file://c:\tmp\ptr_vector_test\Debug\BuildLog.htm"
1>ptr_vector_test - 5 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
``` | Well you can do that with a std::vector either.
In both cases erase takes an iterator as a parameter.
So before you can erase something from a vector (or a ptr\_vector) you need to locate it.
Also note that the ptr\_vector treats its content as if you have stored an object not a pointer. So any searching is done via the object.
So basically
```
std::vector<A> x;
std::ptr_vector<A> y;
// These two object should behave in exactly the same way.
// The ONLY difference is inserting values which for y are pointers.
// Y take ownership of the pointer and all subsequent acesses to the
// members of y look like they are objects
```
Example:
```
#include <boost/ptr_container/ptr_vector.hpp>
#include <vector>
class A
{ int m;
public:
A(int x):m(x) {}
bool operator==(A const& rhs) {return m = rhs.m;}
};
int main()
{
boost::ptr_vector<A> x;
x.push_back(new A(1));
x.erase(std::find(x.begin(),x.end(),A(1)));
std::vector<A> y;
y.push_back(A(2));
y.erase(std::find(y.begin(),y.end(),A(2)));
// To find an exact pointer don't modify the equality.
// Use find_if and pass a predicate that tests for a pointer
A* a = new A(3);
boost:ptr_Vector<A> z;
z.push_back(a);
z.erase(std::find_if(y.begin(),y.end(),CheckPointerValue(a));
}
struct CheckPointerValue
{
CheckPointerValue(A* a):anA(a) {}
bool operator()(A const& x) { return &X == anA;}
private:
A* anA;
};
``` | I think you want to call .release() on the vector instead of erase. That removes the entry and deletes the memory.
See the section "New Functions" for details in [the tutorial](http://www.boost.org/doc/libs/1_37_0/libs/ptr_container/doc/tutorial.html), or check [the reference](http://www.boost.org/doc/libs/1_37_0/libs/ptr_container/doc/ptr_sequence_adapter.html).
Alternatively, you need to get an iterator to an element in order to call erase(), I'm ot sure an A\* counts in terms of a ptr\_vector. | How to erase elements from boost::ptr_vector | [
"",
"c++",
"boost",
"ptr-vector",
""
] |
Recently I [asked](https://stackoverflow.com/questions/267628/scripting-fruityloops-or-propellerheads-reason-from-vb-or-python) about scripting FruityLoops or Reason from Python, which didn't turn up much.
Today I found [LMMS](http://lmms.sourceforge.net/), a free-software FruityLoops clone. So, similarly. Has anyone tried scripting this from Python (or similar)? Is there an API or wrapper for accessing its resources from outside?
If not, what would be the right approach to try writing one? | It seems you can [write plugins](http://lmms.sourceforge.net/wiki/index.php?title=Plugin_development_tutorial) for LMMS using C++. By [embedding Python in the C++ plugin](http://www.python.org/doc/2.5.2/ext/embedding.html) you can effectively script the program in Python. | Look at <http://www.csounds.com/> for an approach to scripting music synth programs in Python. | Scripting LMMS from Python | [
"",
"python",
"audio-player",
"lmms",
""
] |
Is it possible to do a HTTP Head request solely using an XMLHTTPRequest in JavaScript?
My motivation is to conserve bandwidth.
If not, is it possible to fake it? | Easy, just use the HEAD method, instead of GET or POST:
```
function UrlExists(url, callback)
{
var http = new XMLHttpRequest();
http.open('HEAD', url);
http.onreadystatechange = function() {
if (this.readyState == this.DONE) {
callback(this.status != 404);
}
};
http.send();
}
```
This is just a short example to show how to use the HEAD method. Production code may need more fine-grained callbacks for different result states (success, failure, timeout), and may use different [event handlers](http://www.w3.org/TR/XMLHttpRequest2/#event-handlers) (`onload`, `onerror` and `ontimeout` rather than `onreadystatechange`). | The more modern approach is to use the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) which replaced `XMLHttpRequest`.
e.g. (within an `async` function)
```
const url = "https://example.com";
const response = await fetch(url, { method: "HEAD" });
console.log(`Got status: ${response.status}`);
``` | HTTP HEAD Request in Javascript/Ajax? | [
"",
"javascript",
"ajax",
"http-headers",
"xmlhttprequest",
""
] |
I'm running a Django application. Had it under Apache + mod\_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings.
Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0.
Any ideas where to look for?
PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query.
```
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root
if not self.has_permission(request):
File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission
return request.user.is_authenticated() and request.user.is_staff
File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__
request._cached_user = get_user(request)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user
user_id = request.session[SESSION_KEY]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__
return self._session[key]
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session
self._session_cache = self.load()
File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load
expire_date__gt=datetime.datetime.now()
File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator
for row in self.query.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql
cursor.execute(sql, params)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
``` | In the end I switched back to Apache + mod\_python (I was having other random errors with fcgi, besides this one) and everything is good and stable now.
The question still remains open. In case anybody has this problem in the future and solves it they can record the solution here for future reference. :) | Possible solution: <http://groups.google.com/group/django-users/browse_thread/thread/2c7421cdb9b99e48>
> Until recently I was curious to test
> this on Django 1.1.1. Will this
> exception be thrown again... surprise,
> there it was again. It took me some
> time to debug this, helpful hint was
> that it only shows when (pre)forking.
> So for those who getting randomly
> those exceptions, I can say... fix
> your code :) Ok.. seriously, there
> are always few ways of doing this, so
> let me firs explain where is a
> problem first. If you access database
> when any of your modules will import
> as, e.g. reading configuration from
> database then you will get this error.
> When your fastcgi-prefork application
> starts, first it imports all modules,
> and only after this forks children.
> If you have established db connection
> during import all children processes
> will have an exact copy of that
> object. This connection is being
> closed at the end of request phase
> (request\_finished signal). So first
> child which will be called to process
> your request, will close this
> connection. But what will happen to
> the rest of the child processes? They
> will believe that they have open and
> presumably working connection to the
> db, so any db operation will cause an
> exception. Why this is not showing in
> threaded execution model? I suppose
> because threads are using same object
> and know when any other thread is
> closing connection. How to fix this?
> Best way is to fix your code... but
> this can be difficult sometimes.
> Other option, in my opinion quite
> clean, is to write somewhere in your
> application small piece of code:
```
from django.db import connection
from django.core import signals
def close_connection(**kwargs):
connection.close()
signals.request_started.connect(close_connection)
```
Not ideal thought, connecting twice to the DB is a workaround at best.
---
Possible solution: using connection pooling (pgpool, pgbouncer), so you have DB connections pooled and stable, and handed fast to your FCGI daemons.
The problem is that this triggers another bug, psycopg2 raising an *InterfaceError* because it's trying to disconnect twice (pgbouncer already handled this).
Now the culprit is Django signal *request\_finished* triggering *connection.close()*, and failing loud even if it was already disconnected. I don't think this behavior is desired, as if the request already finished, we don't care about the DB connection anymore. A patch for correcting this should be simple.
The relevant traceback:
```
/usr/local/lib/python2.6/dist-packages/Django-1.1.1-py2.6.egg/django/core/handlers/wsgi.py in __call__(self=<django.core.handlers.wsgi.WSGIHandler object at 0x24fb210>, environ={'AUTH_TYPE': 'Basic', 'DOCUMENT_ROOT': '/storage/test', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTPS': 'off', 'HTTP_ACCEPT': 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_AUTHORIZATION': 'Basic dGVzdGU6c3VjZXNzbw==', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_COOKIE': '__utma=175602209.1371964931.1269354495.126938948...none); sessionid=a1990f0d8d32c78a285489586c510e8c', 'HTTP_HOST': 'www.rede-colibri.com', ...}, start_response=<function start_response at 0x24f87d0>)
246 response = self.apply_response_fixes(request, response)
247 finally:
248 signals.request_finished.send(sender=self.__class__)
249
250 try:
global signals = <module 'django.core.signals' from '/usr/local/l.../Django-1.1.1-py2.6.egg/django/core/signals.pyc'>, signals.request_finished = <django.dispatch.dispatcher.Signal object at 0x1975710>, signals.request_finished.send = <bound method Signal.send of <django.dispatch.dispatcher.Signal object at 0x1975710>>, sender undefined, self = <django.core.handlers.wsgi.WSGIHandler object at 0x24fb210>, self.__class__ = <class 'django.core.handlers.wsgi.WSGIHandler'>
/usr/local/lib/python2.6/dist-packages/Django-1.1.1-py2.6.egg/django/dispatch/dispatcher.py in send(self=<django.dispatch.dispatcher.Signal object at 0x1975710>, sender=<class 'django.core.handlers.wsgi.WSGIHandler'>, **named={})
164
165 for receiver in self._live_receivers(_make_id(sender)):
166 response = receiver(signal=self, sender=sender, **named)
167 responses.append((receiver, response))
168 return responses
response undefined, receiver = <function close_connection at 0x197b050>, signal undefined, self = <django.dispatch.dispatcher.Signal object at 0x1975710>, sender = <class 'django.core.handlers.wsgi.WSGIHandler'>, named = {}
/usr/local/lib/python2.6/dist-packages/Django-1.1.1-py2.6.egg/django/db/__init__.py in close_connection(**kwargs={'sender': <class 'django.core.handlers.wsgi.WSGIHandler'>, 'signal': <django.dispatch.dispatcher.Signal object at 0x1975710>})
63 # when a Django request is finished.
64 def close_connection(**kwargs):
65 connection.close()
66 signals.request_finished.connect(close_connection)
67
global connection = <django.db.backends.postgresql_psycopg2.base.DatabaseWrapper object at 0x17b14c8>, connection.close = <bound method DatabaseWrapper.close of <django.d...ycopg2.base.DatabaseWrapper object at 0x17b14c8>>
/usr/local/lib/python2.6/dist-packages/Django-1.1.1-py2.6.egg/django/db/backends/__init__.py in close(self=<django.db.backends.postgresql_psycopg2.base.DatabaseWrapper object at 0x17b14c8>)
74 def close(self):
75 if self.connection is not None:
76 self.connection.close()
77 self.connection = None
78
self = <django.db.backends.postgresql_psycopg2.base.DatabaseWrapper object at 0x17b14c8>, self.connection = <connection object at 0x1f80870; dsn: 'dbname=co...st=127.0.0.1 port=6432 user=postgres', closed: 2>, self.connection.close = <built-in method close of psycopg2._psycopg.connection object at 0x1f80870>
```
Exception handling here could add more leniency:
**/usr/local/lib/python2.6/dist-packages/Django-1.1.1-py2.6.egg/django/db/\_\_init\_\_.py**
```
63 # when a Django request is finished.
64 def close_connection(**kwargs):
65 connection.close()
66 signals.request_finished.connect(close_connection)
```
Or it could be handled better on psycopg2, so to not throw fatal errors if all we're trying to do is disconnect and it already is:
**/usr/local/lib/python2.6/dist-packages/Django-1.1.1-py2.6.egg/django/db/backends/\_\_init\_\_.py**
```
74 def close(self):
75 if self.connection is not None:
76 self.connection.close()
77 self.connection = None
```
Other than that, I'm short on ideas. | Django + FastCGI - randomly raising OperationalError | [
"",
"python",
"django",
"exception",
"fastcgi",
"lighttpd",
""
] |
MySQL column > sdate, edate ( its 2 column).
sdate is start date for project starting and edate is end date for project ending.
so i need to make search between them..
```
<strong>Search</strong><br />
<form method="post" action="search.php">
Start Report Date : <input type="text" name="sdate" />
End Report Date : <input type="text" name="edate" />
<input type="submit" name="Submit" value="Search" />
</form>
This is example data in mysql
sdate Project Name edate
22 December 2008 project 1 23 December 2008
25 December 2008 project 2 26 December 2008
24 December 2008 project 3 27 December 2008
1 January 2008 project 4 20 January 2008
10 December 2008 project 5 12 December 2008
```
so let say a user entered sdate ( eg, 22 December 2008 ) and edate ( eg, 30 December 2008 ).
It should display
```
22 December 2008 project 1 23 December 2008
25 December 2008 project 2 26 December 2008
24 December 2008 project 3 27 December 2008
```
So i need a php code sql query which should display entries lies between those 2 dates..
Please help me..
Thanks very much.. | assuming that your `sdate` and `edate` are of MySQL columns type `DATE` you could do the following:
```
SELECT
Project_Name
, sdate
, edate
FROM your_table
WHERE
sdate <= '2008-12-26'
AND
edate >= '2008-12-26'
```
or you could use DATEDIFF
```
SELECT
Project_Name
, sdate
, edate
FROM your_table
WHERE
DATEDIFF(sdate, '2008-12-26') <= 0
AND
DATEDIFF(edate, '2008-12-26') >= 0
```
The first one is more efficient because MySQL can compare all the rows in your table to a static value. For the second solution it needs to calculate the difference for every row in your table.
If your `sdate` and `edate` columns are not DATE columns, you are out of luck and need to change them first. | It seems like a simple select query with a "where" clause can do the trick.
Peuso-code:
```
select sdate, name, edate
from your_table
where sdate >= '22 December 2008' and edate <= '30 December 2008'
``` | 2 Column Mysql Date Range Search in PHP | [
"",
"php",
"mysql",
"search",
"date",
"range",
""
] |
I Have following code:
Controller:
```
public ActionResult Step1()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Step1(FormCollection form)
{
TempData["messageStatus"] = new Random().Next(1, 1000);
return RedirectToAction("Step1");
}
```
View:
```
<%=TempData["messageStatus"]%>
```
in first time in view im getting **12345** for example, but when i request second time of course i must get something else instead **12345** for example **54321** but not, im getting same result **12345**, how can u explain it? **RedirectToAction** cache pages?
where does it mean i must put Guid in my urls for resolving problems with cache? what do u think about this issue? | I'm guessing you're running into caching problems. It's not a problem with redirect to action. All RedirectToAction does is issues a redirect response to your browser telling it to request Step01. Then your browser makes a request for Step01.
In that case, your browser might have Step01 cached. So you need to add a Response header in STep01 indicating it should never be cached. You can do this like so:
```
[OutputCache(Location = OutputCacheLocation.None)]
public ActionResult Step1()
{
return View();
}
```
Or you can add a random querystring to the redirect to action call by passing in an arbitrary value. | Don't new up a new Random object every time. Use the same one. Remember, the .Net Random is only a Pseudo random number generator. | RedirectToAction Bug? | [
"",
"c#",
"asp.net-mvc",
"beta",
""
] |
I do my php work on my dev box at home, where I've got a rudimentary LAMP setup. When I look at my website on my home box, any numbers I echo are automatically truncated to the least required precision. Eg 2 is echoed as 2, 2.2000 is echoed as 2.2.
On the production box, all the numbers are echoed with at least one unnecessary zero, eg 100 becomes 100.0. On both boxes, the PHP version is 5.2.5. Does anyone know offhand if there is a setting I can change which will force PHP to automatically remove any unnecessary zeroes? I don't want to have to go to every place in my code where I output a number and replace echo with printf or something like that.
Muchas gracias. | And when you can't rely on the PHP configuration, don't forget about [number\_format()](http://us.php.net/manual/en/function.number-format.php) which you can use to define how a number is returned, ex:
```
// displays 3.14 as 3 and 4.00 as 4
print number_format($price, 0);
// display 4 as 4.00 and 1234.56 as 1,234.56 aka money style
print number_format($int, 2, ".", ",");
```
PS: and try to avoid using money\_format(), as it won't work on Windows and some other boxes | A quick look through the available [INI](https://www.php.net/manual/en/ini.php#ini.list) settings makes me thing your [precision](https://www.php.net/manual/en/ini.core.php#ini.precision) values are different? | Default Number of Decimal Places to Output in PHP | [
"",
"php",
"decimal",
"numbers",
""
] |
I've got some blank values in my table, and I can't seem to catch them in an IF statement.
I've tried
`IF @value = ''` and `if @value = NULL` and neither one catches the blank values. Is there any way to test whether or not a varchar is entirely whitespace?
AHA! Turns out I was testing for null wrong. Thanks. | To compare with NULL, use the IS NULL keyword.
```
--Generic example:
SELECT *
FROM MY_TABLE
WHERE SOME_FIELD IS NULL;
--Instead of
SELECT *
FROM MY_TABLE
WHERE SOME_FIELD = NULL;
``` | ```
ltrim(rtrim(isNull(@value,''))) = ''
``` | Testing for whitespace in SQL Server | [
"",
"sql",
"sql-server",
"whitespace",
""
] |
I've got a C# program with values in a config file. What I want is to store ampersands for an url value like...
```
<appSettings>
<add key="myurl" value="http://www.myurl.com?&cid=&sid="/>
</appSettings>
```
But I get errors building my site. The ampersand is not allowed. I've tried various forms of escaping the ampersands to no avail. Anyone know of the correct form to do this? All suggestions are welcome. | Use "`&`" instead of "&". | Have you tried this?
```
<appSettings>
<add key="myurl" value="http://www.myurl.com?&cid=&sid="/>
<appSettings>
``` | How can I add an ampersand for a value in a ASP.net/C# app config file value | [
"",
"c#",
"asp.net",
"web-config",
""
] |
I have a table of time-series data of which I need to find all columns that contain at least one non-null value within a given time period. So far I am using the following query:
```
select max(field1),max(field2),max(field3),...
from series where t_stamp between x and y
```
Afterwards I check each field of the result if it contains a non-null value.
The table has around 70 columns and a time period can contain >100k entries.
I wonder if there if there is a faster way to do this (using only standard sql).
EDIT:
Unfortunately, refactoring the table design is not an option for me. | The EXISTS operation may be faster since it can stop searching as soon as it finds any row that matches the criteria (vs. the MAX which you are using). It depends on your data and how smart your SQL server is. If most of your columns have a high rate of non-null data then this method will find rows quickly and it should run quickly. If your columns are mostly NULL values then your method may be faster. I would give them both a shot and see how they are each optimized and how they run. Also keep in mind that performance may change over time if the distribution of your data changes significantly.
Also, I've only tested this on MS SQL Server. I haven't had to code strict ANSI compatible SQL in over a year, so I'm not sure that this is completely generic.
```
SELECT
CASE WHEN EXISTS (SELECT * FROM Series WHERE t_stamp BETWEEN @x AND @y AND field1 IS NOT NULL) THEN 1 ELSE 0 END AS field1,
CASE WHEN EXISTS (SELECT * FROM Series WHERE t_stamp BETWEEN @x AND @y AND field2 IS NOT NULL) THEN 1 ELSE 0 END AS field2,
...
```
EDIT: Just to clarify, the MAX method might be faster since it could determine those values with a single pass through the data. Theoretically, the method here could as well, and potentially with less than a full pass, but your optimizer may not recognize that all of the subqueries are related, so it might do separate passes for each. That still might be faster, but as I said it depends on your data. | It would be faster with a different table design:
```
create table series (fieldno integer, t_stamp date);
select distinct fieldno from series where t_stamp between x and y;
```
Having a table with 70 "similar" fields is not generally a good idea. | SQL find non-null columns | [
"",
"sql",
""
] |
I'm looking for a sequence of steps to add java code formatting to my blogspot blog.
I'm really looking for a dummies guide - something so simple a cleaner could follow it if they found it on a piece of paper on the floor. | I use [Google prettify](http://code.google.com/p/google-code-prettify/) script (StackOverflow uses it also), here you can find a good guide for using it with blogger:
* [Source code high-light in Blogger](http://sunday-lab.blogspot.com/2007/10/source-code-high-light-in-blogger.html)
You have other alternatives like [SyntaxHighlighter](http://code.google.com/p/syntaxhighlighter/), [here](http://urenjoy.blogspot.com/2008/10/publish-source-code-in-blogger.html) also you can find a guide to use it with blogger (or any other blogging software) | Take a look at Syntax Highlighter, also on google code, Java is one of the many supported languages
<http://code.google.com/p/syntaxhighlighter/>
here is a post from Scott Hanselman on how to install and use: <http://www.hanselman.com/blog/BestCodeSyntaxHighlighterForSnippetsInYourBlog.aspx> | What are the steps I need to take to add nice java code formatting to my blogger/blogspot blog? | [
"",
"java",
"html",
"formatting",
"blogger",
"blogspot",
""
] |
Does anyone know of a Python equivalent for [FMPP](http://fmpp.sourceforge.net/) the text file preprocessor?
Follow up: I am reading the docs and looking at the examples for the suggestions given. Just to expand. My usage of FMPP is to read in a data file (csv) and use multiple templates depending on that data to create multi page reports in html all linked to a main index. | Let me add [Mako](http://makotemplates.org) Fine fast tool (and it even uses ${var} syntax).
Note: Mako, Jinja and Cheetah are *textual* languages (they process and generate text). I'd order them Mako > Jinja > Cheetah (in term of features and readability), but people's preferences vary.
Kid and it's successor [Genshi](http://genshi.edgewall.org/) are HTML/XML aware attribute languages (`<div py:if="variable"> ... </div>` etc ). That's completely different methodology - and tools suitable for HTML or XML only. | Python has lots of templating engines. It depends on your exact needs.
[Jinja2](http://jinja.pocoo.org/2/) is a good one, for example. [Kid](http://www.kid-templating.org/) is another. | Does anyone know of a Python equivalent of FMPP? | [
"",
"python",
"preprocessor",
"template-engine",
"freemarker",
"fmpp",
""
] |
When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used?
I have read its definition below in [this glossary](http://docs.djangoproject.com/en/dev/glossary/):
> **Slug**
> A short label for something, containing only letters, numbers,
> underscores or hyphens. They’re generally used in URLs. For example,
> in a typical blog entry URL:
>
> <https://www.djangoproject.com/weblog/2008/apr/12/spring/> the last bit
> (spring) is the slug. | A "slug" is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. I advise to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually.
An example:
```
<title> The 46 Year Old Virgin </title>
<content> A silly comedy movie </content>
<slug> the-46-year-old-virgin </slug>
```
Now let's pretend that we have a Django model such as:
```
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(max_length=1000)
slug = models.SlugField(max_length=40)
```
How would you reference this object with a URL and with a meaningful name? You could for instance use Article.id so the URL would look like this:
```
www.example.com/article/23
```
Or, you might want to reference the title like this:
```
www.example.com/article/The 46 Year Old Virgin
```
Since spaces aren't valid in URLs, they must be replaced by `%20`, which results in:
```
www.example.com/article/The%2046%20Year%20Old%20Virgin
```
Both attempts are not resulting in very meaningful, easy-to-read URL. This is better:
```
www.example.com/article/the-46-year-old-virgin
```
In this example, `the-46-year-old-virgin` is a slug: it is created from the title by down-casing all letters, and replacing spaces by hyphens `-`.
Also see the URL of this very web page for another example. | If I may provide some historical context :
The term **"slug"** has to do with casting metal—lead, in this case—out of which the press fonts were made. Every paper then had its fonts factory regularly re-melted and recast in fresh molds, since after many prints they became worn out. Apprentices like me started their career there, and went all the way to the top (not anymore).
Typographs had to compose the text of an article in a backward manner with lead characters stacked in a wise. So at printing time the letters would be straight on the paper. All typographs could read the newspaper mirrored as fast as the printed one. Therefore the slugs, (like snails) also the slow stories (the last to be fixed) were many on the bench waiting, solely identified by their fist letters, mostly the whole title generally more readable. Some "hot" news were waiting there on the bench, for possible last minute correction, (Evening paper) before last assembly and definitive printing.
Django emerged from the offices of the Lawrence journal in Kansas. Where probably some printing jargon still lingers. **A-django-enthusiast-&-friendly-old-slug-boy-from-France.** | What is a "slug" in Django? | [
"",
"python",
"django",
"url",
"django-models",
"slug",
""
] |
In C# language when you refer to an array element you can write:
myclass.my\_array['element\_name'] = new Point(1,1);
I think about refering to a element with name element\_name by using dot in place of backets:
myclass.my\_array.element\_name = new Point(1,1);
Do you know any language where exists similar syntax to the example above?
What do you think about this example of refering to a array element? Is this good or is it as bad as my writing in english skills?
Kind regards | You could almost certainly do this in any dynamic language, by handling property/variable access as an indexer if the specified property/variable didn't actually exist. I suspect that many dynamic languages already provide this functionality in some areas.
It's possible that in C# 4 you'll be able to make your objects behave like this if you really want to.
However, I would agree with the implicit judgement in Mohit's question - I see no reason to consider this more generally readable than using the more common indexer syntax, and it will confuse people who are used to indexers looking like indexers.
One area where I *would* quite possibly do something like this would be for an XML API, where a property would indicate "take the first element of the given name":
```
XElement author = doc.Root.Posts.Author;
```
That's quite neat - for the specific cases where it's what you want. Just don't try to apply it too generally... | JavaScript does exactly what you describe. In JavaScript, every object is just a map of property names to values. The bracket operator just returns a property by name (or by value in the case of an integer index). You can refer to named properties by just using a dot, though you can't do that with integer indicies. [This page](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Member_Operators) describes the bracket operator and dot notation in detail. | Programming language where you can refer to a array element by . (dot) | [
"",
"c#",
"arrays",
""
] |
This is a follow-up to my [question from yesterday](https://stackoverflow.com/questions/372695/is-there-a-standard-c-function-object-for-taking-apart-a-stdpair). I have Scott Meyers' warning about write-only code on my mind. I like the idea in principle of using standard algorithms to access the keys or values of a std::map, but the syntax required is a little baroque IMHO. Let's say I want to dump all the keys of a map to a vector. Given following declarations,
```
typedef std::map<int, int> MyMap;
MyMap m;
std::vector<int> v;
```
which code is more maintainable (i.e., potentially less confusing)?
Option #1:
```
std::transform(m.begin(),
m.end(),
std::back_inserter(v),
std::tr1::bind(&MyMap::value_type::first, _1));
```
Option #2:
```
for (MyMap::iterator i = m.begin(); i != m.end(); ++i)
{
v.push_back(i->first);
}
```
Option 1 is more standard library-ish but I have to mentally decompose it to understand what's going on. Option 2 seems easier to read at the expense of a possible small runtime penalty. I'm not hurting for CPU time so I'm leaning toward option 2. Does you guys agree? Is there a third option I should consider?
P.S. Over the course of writing this question I concluded that the best way (for my project) to read the keys of a std::map is to store them off in a side container and iterate over that. The maintainability question still stands though. | Clarity always beats clever. Do what you can read later.
You're not alone in thinking that the standard code is a little obtuse. The next C++ standard will introduce [lambda functions](http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions) so you can write more legible code with the standard algorithms. | The first is just as readable and maintainable as the second -- *if* you know what `bind` does. I've been working with Boost::Bind (essentially identical to `std::tr1::bind`) long enough that I have no trouble with it.
Once TR1 becomes part of the official standard, you can safely assume that any competent C++ programmer will understand it. Until then, it could pose some difficulty, but I always think of the long-term over the short-term. | Is std::map + std::tr1::bind + standard algorithms worthwhile? | [
"",
"c++",
"algorithm",
"stl",
"bind",
""
] |
I don't really get it and it's driving me nuts.
i've these 4 lines:
```
Image img = Image.FromFile("F:\\Pulpit\\soa.bmp");
MemoryStream imageStream = new MemoryStream();
img.Save(imageStream, ImageFormat.Bmp);
byte[] contentBuffer = new byte[imageStream.Length];
imageStream.Read(contentBuffer, 0, contentBuffer.Length);
```
when debugging i can see the bytes values in imageStream. after imageStream.Read i check content of contentBuffer and i see only 255 values.
i can't get why is it happening? there is nothing to do wrong in these few lines!
if anyone could help me it would be greatly appreciated!
thanks,
agnieszka | Try setting imageStream.Position to 0. When you write to the MemoryStream it moves the Position after the bytes you just wrote so if you try to read there's nothing there. | You need to reset the file pointer.
```
imageStream.Seek( 0, SeekOrigin.Begin );
```
Otherwise you're reading from the end of the stream. | MemoryStream.Read doesn't copy bytes to buffer - c# | [
"",
"c#",
"image",
"buffer",
"memorystream",
""
] |
I'm using `urllib2` to read in a page. I need to do a quick regex on the source and pull out a few variables but `urllib2` presents as a file object rather than a string.
I'm new to python so I'm struggling to see how I use a file object to do this. Is there a quick way to convert this into a string? | You can use Python in interactive mode to search for solutions.
if `f` is your object, you can enter `dir(f)` to see all methods and attributes. There's one called `read`. Enter `help(f.read)` and it tells you that `f.read()` is the way to retrieve a string from an file object. | From the doc [file.read()](http://docs.python.org/library/stdtypes.html#file.read) (my emphasis):
> file.read([size])
>
> Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. **The bytes are returned as a string object**. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.
Be aware that a regexp search on a large string object may not be efficient, and consider doing the search line-by-line, using [file.next()](http://docs.python.org/library/stdtypes.html#file.next) (a file object is its own iterator). | Read file object as string in python | [
"",
"python",
"file",
"urllib2",
""
] |
In my company we are thinking of moving from wiki style
intranet to a more bespoke CMS solution. Natural choice
would be Joomla, but we have a specific architecture. There
is a few hundred people who will use the system. System
should be self explainable (easier than wiki).
We use a lot of tools web, applications and integrated
within 3rd party software. The superior element which is a
glue for all of them is API. In example for the intranet
tools we do use Django, but it's used without ORM, kind of
limited to templates and url - every application has an
adequate methods within our API. We do not use the Django
admin interface, because it is hardly dependent on ORM.
Because of that Joomla may be hard to integrate. Every
employee should be able to edit most of the pages,
authentication and privileges have to be managed by our API.
How hard is it to plug Joomla to use a different
authentication process? (extension only - no hacks)
If one knows Django better than Joomla, should Django be
used? | Django isn't a CMS. If you want to build an application then you'd use Django (by the sound of your post you understand that though). If you just want to be able to edit/store content and have permissions for your users - a CMS would be the way to go. I really don't know anything about Joomla though. It should be easy enough to mock up a hack to do whatever authentication you need - even if that's just a POST directly to the server.
Django will take a long time to get up to the point where you're using it for the purposes you mention. The admin interface will need to be used (or you're building a CMS from scratch) - which means creating models to model the content you already own. Then you have to customise each model page, and 'plug in' whatever authentication system you want.
Lot of work. | Perhaps you can check [Django CMS](http://django-cms.org/). | Which software for intranet CMS - Django or Joomla? | [
"",
"python",
"django",
"content-management-system",
"joomla",
""
] |
How do I prevent a form that is posted a second time because of a page reload in a browser from being added to my database again with C# Asp.Net.
Thanks,
Steven | you need some unique value that identifies the form/page - perhaps a generated number in a hidden field - and remember/check that is has been processed | One thing you can do is after your first page is submited, you can do a response.redirect back to the same page (thus killing the SUMBIT if refresh is hit).
EDIT: For Spelling. | Asp.net duplicate form submissions on reload | [
"",
"c#",
"asp.net",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.