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 |
----------------------... | 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... | 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 t... | 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 el... | 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 ... | 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 e... | 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 ... | 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 seq... | 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... | 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/im... | 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 i... | 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 ... | 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... | 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... | [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 w... | 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 w... | 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 ... | 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 ev... | 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 us... | 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)
... | 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... | 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.creat... | 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.h... | 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_... | 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:
... | 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:... | 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 );
}
``... | 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... | 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 wr... | 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.WorkingDi... | 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 t... | 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;
... | **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 i... | 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 ... | 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 ... | 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
```
WebR... | 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 i... | 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 a... | 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... | 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 = (fr... | 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... | 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 po... | 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 =... | 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
{
... | 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; ... | 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
> st... | 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-wi... | 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 ... | 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 ... | 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 'Integ... | `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-u... | 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 decisio... | 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... | 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 ... | 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 ... | 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 suspicio... | 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... | 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... | 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 mo... | 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 eit... | 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 ... | 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 me... | 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... | 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 u... | 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 o... | 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... | 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 ... | 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 [E... | 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 ... | 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:
```
con... | 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 t... | ```
// 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.Appen... | ```
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 knowin... | 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 ca... | 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 re... | 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 i... | 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 li... | 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 (... | 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... | * [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)
* [Priv... | 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, switc... | 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 practic... | 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 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 contro... | 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();
... | 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 ... | 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 res... | 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 ... | 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 th... | > > *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 m... | 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 )
{
UI... | 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.
... | 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 ... | 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 );
s... | 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-... | 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
... | 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'... | 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... | 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-c... | 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 ... | ```
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-char... | 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... | 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 hea... | 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 ... | 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 se... | 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:
`... | 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 interfa... | 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 ex... | 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
... | 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 ne... | 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, Assemb... | 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 ... | 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! Thank... | 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(... | 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" checke... | 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 ... | 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; i... | 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 (... | 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... | 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
> a... | 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 de... | 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 ... | 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 ... | 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>` ... | 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 Me... | 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.";
$... | ```
$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 hundre... | 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 b... | 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.
```
$referringS... | 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 protec... | 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 suc... | **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 concern... | 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... | 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... | 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 impl... | 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 ... | 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 us... | 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... | 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) {
/... | 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 ... | 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... | 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 tim... | 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... | 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-poi... | 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 ti... | 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_thr... | 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 buil... | 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... | "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 ... | 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... | 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 colu... | 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 fi... | 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(){... | 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.addIte... | 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 ... | 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 Ecl... | 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#setProper... | 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/... | 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.p... | 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.
*... | 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 u... | 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
... | 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 th... | 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 ... | 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 "$(Project... | 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 wo... | 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 vi... | 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... | 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 ... | 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.sen... | 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 ... | 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... | 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... | 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
WHER... | 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["message... | 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 Re... | 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 un... | 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,23... | 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 am... | 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 r... | 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 shoul... | 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 [... | 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 crea... | 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 [Gensh... | 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 "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 Yea... | 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 ca... | 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 t... | 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... | 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. [Th... | 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... | 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 algorith... | 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++ program... | 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)... | 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 retur... | 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 ... | 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 ... | 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.