Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Given a sorted vector with a number of values, as in the following example: ``` std::vector<double> f; f.pushback(10); f.pushback(100); f.pushback(1000); f.pushback(10000); ``` I'm looking for the most elegant way to retrieve for any double d the two values that are immediately adjacent to it. For example, given the ...
I'm going to post my own anser, and vote anyone up that helped me to reach it, since this is what I'll use in the end, and you've all helped me reach this conclusion. Comments are welcome. ``` std::pair<value_type, value_type> GetDivisions(const value_type& from) const { if (m_divisions.empty()) throw 0; /...
You can use STL's lower\_bound to get want you want in a few lines of code. lower\_bound uses binary search under the hood, so your runtime is O(log n). ``` double val = 45; double lower, upper; std::vector<double>::iterator it; it = lower_bound(f.begin(), f.end(), val); if (it == f.begin()) upper = *it; // no smaller...
Find nearest points in a vector
[ "", "c++", "stl", "" ]
Can anyone find a constant in the .NET framework that defines the number of days in a week (7)? ``` DateTime.DaysInAWeek // Something like this??? ``` Of course I can define my own, but I'd rather not if it's somewhere in there already. ## Update: I am looking for this because I need to allow the user to select a w...
You could probably use [System.Globalization.DateTimeFormatInfo.CurrentInfo.DayNames](http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.daynames.aspx).Length.
I think it's ok to harcode this one. I don't think it will change any soon. *Edit: I depends where you want to use this constant. Inside the some calendar related algorithm it is obvious what 7 means. On the other hand sometimes named constant make code much more readable.*
System constant for the number of days in a week (7)
[ "", "c#", ".net", "datetime", "date", "" ]
I know very little about JavaScript but despite this I'm trying to cobble something together on my wordpress blog. It's not working, and I don't know how to resolve it, and hey, that's what StackOverflow is for, right? Firstly, the error message is: ``` Error: element.dispatchEvent is not a function Source File: http...
Thanks for the suggestions all. In the end I think Kent's explanation was the closest, which basically amounted to "Prototype is broken". (Sorry if I'm summarizing you incorrectly :) As for the `jQuery.noConflict` option - I already mentioned this in the question. It makes a difference *when* you run this method, and ...
There is a nasty trick many libraries do that I've taken a distinct liking to, and it looks like prototype is one of these. Mootools does this, If I am right, and it involves overloading many of the prototypes on the basic classes, monkey patching them. And likewise, I similarly encountered strange behaviour when moo...
prototype and jQuery peaceful co-existence?
[ "", "javascript", "jquery", "wordpress", "prototypejs", "" ]
I was taking a look at <http://www.zenfolio.com/zf/features.aspx> and I can't figure out how they are doing the accordion style expand and collapse when you click on the orange links. I have been using the Web Developer Toolbar add-on for firefox, but I have not been able to find anything in the source of the page like...
They're setting the .display CSS property on an internal DIV from 'none' to '', which renders it. It's a bit tricky, as the JS seems to be in here that's doing it: <http://www.zenfolio.com/zf/script/en-US/mozilla5/windows/5AN2EHZJSZSGS/sitehome.js> But that's basically how everyone does this. It's in there, somewher...
It is being done with JavaScript. When you click a link, the parent td's class changes from 'desc' to 'desc open'. Basically, the expanded text is always there but hidden (display: none;). When it gets the css class of 'open' the text is no longer being hidden (display: block;). If you look in the sitehome.js and sit...
How are they doing the accordion style dropdown on the following website?
[ "", "javascript", "css", "" ]
(Let me give you some context) I am currently designing an application that is supposed to generate a printable A4 page based on some data. Naturally, the device independent pixels of WPF (96 pixels/inch) are not a very natural unit of measurement in the paper world. Something like millimetres would be more appropriate...
For the outlined requirements you do not need to do anything special at all, just go ahead and use centimeters as unit of measurement for the WPF elements themselves (i.e. without any transform) - the very nature of WPF device independence allows you to to the following: ``` <Window x:Class="WpfApplication1.Window1" ...
You can also set sizes in points (FontSize="10pt"), in inches (FontSize="10in") or in centimeters (FontSize="10cm"). Of course the real size depends on the DPI setting of Windows and the DPI of your monitor or printer in this case.
How to use a different coordinate system in WPF? (scaling only)
[ "", "c#", "wpf", "font-size", "dpi", "" ]
The following code generates warning C4250. My question is, what's the best solution to it? ``` class A { virtual void func1(); } class B : public A { } class C : public A { virtual void func1(); } class D : public B, public C { } int main() { D d; d.func1(); // Causes warning } ``` According to what I've...
I had the same warning for the following code: ``` class Interface { public: virtual void A() = 0; }; class Implementation : public virtual Interface { public: virtual void A() {}; }; class ExtendedInterface : public virtual Interface { virtual void B() = 0; }; class ExtendedImplementation : public Exte...
Did you try to inherit public virtual from class A? I think it should solve it. ``` class B :public virtual A; class C :public virtual A; class D : public virtual B, public virtual C; ``` The virtual inheritance suppose to solve the ambiguity.
Visual Studio Compiler warning C4250 ('class1' : inherits 'class2::member' via dominance)
[ "", "c++", "visual-studio-2008", "warnings", "multiple-inheritance", "" ]
I am asp.net-MVC using the BeginForm syntax in my source ciew page and I was told if you want the form to submit you have to have the submit Button at the end of the using statement. I don't want to use a Button to call the desired Action I have an Actionlink set up like so: ``` <%=Html.ActionLink("" + CreateMore, "...
I would once again turn to jQuery to handle this task ``` $(function(){ $('input:submit').hide(); //hide the submit button $('#submitLinkID').click(function(){ // bind the link's click event $('input:submit').click(); //click the hidden button return false; //return false to stop the link from doing anyth...
What is the question? style="display:none;" would hide the button. You aren't indicating where you are running into a problem.
Hide Submit Button for form
[ "", "c#", "asp.net-mvc", "forms", "" ]
Is there a way to test code coverage within visual studio if I'm using MSTest? Or do I have to buy NCover? Is the NCover Enterprise worth the money or are the old betas good enough if Microsoft doesn't provide built in tools to do code coverage? EDIT: Description of VS Products and which ones include code coverage <h...
Yes, you can find code coverage information from within Visual Studio, provided that you have a version of Visual Studio that provides that functionality, such as the Team System. When setting up the unit tests in VS.NET, a localtestrun.testrunconfig file will be created and added as part of the solution. Double-click ...
MSTest includes code coverage, at least it does in the version of VS I have. However, you need to enable the instrumentation in the testrunconfig, which is just ugly and a major PITA. A much easier option is to use [TestDriven.NET](http://testdriven.net/), which can automate coverage, even for MSTest. And since it use...
MSTest Code Coverage
[ "", "c#", ".net", "testing", "tdd", "code-coverage", "" ]
It is my understanding that the `java.regex` package does not have support for named groups (<http://www.regular-expressions.info/named.html>) so can anyone point me towards a third-party library that does? I've looked at [jregex](http://jregex.sourceforge.net/) but its last release was in 2002 and it didn't work for ...
(**Update**: **August 2011**) As [geofflane](https://stackoverflow.com/users/50260/geofflane) mentions in [his answer](https://stackoverflow.com/questions/415580/regex-named-groups-in-java/7033467#7033467), [Java 7 now support named groups](http://download.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#grou...
For people coming to this late: Java 7 adds named groups. [Matcher.group(String groupName) documentation.](http://download.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group%28java.lang.String%29)
Regex Named Groups in Java
[ "", "java", "regex", "" ]
I'm coding some c# against Active Directory and have tried endlessly to get this to work to no avail. The following code works and the code that follows it does not: The code below is using "WinNT://" + Environment.MachineName + ",Computer" to make the connection and works fine. ``` DirectoryEntry localMachine = n...
When connecting to AD using the .NET Framework, you can use "serverless" binding or you can specify a server to use everytime (server bound). Here's an example of using both: ``` // serverless DirectoryEntry rootConfig = new DirectoryEntry("LDAP://dc=domainname,dc=com"); // server bound DirectoryEntry rootEntry = ne...
Yes- RootDSE is not a container - but it holds a number of interesting properties which you can query for - e.g. the name of your domain controller(s). You can check these out by using code like this: ``` DirectoryEntry deRoot = new DirectoryEntry("LDAP://RootDSE"); if (deRoot != null) { Console.WriteLine("Default...
c# against Active Directory over LDAP
[ "", "c#", "active-directory", "ldap", "" ]
Can I control the order static objects are being destructed? Is there any way to enforce my desired order? For example to specify in some way that I would like a certain object to be destroyed last, or at least after another static object?
The static objects are destructed in the reverse order of construction. And the order of construction is very hard to control. The only thing you can be sure of is that two objects defined in the same compilation unit will be constructed in the order of definition. Anything else is more or less random.
The other answers to this insist that it can't be done. And they're right, according to the spec -- but there *is* a trick that will let you do it. Create only a *single* static variable, of a class or struct that contains all the other things you would normally make static variables, like so: ``` class StaticVariabl...
Destruction order of static objects in C++
[ "", "c++", "static", "destruction", "" ]
If I have a table that (among other columns) has two DATETIME columns, how would I select the **most recent** date from those two columns. Example: ``` ID Date1 Date2 1 1/1/2008 2/1/2008 2 2/1/2008 1/1/2008 3 1/10/2008 1/10/2008 ``` If I wanted my results to look like ``` ID MostR...
CASE is IMHO your best option: ``` SELECT ID, CASE WHEN Date1 > Date2 THEN Date1 ELSE Date2 END AS MostRecentDate FROM Table ``` --- If one of the columns is nullable just need to enclose in [`COALESCE`](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/coalesce-transact-sql): ...
From **SQL Server 2012** on, it's possible to use the shortcut [`IIF`](https://learn.microsoft.com/en-us/sql/t-sql/functions/logical-functions-iif-transact-sql) to `CASE` expression though the latter is SQL Standard: ``` SELECT ID, IIF(DateColA > DateColB, DateColA, DateColB) AS MostRecentDate FROM theTable `...
Selecting most recent date between two columns
[ "", "sql", "database", "sql-server-2005", "" ]
I have a file that I can get to with the UNC \mypath\myfile. I retrieve the path with c# and assign it to a link. The browser opens the file inside itself (ie display in the browser) without problem. But, when I try and save to \mypath\myfile I am prompted to save it locally. If I view the file outside of the browser (...
When you open a file via a web browser the web browser downloads the file locally, then sends a local file path to the application that opens it. Even in the case you are using a UNC in your href Adobe does not get that UNC path to save back to, it is getting a local machine path. Keep in mind the browser does the same...
Saving a PDF in your browser (through File-Save As in IE etc) or Save A Copy in the Adobe system will always prompt you to save it locally. You could navigate manually to your UNC path, but this is browser behaviour, not server behaviour.
Is there any way to make a PDF savable from inside the browser?
[ "", "c#", "pdf", "" ]
I was wonder if there is a simpler (single) way to calculate the remaining space in a circular buffer than this? ``` int remaining = (end > start) ? end-start : bufferSize - start + end; ```
If you're worried about poorly-predicted conditionals slowing down your CPU's pipeline, you could use this: ``` int remaining = (end - start) + (-((int) (end <= start)) & bufferSize); ``` But that's likely to be premature optimisation (unless you have really identified this as a hotspot). Stick with your current tech...
Hmmm.... ``` int remaining = (end - start + bufferSize) % bufferSize; ``` 13 tokens, do I win?
Simplified algorithm for calculating remaining space in a circular buffer?
[ "", "c++", "circular-buffer", "" ]
I'm a beginner (self-learning) programmer learning C++, and recently I decided to implement a binary-coded decimal (BCD) class as an exercise, and so I could handle very large numbers on [Project Euler](http://www.projecteuler.net). I'd like to do it as basically as possible, starting properly from scratch. I started ...
Just one note, using an array of `bitset<4>`'s is going to require the same amount of space as an array of long's. bitset is usually implemented by having an array of word sized integers be the backing store for the bits, so that bitwise operations can use bitwise word operations, not byte ones, so more gets done at a ...
> Is using a library class like this overkill as well? I would benchmark it against an array of ints to see which one performs better. If an array of bitset<4> is faster, then no it's not overkill. Every little bit helps on some of the PE problems > Would you consider it cheating? No, not at all. > Is there a bette...
How best to implement BCD as an exercise?
[ "", "c++", "bitsets", "" ]
I have a table that contains maybe 10k to 100k rows and I need varying sets of up to 1 or 2 thousand rows, but often enough a lot less. I want these queries to be as fast as possible and I would like to know which approach is generally smarter: 1. Always query for exactly the rows I need with a WHERE clause that's dif...
I firmly believe option 1 should be preferred in an initial situation. When you encounter performance problems, you can look on how you could optimize it using caching. (Pre optimization is the root of all evil, Dijkstra once said). Also, remember that if you would choose option 3, you'll be sending the complete table...
with 10K to 100K rows, number 1 is the clear winner to me. If it was <1K I might say keep it cached in the application, but with this many rows, let the DB do what it was designed to do. With the proper indexes, number 1 would be the best bet. If you were pulling the same set of data over and over each time then cachi...
Any SQL database: When is it better to fetch a whole table instead of querying for particular rows?
[ "", "sql", "database", "" ]
Just wondering if anyone knew off the top of their heads if there was much difference in doing the following: ``` String wibble = "<blah> blah blah </blah>.... <wibble> blah wibble blah </wibble> some more test here"; int i = wibble.lastIndexOf(">"); int j = wibble.lastIndexOf('>'); ```
Opinions are great but data are better. I wrote a quick benchmark: ## Test Code ``` public static void main(String[] args) { System.out.println("Starting perfo test"); final long NUM_TESTS = 100000000L; String wibble = "<blah> blah blah </blah>.... <wibble>" + " blah wibble blah </wibble> some...
You can actually look into the source code of String class. It seems lastIndex(char) and lastIndex(String) were actually written separately. There should also be an overhead with String class. So char version might be a little bit faster, but I doubt there will be a case with any significant performance difference. <h...
String.lastIndexOf() is there a difference between a char and a string with a single character?
[ "", "java", "performance", "optimization", "" ]
I'm developing an Windows Forms application that requires me to call a separate program to perform a task. The program is a console application and I need to redirect standard output from the console to a TextBox in my program. I have no problem executing the program from my application, but I don't know how to redire...
This works for me: ``` void RunWithRedirect(string cmdPath) { var proc = new Process(); proc.StartInfo.FileName = cmdPath; // set up output redirection proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.EnableRaisingEvents = true; proc.Start...
You can use the following code ``` MemoryStream mem = new MemoryStream(1000); StreamWriter writer = new StreamWriter(mem); Console.SetOut(writer); Assembly assembly = Assembly.LoadFrom(@"C:\ConsoleApp.exe"); assembly.EntryPoint.Invoke(null, null); writer.Close(); ...
Redirect console output to textbox in separate program
[ "", "c#", ".net", "winforms", "textbox", "console", "" ]
I have an image that is Base64 encoded. What is the best way to decode that in Java? Hopefully using only the libraries included with Sun Java 6.
As of v6, Java SE ships with JAXB. [`javax.xml.bind.DatatypeConverter`](http://download.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html) has static methods that make this easy. See [`parseBase64Binary()`](http://download.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html#parseBase64Bi...
As of **Java 8**, there is an officially supported API for Base64 encoding and decoding. In time this will probably become the default choice. The API includes the class [`java.util.Base64`](https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html) and its nested classes. It supports three different flavors: ba...
Decode Base64 data in Java
[ "", "java", "base64", "" ]
I have one class that needs to grab an attribute that is set in another. It's not a standard data type though. Here's the code; ``` class graphics: def __init__(self, Fullscreen = False, Width = 640, Height = 480): print "Graphics Init" SCREEN_SIZE = (Width, Height) pygame.init() if Fullscreen: ...
You rarely, if ever, reference attributes of a class. You reference attributes of an object. (Also, class names should be uppercase: `Graphics`). ``` class Graphics: SCREEN_SIZE = (640, 480) def __init__(self, Fullscreen = False, Width = 640, Height = 480): print "Graphics Init" self.SCREEN_SIZE = (Width, Hei...
I'm thinking that a short explanation of the difference between class and instance attributes in Python might be helpful to you. When you write code like so: ``` class Graphics: screen_size = (1024, 768) ``` The class `Graphics` is actually an object itself -- a class object. Because you defined `screen_size` in...
How do you make a class attribute that isn't a standard data type?
[ "", "python", "pygame", "" ]
How much of a performance benefit is there by selecting only required field in query instead of querying the entire row? For example, if I have a row of 10 fields but only need 5 fields in the display, is it worth querying only those 5? what is the performance benefit with this limitation vs the risk of having to go ba...
It's not just the extra data aspect that you need to consider. Selecting all columns will negate the usefulness of covering indexes, since a bookmark lookup into the clustered index (or table) will be required.
It depends on how many rows are selected, and how much memory do those extra fields consume. It can run much slower if several text/blobs fields are present for example, or many rows are selected. How is adding fields later a risk? modifying queries to fit changing requirements is a natural part of the development pro...
Performance benefit when SQL query is limited vs calling entire row?
[ "", "sql", "linq-to-sql", "" ]
> Edit again: > I think I get it now. All I need to do then is use the current class colon the class I want to be able to access? Person : Student, or person : teacher > Is that correct? I'm currently trying to learn the ins and outs of object oriented programming. Currently I have a new object that's something like t...
You're still missing the essential point: a *class* associates the data *with its methods.* So the method that sets Jim's teacher is part of the Student class, as is the method that sets Jim's grade. Think of it in natural language first. "Jim is a student; students have names, stident ID numbers, and classes. Classes...
Since you're using C#, and assuming you're using .NET 3.5, your class would probably be looking something like this: ``` public class Student { public int Grade { get; set; } public string Teacher { get; set; } } ``` Grade and Teacher are automatic properties, which are roughly equivalent to getters and sette...
Using Objects across methods
[ "", "c#", "methods", "oop", "" ]
I have an application which makes decisions based on part of URL: ``` if ( isset($this->params['url']['url']) ) { $url = $this->params['url']['url']; $url = explode('/',$url); $id = $this->Provider->getProviderID($url[0]); $this->providerName = $url[0]; //set the provider name return $id; ...
Other comments here are correct, in AppController's beforeFilter validate the provider against the providers in your db. However, if all URLs should be prefixed with a provider string, you are going about extracting it from the URL the wrong way by looking in $this->params['url']. This kind of problem is exactly what...
the parameter will be a providername - alphanumeric string. i think the answer is basically to to use ctype\_alpha() in combination with a check that the providername is a valid one, based on other application logic. thanks for the replies
PHP - securing parameters passed in the URL
[ "", "php", "security", "validation", "cakephp", "" ]
I need to run a callable at a specific time of day. One way to do it is to calculate the timediff between now and the desired time , and to use the executor.scheduleAtFixedRate . Have a better idea? `executor.scheduleAtFixedRate(command, TIMEDIFF(now,run_time), period, TimeUnit.SECONDS))`
For this kind of thing, just go ahead and install [Quartz](http://www.quartz-scheduler.org/). EJB has some support for this kind of thing but really you just want Quartz for scheduled tasks. That being said, if you insist on doing it yourself (and I'd recommend not), use the [`ScheduledThreadPoolExecutor`](http://java...
You can user [JDK Timer](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Timer.html) and dont need to calculate the time difference: ``` Timer timer = new Timer(); Date executionDate = new Date(); long period = 24 * 60 * 60 * 1000; timer.scheduleAtFixedRate( new TimerTask() { @Override public voi...
How to schedule a Callable to run on a specific time?
[ "", "java", "scheduling", "callable", "" ]
The ruby folks have [Ferret](https://github.com/dbalmain/ferret). Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching.
[Whoosh](http://pypi.python.org/pypi/Whoosh/) is a new project which is similar to lucene, but is pure python.
The only one pure-python (not involving even C extension) search solution I know of is [Nucular](http://nucular.sourceforge.net/). It's slow (much slower than PyLucene) and unstable yet. We moved from PyLucene-based home baked search and indexing to [Solr](http://lucene.apache.org/solr/) but YMMV.
Is there a pure Python Lucene?
[ "", "python", "full-text-search", "lucene", "ferret", "" ]
I have been looking at OpenLaszlo and observed that scripting in the client is implemented in JavaScript. Does this mean it is possible to use libraries like JQuery and PrototypeJS ?
jQuery and Prototype rely heavily on the browser's DOM API, not just JavaScript. I am not very familiar with OpenLaszlo, but if it doesn't provide a DOM for manipulating the document to be output, then libraries oriented around abstracting cross-browser DOM incompatibilities will be less useful. Aptana's [Jaxer](http:/...
Directions on using JQuery with other Libraries: <http://docs.jquery.com/Using_jQuery_with_Other_Libraries>
Can OpenLaszlo Use JavaScript Libraries like JQuery and PrototypeJS?
[ "", "javascript", "jquery", "prototypejs", "openlaszlo", "" ]
Does anybody know any fine open source cube browser? Ideally, it would be something built with plain javascript. Does it even exists? I'm planing to use it with classic asp agains a SQL database.
You can look at [Pentaho Mondrian](http://mondrian.pentaho.org/) (including [JPivot](http://jpivot.sourceforge.net)), or at [Eclipse BIRT](http://eclipse.org/birt) With these, you get some kind of flexible reporting tools on the most popular databases, and it includes functionality to browse OLAP cubes too.
If you're looking for something lightweight, give [CubesViewer](https://github.com/jjmontesl/cubesviewer) a try: It's mostly Javascript, backed up by Cubes OLAP server. *(Disclaimer, I'm the main developer :-))*
Browsing OLAP cubes
[ "", "javascript", "database", "widget", "olap", "cube", "" ]
I'd like to split strings like these ``` 'foofo21' 'bar432' 'foobar12345' ``` into ``` ['foofo', '21'] ['bar', '432'] ['foobar', '12345'] ``` Does somebody know an easy and simple way to do this in python?
I would approach this by using `re.match` in the following way: ``` import re match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I) if match: items = match.groups() print(items) >> ("foofo", "21") ```
``` def mysplit(s): head = s.rstrip('0123456789') tail = s[len(head):] return head, tail ``` ``` >>> [mysplit(s) for s in ['foofo21', 'bar432', 'foobar12345']] [('foofo', '21'), ('bar', '432'), ('foobar', '12345')] ```
How to split strings into text and number?
[ "", "python", "string", "split", "" ]
In Java, can Class.forName ever return null, or will it always throw a ClassNotFoundException or NoClassDefFoundError if the class can't be located?
Java Docs says it will throw ClassNotFoundException if the class cannot be found so I'd say it never returns null.
Since null is not mentioned anywhere in the documentation for this method and because there doesn't seem to be any situation in which it would make sense for the method to return null instead of throwing an exception, I think it's pretty safe to assume that it never returns null. It won't throw a NoClassDefFoundError,...
In Java, can Class.forName ever return null?
[ "", "java", "classloader", "" ]
Say you have these two methods: Number 1: ``` void AddPerson(Person person) { // Validate person if(person.Name != null && IsValidDate(person.BirthDate) DB.AddPersonToDatabase(person); } ``` Number 2: ``` void AddPerson(string name, DateTime birthDate) { Person p = new Person(name, birthDate); DB.AddPer...
The first shouldn't have to validate person.Name and person.BirthDate - they should be validated automatically by the `Person` constructor. In other words, if you're passed a Person, you should know that it's valid. On the other hand, you'd have to check that `person` isn't a null reference. It's sometimes worth havi...
The first one has the advantage of allowing you to change the Person definition without breaking existing code, only recompilation is needed. You may think the second one is more readable, but the first one is more maintainable, your choice.
OO style parameters vs type parameters
[ "", "c#", "oop", "methods", "" ]
How do I increment a step value to be processed when the page loads? For example, in the code below the viewstate variable is not incremented until after Page\_Load, due to the ASP.NET page lifecycle. ``` protected void Page_Load(object sender, EventArgs e) { switch ((int)ViewState["step"]) { //do some...
Just move the switch statement into an event that happens later. E.g. LoadComplete() or PreRender(). PreRender is probably a bit late, depending on what you want to do.
There's no way around this. Page\_Load event will always happen before any control events get fired. If you need to do something after the control event, use Page\_PreRender. [ASP.Net Page Lifecycle Image](http://codebetter.com/blogs//images/codebetter_com/raymond.lewallen/89/o_aspNet_Page_LifeCycle.jpg)
How do I increment a step value to be processed when the page loads in ASP.NET?
[ "", "c#", "asp.net", "postback", "" ]
In c (or maybe c++) , what's the difference between ``` char myarr[16]={0x00}; ``` and ``` char myarr[16]; memset(myarr, '\0', sizeof(myarr)); ``` ?? edit: I ask this because in vc++ 2005 the result is the same.. edit more : and ``` char myarr[16]={0x00,}; ``` ? maybe can get more comprehensive answer and ...
The important difference is that the first default initializes the array in an element-specific manner: Pointers will receive a *null pointer value*, which doesn't need to be 0x00 (as in all-bits-zero), booleans will be *false*. If the element type is a class type that's not a so-called *POD* (plain old data-type), the...
ISO/IEC 9899:TC3 6.7.8, paragraph 21: > If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialize...
Difference in initializing and zeroing an array in c/c++?
[ "", "c++", "c", "arrays", "" ]
In a Java project (SWT desktop app), I want to inform the user about events through animated notification box (actually, it's not required to be animated). Something like MSN or any other IM client. There is [JToaster](http://jtoaster.sourceforge.net/) for Swing, but I wonder if there isn't any other implementation ba...
The [MyLyn](http://www.eclipse.org/mylyn) plugin for Eclipse does this. Since it's open source, maybe you can check the MyLyn code to see how it's done there?
If you want to create SWT-based System notifications, this is the best resource to start with: <http://hexapixel.com/2009/06/30/creating-a-notification-popup-widget> The author creates real System notifications which are stackable and fade out nicely.
SWT Notification animated box (a.k.a toaster) needed
[ "", "java", "user-interface", "swt", "desktop", "desktop-application", "" ]
I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the document icon in Explorer or Finder. What is the best way to do this in Python?
`open` and `start` are command-interpreter things for Mac OS/X and Windows respectively, to do this. To call them from Python, you can either use `subprocess` module or `os.system()`. Here are considerations on which package to use: 1. You can call them via `os.system`, which works, but... **Escaping:** `os.syst...
Use the `subprocess` module available on Python 2.4+, not `os.system()`, so you don't have to deal with shell escaping. ``` import subprocess, os, platform if platform.system() == 'Darwin': # macOS subprocess.call(('open', filepath)) elif platform.system() == 'Windows': # Windows os.startfile(filepath...
Open document with default OS application in Python, both in Windows and Mac OS
[ "", "python", "windows", "macos", "" ]
I have a `HashMap` (although I guess this question applies to other collections) of objects. From what I understand, when the documentation talks about removing mappings, then it is removing the entry from the hashtable, i.e. not necessarily destroying the actual object. If the only remaining reference to the object is...
Yes, if the collection is the last place these objects are referenced they are eligible for garbage collection after they have been removed from the collection. And no, you can not destroy these objects forcefully. The garbage collector will handle them when it feels like it.
Note that [WeakHashMap](http://java.sun.com/j2se/1.4.2/docs/api/java/util/WeakHashMap.html) allows you to place objects in it and have them eligible for garbage collection as soon as there are no more references to the key (not the value) outside the map - the map entry will disappear at this point. In general you sho...
Removing objects from Java Collections
[ "", "java", "collections", "" ]
I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is ...
``` import jpeg jpeg.setExif(jpeg.getExif('foo.jpg'), 'foo-resized.jpg') ``` <http://www.emilas.com/jpeg/>
There is actually a really simple way of copying EXIF data from a picture to another with only PIL. Though it doesn't permit to modify the exif tags. ``` image = Image.open('test.jpg') exif = image.info['exif'] # Your picture process here image = image.rotate(90) image.save('test_rotated.jpg', 'JPEG', exif=exif) ``` ...
Resize image in Python without losing EXIF data
[ "", "python", "image-processing", "python-imaging-library", "exif", "" ]
I need a simple function which will take a FileInfo and a destination\_directory\_name as input, get the file path from the fileinfo and replicate it in the destination\_directory\_name passed as the second parameter. for ex. filepath is "d:\recordings\location1\client1\job1\file1.ext the function should create the di...
I'm using the following method for that purpose: ``` public static void CreateDirectory(DirectoryInfo directory) { if (!directory.Parent.Exists) CreateDirectory(directory.Parent); directory.Create(); } ``` Use it in this way: ``` // path is your file path string directory = Path.GetDirectoryName(path...
System.IO.Directory.CreateDirectory can be used to create the final directory, it will also automatically create all folders in the path if they do not exist. ``` //Will create all three directories (if they do not already exist). System.IO.Directory.CreateDirectory("C:\\First\\Second\\Third") ```
c# - Function to replicate the folder structure in the file path
[ "", "c#", "filesystems", ".net", "system.io.directory", "" ]
This is an attempt to rephrase a question I asked earlier. I'd like to know why C++ seems to be the language of choice for certain thick client apps. The easiest example I can think of is video games and my favorite app VirtualBox. Please don't close this post I'm just trying to understand why this is the case.
As a profesional game dev working on AAA titles I can tell you. Reason number 1 is C++ and C will compile and run on any platform say a PS3 or an NDS. Next platform makers only provide robust C libraries to interface with hardware. The reason behind this is C and C++ are free, and not owned by one corporation, and beca...
There are lots of potential reasons: * Speed increases either perceived or real. * Previous knowledge. There are a lot of people out there that have been programming C++ for 20+ years. Not so with C#. * Existing code. It is true that .Net has a lot of capability wrapped up in the framework. Even then it still doesn't ...
What advantage does C++ have over .NET when it comes to to game development and apps like VirtualBox
[ "", ".net", "c++", "" ]
Common question but I could use an "english" explanation. Is it like Java where ``` Cat myCat ``` actually is a pointer to `Cat`? Should I really create copy constructors in C#? --- I understand we are passing by value, but now my question is are we passing by pointer value or full copy of the object? If it's th...
As @rstevens answered, if it is a class, myCat is a reference. But if you pass myCat to a method call, then the reference itself is passed by value - i.e. the parameter itself will reference the same object, but it's a completely new reference, so if you assign it to null, or create a new object, the old myCat referenc...
Remember that a pointer is not exactly the same as a reference, but you can just about think of it that way if you want. I swear I saw another SO question on this not 10 minutes ago, but I can't find the link now. In the other question I saw, they were talking about passing arguments by ref vs by value, and it came do...
C# pass by value/ref?
[ "", "c#", "" ]
I do not quite understand the difference between a C# reference and a pointer. They both point to a place in memory don't they? The only difference I can figure out is that pointers are not as clever, cannot point to anything on the heap, are exempt from garbage collection, and can only reference structs or base types....
C# references can, and will be relocated by garbage collector but normal pointers are static. This is why we use `fixed` keyword when acquiring a pointer to an array element, to prevent it from getting moved. EDIT: Conceptually, yes. They are more or less the same.
There is a slight, yet extremely important, distinction between a pointer and a reference. A pointer points to a place in memory while a reference points to an object in memory. Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at. Take for example the followi...
What is the difference between a C# Reference and a Pointer?
[ "", "c#", "pointers", "reference", "" ]
I want to send a custom "Accept" header in my request when using urllib2.urlopen(..). How do I do that?
Not quite. Creating a `Request` object does not actually send the request, and Request objects have no `Read()` method. (Also: `read()` is lowercase.) All you need to do is pass the `Request` as the first argument to `urlopen()` and that will give you your response. ``` import urllib2 request = urllib2.Request("http:/...
I normally use: ``` import urllib2 request_headers = { "Accept-Language": "en-US,en;q=0.5", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Referer": "http://thewebsite.com", "Connection": "keep-al...
How do I send a custom header with urllib2 in a HTTP Request?
[ "", "python", "header", "urllib2", "" ]
I'm building a wepage in php using MySQL as my database. Which way is faster? 1. 2 requests to MySQL with the folling query. SELECT points FROM data; SELECT sum(points) FROM data; 2. 1 request to MySQL. Hold the result in a temporary array and calcuale the sum in php. $data = SELECT points FROM data; ED...
It's really going to depend on a lot of different factors. I would recommend trying both methods and seeing which one is faster.
Since Phill and Kibbee have answered this pretty effectively, I'd like to point out that premature optimization is a Bad Thing (TM). Write what's simplest for you and profile, profile, profile.
php and MySQL: 2 requests or 1 request?
[ "", "php", "mysql", "" ]
I have a WCF service that I call from a windows service. The WCF service runs a SSIS package, and that package can take a while to complete and I don't want my windows service to have to wait around for it to finish. How can I make my WCF service call asynchronous? (or is it asynchronous by default?)
All your needs will be satisfied in the following articles from MSDN: [Implementing an Async Service Operation](http://msdn.microsoft.com/en-us/library/ms731177.aspx) [Calling WCF Service Async](http://msdn.microsoft.com/en-us/library/ms730059.aspx) [Designing Service Contracts](http://msdn.microsoft.com/en-us/libra...
On Visual Studio 2010, on the `Add Service Reference > click Advanced button > check the Generate Asynchronous Operations` checkbox. After doing so, the Async operations will be added and be available for your use.
How to make a call to my WCF service asynchronous?
[ "", "c#", ".net", "wcf", "windows-services", "" ]
I have a function that accepts an anonymous function as an argument and sets it to a variable (scoped) for reference. I then try to execute another function with that reference but it obviously fails since that function is out of scope. I was wondering if anyone knew of a simple way of passing the anonymous function s...
``` var tf = arguments.splice(i,1) ``` This returns an array into tf. Is eventListen expecting an array? If not use:- ``` var tf = arguments.splice(i,1)[0] ``` Since you don't seem to have any other uses for your other arguments why are you using splice anyway?
You can do: ``` for (var i=0;i<arguments.length;i++){ if (typeof(arguments[i])=='function'){ JAS.Globals.eventListen('click',el,arguments[i]); break; } } ``` or if you need to assign the event after the loop for some reason: ``` var tf; for (var i=0;i<arguments.length;i++){ if (typeof(arg...
Pass anonymous function by value in javascript?
[ "", "javascript", "anonymous-function", "byval", "" ]
What's the best/easiest way to run periodic tasks (like a daemon thread) on a tomcat/jetty server? How do I start the thread? Is there a simple mechanism or is this a bad idea at all?
It's okay and effective to stash a java.util.Timer (or better yet ScheduledExecutor) instance in your ServeletContext. Create it in a Servlet's init() call and all your servlets can add TimerTasks to it.
If want to keep everything on java side, give a look to [Quartz](http://www.quartz-scheduler.org/). It handles failover and fine grained repartition of jobs, with the same flexibility of cron jobs.
run periodic tasks on server in the background
[ "", "java", "web-services", "tomcat", "daemon", "" ]
I have tried to use some of the widgets in `JQuery UI` on an `Asp.Net MVC` site without luck. For example the basic datepicker from [jQuery UI - functional demos](http://ui.jquery.com/repository/tags/latest/demos/functional/#ui.datepicker). I have created a simple MVC project and added the script references in `Site....
Make sure your initializer is called after the DOM is loaded: ``` $(document).ready(function() { $("#basics").datepicker(); }); ``` [jQuery ready event](http://docs.jquery.com/Events/ready#fn): > By using this method, your bound > function will be called the instant > the DOM is ready to be read and > manipulate...
I've got a write-up of this with MVC 3 here: <http://blogs.msdn.com/b/stuartleeks/archive/2011/01/25/asp-net-mvc-3-integrating-with-the-jquery-ui-date-picker-and-adding-a-jquery-validate-date-range-validator.aspx>
JQuery UI datepicker in Asp.Net MVC
[ "", "javascript", "jquery", "html", "asp.net-mvc", "jquery-ui", "" ]
I was wondering what is the design motive behind extension methods in C#
It allows you to create new functionality to an existing code base without editing the original code. <http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx> **"Extension methods allow developers to add new methods to the public contract of an existing CLR type, without h...
The primary reason for their existence is being able to somehow add features to a type without inheriting from it. This was required to provide `Where`, `Select`, ... methods for use in LINQ for collections that didn't have one.
What is the design motive behind extension methods in C#
[ "", "c#", ".net-3.5", "c#-3.0", "" ]
I am looking to have a C# application implement the Konami Code to display an Easter Egg. <http://en.wikipedia.org/wiki/Konami_Code> What is the best way to do this? This is in a standard C# windows forms app.
In windows forms I would have a class that knows what the sequence is and holds the state of where you are in the sequence. Something like this should do it. ``` using System; using System.Collections.Generic; using System.Windows.Forms; namespace WindowsFormsApplication3 { public class KonamiSequence { ...
The correct sequence, the same way Konami itself would have implemented it: * get input * if input equals byte at index of code array, increment index + else, clear index * if index is greater than code length, code is correct Here is how NOT to do it: * Accumulating a buffer of keystrokes and then doing a byte-by...
Konami Code in C#
[ "", "c#", ".net", "winforms", "" ]
In my last development environment, I was able to easily interact with COM, calling methods on COM objects. Here is the original code, translated into C# style code (to mask the original language): ``` public static void SpawnIEWithSource(String szSourceHTML) { OleVariant ie; //IWebBrowser2 OleVariant ie = new...
Late bound IDispatch called is relativly easy in .NET, although piss-poor: ``` public static void SpawnIEWithSource(String szHtml) { // Get the class type and instantiate Internet Explorer. Type ieType = Type.GetTypeFromProgID("InternetExplorer.Application"); object ie = Activator.CreateInstance(ieType); ...
> **Update:** Based on question updates, I have removed the portions of my answer that are no longer relevant to the question. However, in case other readers are looking for a quick and dirty way to generate HTML in a winforms app and do not require an in-process IE, I will leave the following: **Possible Scenario 1: ...
.NET2.0 C# Interop: How to call COM code from C#?
[ "", "c#", "com", "interop", ".net-2.0", "idispatch", "" ]
Can anyone help me with the trying to write SQL (MS SqlServer) - I must admit this is not by best skill. What I want to do is exactly the same functionality as appears for the search boxes for the [Yell website](http://www.yell.com/) i.e. * Search for company type * AND/OR company name * AND/OR enter a company name *...
Typically, one does something like this: ``` -- All these are NULL unless provided DECLARE @CompanyType AS varchar DECLARE @CompanyName AS varchar DECLARE @Town AS varchar SELECT * FROM TABLE_NAME WHERE (@CompanyType IS NULL OR COMPANY_TYPE_COLUMN LIKE '%' + @CompanyType + '%') AND (@CompanyName IS NULL OR COMPA...
Can you provide the database layout (schema) that the sql would run against? It would be necessary to give you an exact result. But generally speaking what you are looking for is ``` SELECT * FROM tablename WHERE companyType = 'type' OR companyName = 'companyName' ```
Writing SQL code: same functionality as Yell.com
[ "", "sql", "sql-server-2005", "" ]
I'd like to have the nightly build check for how many NotImplementedExeptions there are in my .NET code so hopefully we can remove them all before releasing. My first thought is that FxCop might be a good tool to do this. Does anyone have a custom FxCop rule for this? How would I go about creating one myself?
I've actually implemented one and shown the code in [this answer](https://stackoverflow.com/questions/410719/notimplementedexception-are-they-kidding-me/410800#410800).
Unit test like this will fail if more than 10 methods create NotImplementedException. On failing it will report all methods that create this exception. ``` var throwingMethods = codebase.Methods .Where(m => m .GetInstructions() .Exists(i => i.Creates<NotImplementedException>())) .ToArray(); if (...
FxCop rule that checks for NotImplementedExceptions
[ "", "c#", ".net", "fxcop", "ndepend", "notimplementedexception", "" ]
How can I remove the "xmlns:..." namespace information from each XML element in C#?
Zombiesheep's cautionary answer notwithstanding, my solution is to wash the xml with an xslt transform to do this. **wash.xsl:** ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="no" encoding="UTF-8"/> <xsl:template match="/|comment()|processing-...
From here <http://simoncropp.com/working-around-xml-namespaces> ``` var xDocument = XDocument.Parse( @"<root> <f:table xmlns:f=""http://www.w3schools.com/furniture""> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table> </root>"); xDocument....
C#: How to remove namespace information from XML elements
[ "", "c#", ".net", "xml", "namespaces", "" ]
I have a small (500kb) swing applet that displays very simple/limited set of small HTML page(s) inside it with JEditorPane, however this does not seem to work 100% fluently, some customers get a blank page displayed without any java exceptions. The page works OK from my machine. I need a more reliable way to show HTML ...
AFAIK, JEditorPane is a very primitive HTML component: it is confused by CSS and knows nothing about JS. I doubt you will find a "small + free" class doing better, HTML parsing and displaying isn't a simple business, even less today. Perhaps it is better to let the big names in the business to take care of this task...
Although I haven't used it before, [Lobo](http://lobobrowser.org/java-browser.jsp) is an open source web browser for Java with support for HTML 4, Javascript and CSS 2. Compared to the [`JEditorPane`](http://java.sun.com/javase/6/docs/api/javax/swing/JEditorPane.html) which only has support of HTML 3.2, it seems like ...
Viewing HTML inside Applet without using JEditorPane
[ "", "java", "applet", "" ]
Date and time in MySQL can be stored as DATETIME, TIMESTAMP, and INTEGER (number of seconds since 01/01/1970). What are the benefits and drawbacks of each, particularly when developing under a LAMP stack?
* TIMESTAMP is stored in a MySQL proprietary method (though it's basically just a string consisting of year, month, day, hour, minutes and seconds) and additionally, a field of type TIMESTAMP is automatically updated whenever the record is inserted or changed and no explicit field value is given: ``` mysql> create...
I would save data using the DATETIME or DATE fields in MySQL. At least, if you are going to store date values up to the year 2038: <http://en.wikipedia.org/wiki/Year_2038_problem>. If you're on a system that stores integers differently, you may not have this issue. It is still easy to compare date values or even times...
What are the pros and cons of the various date/time field types in MySQL?
[ "", "php", "mysql", "datetime", "timestamp", "lamp", "" ]
I would like to do something like this: ``` container::iterator it = NULL; switch ( eSomeEnum ) { case Container1: it = vecContainer1.begin(); break; case Container2: it = vecContainer2.begin(); break; ... } for( ; it != itEnd ; ++it ) { .. } ``` But I can't create and initialise an iterator to NULL. Is there s...
You just needn't initialize it at all, because iterators are DefaultConstructible.
All you should need to do is change ``` container::iterator it = NULL; ``` to ``` container::iterator it; ``` and I think your code will work as intended.
Using an STL Iterator without initialising it
[ "", "c++", "stl", "scope", "iterator", "" ]
I have a table which defines a child-parent relationship between nodes: ``` CREATE TABLE node ( ' pseudo code alert id INTEGER PRIMARY KEY, parentID INTEGER, ' should be a valid id. ) ``` If `parentID` always points to a valid existing node, then this will naturally define a tree...
[This link](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/) provides a tutorial on both the Adjacency List Model (as described in the question), and the Nested Set Model. It is written as part of the documentation for MySQL. What is not discussed in that article is insertion/delection time, and m...
> If you have any magic books you reach for for this kind of query, I'd like to know. Celko's *Trees and Hierarchies in SQL For Smarties*
How to find all nodes in a subtree in a recursive SQL query?
[ "", "sql", "recursion", "tree", "odbc", "" ]
I have changed the Treeview.HideSelection = false; But how do I insure that when focus is lost that the selected item remains the original selected color? EDIT: I have a listview on a form that holds a list of process events. Alongside the Treeview on the same form is a series of selections that the user completes to...
Setting `ListView.HideSelection` to true means that when focus is lost, it will hide the selection. By setting `HideSelection` to false, the selected item will still have the color indicator showing which item is selected.
Generally, you don't. The change in color is one of the visual cues that indicate which control has the focus. Don't confuse your customers by getting rid of that. If you want to buck the convention, then you can make your control owner-drawn, and then you can paint the items whatever color you want. Another option, ...
C# how do I ensure the selected node remains highlighted when focus lost
[ "", "c#", "treeview", "" ]
I'm looking for the name of the PHP function to build a query string from an array of key value pairs. Please note, I am looking for *the built in PHP* function to do this, not a homebrew one (that's all a google search seems to return). There is one, I just can't remember its name or find it on php.net. IIRC its name ...
You're looking for [`http_build_query()`](http://us.php.net/manual/en/function.http-build-query.php).
Here's a simple php4-friendly implementation: ``` /** * Builds an http query string. * @param array $query // of key value pairs to be used in the query * @return string // http query string. **/ function build_http_query( $query ){ $query_array = array(); foreach( $query as $key => $key_value ){ ...
PHP function to build query string from array
[ "", "php", "" ]
I've got some code that was at the bottom of a php file that is in javascript. It goes through lots of weird contortions like converting hex to ascii then doing regex replacements, executing code and so on... Is there any way to find out what it's executing before it actually does it? The code is here: <http://paste...
You can just go through it stage by stage - since it's Javascript, and it's interpreted, it needs to be its own decryptor. If you have access to a command-line Javascript interpreter (such as the Console in [Firebug](http://www.getfirebug.com/)), this will be fairly straightforward. I'll have a look and see what comes...
Just write a perl script or something that changes all escaped hex characters to ascii? Then just look through the regexs to see what exactly is happening, and do the same thing with your perl/whatever script.
How would you reverse engineer this?
[ "", "javascript", "hex", "obfuscation", "reverse-engineering", "deobfuscation", "" ]
Suppose I have: ``` <a href="http://www.yahoo.com/" target="_yahoo" title="Yahoo!&#8482;" onclick="return gateway(this);">Yahoo!</a> <script type="text/javascript"> function gateway(lnk) { window.open(SERVLET + '?external_link=' + encodeURIComponent(lnk.href) + '&external_target=' + encodeURIC...
You are nearly there. EncodeURIComponent correctly encodes to UTF-8, which is what you should always use in a URL today. The problem is that the submitted query string is getting mutilated on the way into your server-side script, because getParameter() uses ISO-8559-1 instead of UTF-8. This stems from Ancient Times be...
I got the same problem and solved it by decoding `Request.getQueryString()` using URLDecoder(), and after extracting my parameters. ``` String[] Parameters = URLDecoder.decode(Request.getQueryString(), 'UTF-8') .splitat('&'); ```
How do I correctly decode unicode parameters passed to a servlet
[ "", "java", "unicode", "servlets", "" ]
Do you know a quick way to implement method(s) from an Interface to a Class. If yes, how can you do it? Situation : I have an Interface used by over 15 concrete classes. I added a new method and I need to implement this new method in all concrete class. **Update** All my concrete class implement the interface and al...
Since you mentioned that you have ReSharper installed, here some way to quickly implement this: * Use "Find Usages Advanced" with "Implementations" checkbox checked * For each class use quick action "Implement members" Also you can use "[solution wide analysis](http://www.jetbrains.com/resharper/features/code_ana...
Provide an abstract base class with a default implementation, and then have all your concrete classes inherit that abstract class.
Quickest way to implement a new interface member in many classes?
[ "", "c#", ".net", "" ]
The ScheduledExecutorService in Java is pretty handy for repeating tasks with either fixed intervals or fixed delay. I was wondering if there is an something like the existing ScheduledExecutorService that lets you specify a time of day to schedule the task at, rather than an interval i.e. "I want this task to fire at ...
You can use the [Timer](http://java.sun.com/j2se/1.4.2/docs/api/java/util/Timer.html) class. Specifically, scheduleAtFixedRate(TimerTask task, Date firstTime, long period). Where you can set a task to start at 10am on a particular day and repeat every 24 hours.
ThreadPoolTaskScheduler, can be used whenever external thread management is not a requirement. Internally, it delegates to a *ScheduledExecutorService* instance. *ThreadPoolTaskScheduler* implements Spring’s *TaskExecutor* interface too, so that a single instance can be used for asynchronous execution as well as schedu...
Is there a cron-like implementation of ScheduledExecutorService in Java?
[ "", "java", "scheduler", "" ]
I often see something like that: `something.property|escape` --- `something` is an object, `property` is it's string property. `escape` - i don't know :) What does this mean? And what min python version it is used in? EDIT: The question was asked wrongly, it said "What does | mean in Python", so the bitwise or a...
obj.property|escape is the way to apply the [escape filter in a template](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#built-in-filter-reference), which will HTML escape the string representation of that property.
The pipe character indicates that you want to send the results of the left hand side to the filter defined on the right side. The filter will modify the value in some way. The 'escape' filter is just one of many. The list of built in filters can be found here: [Django Documentation - Built-in filters reference](http:...
What does "|" sign mean in a Django template?
[ "", "python", "django", "django-templates", "" ]
``` void pushSynonyms (string synline, char matrizSinonimos [1024][1024]){ stringstream synstream(synline); vector<int> synsAux; int num; while (synstream >> num) {synsAux.push_back(num);} int index=0; while (index<(synsAux.size()-1...
### What's wrong with it The code as you have it there - i can't find a bug. The only problem i spot is that if you provide no number at all, then this part will cause harm: ``` (synsAux.size()-1) ``` It will subtract one from 0u . That will wrap around, because `size()` returns an unsigned integer type. You will en...
Arrays are passed as pointers - there's no need to do a pass-by-reference to them. If you declare your function to be: ``` void pushSynonyms(string synline, char matrizSinonimos[][1024]); ``` Your changes to the array will persist - arrays are *never* passed by value.
C++ Why is this passed-by-reference array generating a runtime error?
[ "", "c++", "pass-by-reference", "" ]
What is the best way(s) to fake function overloading in Javascript? I know it is not possible to overload functions in Javascript as in other languages. If I needed a function with two uses `foo(x)` and `foo(x,y,z)` which is the best / preferred way: 1. Using different names in the first place 2. Using optional argum...
The best way to do function overloading with parameters is not to check the argument length or the types; checking the types will just make your code slow and you have the fun of Arrays, nulls, Objects, etc. What most developers do is tack on an object as the last argument to their methods. This object can hold anythi...
I often do this: C#: ``` public string CatStrings(string p1) {return p1;} public string CatStrings(string p1, int p2) {return p1+p2.ToString();} public string CatStrings(string p1, int p2, bool p3) {return p1+p2.ToString()+p3.ToString();} CatStrings("one"); // result = one CatStrings...
Function overloading in Javascript - Best practices
[ "", "javascript", "overloading", "" ]
I have a sample string: ``` <num>1.</num> <Ref>véase anomalía de Ebstein</Ref> <num>2.</num> <Ref>-> vascularización</Ref> ``` I wish to make a comma seperated string with the values inside ref tags. I have tried the following: ``` Regex r = new Regex("<ref>(?<match>.*?)</ref>"); Match m = r...
You want to be using Matches rather than match to get all matches that occur, something like: ``` Regex r = new Regex("<ref>(?<match>.*?)</ref>"); foreach (Match m in r.Matches(csv[4])) { if (m.Groups.Count > 0) { if (m.Groups["match"].Captures.Count > 0) { foreach (Capture c in m.G...
I strongly recommend using XPath over regular expressions to search XML documents. ``` string xml = @"<test> <num>1.</num> <Ref>véase anomalía de Ebstein</Ref> <num>2.</num> <Ref>-> vascularización</Ref> </test>"; XmlDocument d = new XmlDocument(); d.LoadXml(xml); var list = from XmlNode n in d.SelectNodes("//Re...
Finding values within certain tags using regex
[ "", "c#", "regex", "" ]
This code will always make my aspx page load twice. And this has nothing to do with AutoEventWireup. ``` Response.Clear(); Response.ContentType = "application/pdf"; Response.AppendHeader("Content-Disposition", "inline;filename=data.pdf"); Response.BufferOutput = true; byte[] response = GetDocument(doclocation); Respon...
Have you found a resolution to this yet? I having the same issue, my code is pretty much a mirror of yours. Main difference is my pdf is hosted in an IFrame. So interesting clues I have found: If I stream back a Word.doc it only gets loaded once, if pdf it gets loaded twice. Also, I have seen different behavior from d...
``` GetDocument(doclocation); ``` May be this method somehow returns Redirection code ? or may be an iframe or img for your dynamic content? *If so:* In general the control could get called twice because of the url response. First it renders the content. After that your browser tries to download the tag (iframe,img)...
C# Writing to the output stream
[ "", "c#", "asp.net", "load", "" ]
I have a Python-based app that can accept a few commands in a simple read-eval-print-loop. I'm using `raw_input('> ')` to get the input. On Unix-based systems, I also `import readline` to make things behave a little better. All this is working fine. The problem is that there are asynchronous events coming in, and I'd ...
Maybe something like this will do the trick: ``` #!/usr/bin/env python2.6 from __future__ import print_function import readline import threading PROMPT = '> ' def interrupt(): print() # Don't want to end up on the same line the user is typing on. print('Interrupting cow -- moo!') print(PROMPT, readline...
Why are you writing your own REPL using `raw_input()`? Have you looked at the `cmd.Cmd` class? **Edit:** I just found the [sclapp](http://www.alittletooquiet.net/software/sclapp/) library, which may also be useful. Note: the `cmd.Cmd` class (and sclapp) may or may not directly support your original goal; you may have ...
How to implement a python REPL that nicely handles asynchronous output?
[ "", "python", "readline", "read-eval-print-loop", "" ]
I'm having a hard time understanding what the difference is between incrementing a variable in C# this way: ``` myInt++; ``` and ``` ++myInt; ``` When would ever matter which one you use? I'll give voteCount++ for the best answer. Or should I give it ++voteCount...
There is no difference when written on its own (as shown) - in both cases myInt will be incremented by 1. But there is a difference when you use it in an expression, e.g. something like this: ``` MyFunction(++myInt); MyFunction(myInt++); ``` In the first case, myInt is incremented and the new/incremented value is pa...
Others have shown where it makes a difference, and have commented that as a single statement it doesn't make a difference. I'd like to add that it's almost always a bad idea to use it where it makes a difference. I suspect there *may* be some times where it's more readable to have code such as: ``` Console.WriteLine(...
In C# what is the difference between myInt++ and ++myInt?
[ "", "c#", "syntax", "" ]
C++ does not have native support for lazy evaluation (as Haskell does). I'm wondering if it is possible to implement lazy evaluation in C++ in a reasonable manner. If yes, how would you do it? EDIT: I like Konrad Rudolph's answer. I'm wondering if it's possible to implement it in a more generic fashion, for example ...
> I'm wondering if it is possible to implement lazy evaluation in C++ in a reasonable manner. If yes, how would you do it? Yes, this is possible and quite often done, e.g. for matrix calculations. The main mechanism to facilitate this is operator overloading. Consider the case of matrix addition. The signature of the ...
Boost.Lambda is very nice, but [Boost.Proto](http://boost-sandbox.sourceforge.net/libs/proto/doc/html/index.html) is *exactly* what you are looking for. It already has overloads of *all* C++ operators, which by default perform their usual function when `proto::eval()` is called, but can be changed.
Lazy evaluation in C++
[ "", "c++", "lazy-evaluation", "" ]
The following code ``` using System.Threading; class Test { volatile int counter = 0; public void Increment() { Interlocked.Increment(ref counter); } } ``` Raises the following compiler warning: ``` "A reference to a volatile field will not be treated as volatile" ``` Am I doing something w...
You are not doing anything wrong. According to the [documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0420): > A volatile field should not normally > be passed using a ref or out > parameter, since it will not be > treated as volatile within the scope > of the functi...
Basically the warning is that when you pass a volatile field by reference, the calling code doesn't know to treat it in a volatile manner. For Interlocked.Increment that probably doesn't matter, due to the nature of the method - but then you don't need the variable to be volatile *anyway* if you're using Interlocked. ...
"A reference to a volatile field will not be treated as volatile" implications
[ "", "c#", ".net", "multithreading", "volatile", "" ]
Given a path and filename how can I get the `Image` object: ``` Image image = ...(filename) ```
You want to call the [static `FromFile` method on the `Image` class](http://msdn.microsoft.com/en-us/library/e6ytk052.aspx).
Another alternative is to use a Bitmap object (which inherits from Image) like so: ``` Bitmap bitmap = new Bitmap(imagePath); ``` (This works for all image formats, not just \*.bmp as the name might imply.)
get Image object from path name
[ "", "c#", ".net", "image", "" ]
I currently have a download site for my school that is based in .net. We offer anything from antivirus, autocad, spss, office, and a number of large applications for students to download. It's currently setup to handle them in 1 of 2 ways; anything over 800 megs is directly accessable through a seperate website while u...
I have two recommendations: * Increase the buffer size so that there are less iterations AND/OR * Do not call IsClientConnected on each iteration. The reason is that according to [Microsoft Guidelines](http://technet.microsoft.com/en-us/library/bb727078.aspx#EMAA): *Response.IsClientConnected has some costs, so on...
If you are having performance issues and you are delivering files that exist on the filesystem (versus a DB), use the [HttpResponse.TransmitFile](http://msdn.microsoft.com/en-us/library/12s31dhy(VS.80).aspx) function. As for the failures, you likely have a bug. If you post the code you may be better response.
Best way to handle a large download site?
[ "", "c#", "filestream", "" ]
I'm starting a new personal project on the side, so this is the first time I'll be able to start from the ground up on a larger project since ASP.NET 2.0 was first released. I'd like this to also be a good learning experience for me, so right now I'm planning on building this upon ASP.NET MVC, Castle ActiveRecord, and ...
[**Web Framework: MVC**](http://www.asp.net/mvc/) Just a better way to make web applications [**OR/M: NHibernate**](http://www.hibernate.org/343.html) Nothing really beats it in performance or features [**Javascript: JQuery**](http://jquery.com/) Been using it before it got all cool. JQuery to me seems less like a...
Built on nothing. Personally, I'm not a big fan of using frameworks and pre-built components for every single aspect of my project. I like to be in control of all the code, and write all the code myself. You could call it an extreme case of not invented here syndrome. Or you could say, if it's a core business function,...
What's your ideal C# project built upon?
[ "", "c#", "" ]
Is there a way to restrict certain tables from the mysqldump command? For example, I'd use the following syntax to dump *only* `table1` and `table2`: ``` mysqldump -u username -p database table1 table2 > database.sql ``` But is there a similar way to dump all the tables *except* `table1` and `table2`? I haven't foun...
You can use the [--ignore-table](https://dev.mysql.com/doc/refman/8.0/en/mysqldump.html#option_mysqldump_ignore-table) option. So you could do ``` mysqldump -u USERNAME -pPASSWORD DATABASE --ignore-table=DATABASE.table1 > database.sql ``` There is no whitespace after `-p` (this is not a typo). To ignore multiple tab...
Building on the answer from @Brian-Fisher and answering the comments of some of the people on this post, I have a bunch of huge (and unnecessary) tables in my database so I wanted to skip their contents when copying, but keep the structure: ``` mysqldump -h <host> -u <username> -p <database> --no-data > db.sql mysqldu...
How to skip certain database tables with mysqldump?
[ "", "sql", "mysql", "database", "dump", "database-dump", "" ]
I'v never done unit testing before, but now I am willing to give it a try. **What framework is best for starters?** Pros and Cons **what should i read before i begin any coding?** Books/Articles/Code/Blogs **is there any opensource "sample projects"?** I will be usign it with asp.net mvc/C#.
If you have integrated Unit Testing in Visual Studio (I think it's part of Professional and better), start with that, because it's integrated. Downside is that to my knowledge, there is no test runner outside of Visual Studio or the Team Foundation Server which disqualifies it for automated testing, but I am not sure h...
I recommend you look into the [Gallio Automation Platform for .NET](http://www.gallio.org/) as it provides a neutral (and FREE) tool that can implement multiple unit testing frameworks for you under the one GUI tool. It is created by the guys behind mbUnit. My main pro for any unit testing framework is that it gives y...
Which Unit test framework and how to get started (for asp.net mvc)
[ "", "c#", "asp.net-mvc", "unit-testing", "" ]
The Yahoo Javascript library (YUI), JQuery and less so Google maps all allow you to reference their files using the following format: ``` <script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/yahoo-dom-event/yahoo-dom-event.js"></script> ``` This does a request for the script from their servers, wh...
Chris, I work on the YUI team at Yahoo. We host only YUI on yui.yahooapis.com; Google hosts YUI and many other libraries on its CDN. I can tell you from the Yahoo side that we don't monitor site usage of YUI from our CDN. We do track general growth of yui.yahooapis.com usage, but we don't track which sites are genera...
Of course they produce statistics - at minimum they need to know how many resources they spend on hosting these scripts. And it's also nice to know who uses your code. I don't think it's a bad thing. And using a hosted version makes even more sense because your visitors might have the script already cached after visi...
Hosted Yui, Google maps, JQuery - an easy way of monitoring website usage?
[ "", "javascript", "jquery", "yui", "" ]
I have a data structure that represents C# code like this: ``` class Namespace: string Name; List<Class> Classes; class Class: string Name; List<Property> Properties; List<Method> Methods; List<Method> Constructors; List<Field> Fields; List<Class> InnerClasses; Class Parent; Li...
You could try to aggregate your 3000 rules. Some of the 3000, I would guess assume another member of the 3000. Say rule 12 checks 'a class implements an interface'. Rule 85 might be 'a class only implements interfaces in the same assembly'. If rule 12 fails, no need to run rule 85 at all. This approach (alpha-beta pru...
I'd consider creating some sort of representation for pattern/context, then creating a hash map from pattern to set of actions. Without knowing more of your requirements, it's hard to be more specific, but as an example, the string `"Namespace/Class"` could be a key to a set of actions that depend on knowing the namesp...
How would you implement?: Lots of rules over a tree in C#
[ "", "c#", "tree", "design-patterns", "rules", "traversal", "" ]
I've written a class with a single static method that copies property values from one object to another. It doesn't care what type each object is, only that they have identical properties. It does what I need, so I'm not engineering it further, but what improvements would you make? Here's the code: ``` public class S...
Are your DTOs serializable? I would expect so, in which case: ``` MemberInfo[] sm = FormatterServices.GetSerializableMembers(typeof(From)); object[] data = FormatterServices.GetObjectData(from, sm); FormatterServices.PopulateObjectMembers(to, sm, data); ``` But note that I don't really agree with this general approac...
* Change your type parameter names to comply with naming conventions, e.g. TFrom and TTo, or TSource and TDest (or TDestination). * Do most of your work in a generic type instead of in just a generic method. That allows you to cache the properties, as well as allowing type inference. Type inference is important on the ...
How would you improve this shallow copying class?
[ "", "c#", "reflection", "shallow-copy", "" ]
In a visual studio C++ project, would MFC be faster than using the CLR? I'd specificily be using 2008. Oh and the reason I ask is because I have experience with .NET but not so much with MFC. I understand what MFC is but have never really used it much.
If you are talking about a Visual C++ project with /clr enabled, then definitely one without /clr will be faster. However, a Visual C++ project without /clr can be outrun by a Visual C# project in some cases(some cases: not all of them) mainly because of the optimizations that can be done at the CLR layer.
If you're referring to dev time, if you have experience with .NET and the runtime environment requirements are not a concern, you're probably better off doing a CLR project of some sort. MFC has a fairly steep learning curve, and .NET experience is fairly easy to translate cross-language. If you're talking about runti...
MFC vs. CLR?
[ "", ".net", "c++", "visual-studio", "mfc", "clr", "" ]
As the title suggests, I'm using Google App Engine and Django. I have quite a bit of identical code across my templates and would like to reduce this by including template files. So, in my main application directory I have the python handler file, the main template, and the template I want to include in my main templa...
I found that it works "out of the box" if I don't load Templates first and render them with a Context object. Instead, I use the standard method shown in the [AppEngine tutorial](http://code.google.com/appengine/docs/python/gettingstarted/templates.html).
First, you should consider using [template inheritance](http://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance) rather than the `include` tag, which is often appropriate but sometimes far inferior to template inheritance. Unfortunately, I have no experience with App Engine, but from my experience ...
AppEngine and Django: including a template file
[ "", "python", "django", "google-app-engine", "templates", "include", "" ]
this subquery works in SQL Server: ``` select systemUsers.name, (select count(id) from userIncidences where idUser = systemUsers.id ) from systemUsers ``` How can It be made in SQL Compact? Thanks!
Try this: ``` SELECT su.Name, COUNT(ui.ID) FROM systemUsers su LEFT JOIN userIncidences ui ON ui.idUser = su.ID GROUP BY su.Name ``` [Edit:] I originally had an INNER JOIN just like Tomalak, but I realized that this would exclude users with no incidents, rather than show them with a 0 count. That might even be what...
There are cases when you can't avoid a subquery, for instance if you have to include calculated columns that use data from the current and the previous row. Consider this query, for instance: ``` SELECT (Current.Mileage - Last.Mileage)/Quantity as MPG FROM GasPurchases AS Current LEFT OUTE...
How can I make this query in SQL Server Compact Edition?
[ "", "sql", "sql-server", "sql-server-ce", "" ]
I have 2 classes, main and extended. I need to use main vars in extended class. ``` <?php class Main { public $vars = array(); } $main = new Main; $main->vars['key'] = 'value'; class Extended extends Main { } $other = new Extended; var_dump($other->vars); ?> ``` Who I can do it? No valid for example: ``` <?...
**EDIT**: This can be solved much better with *Inversion of Control* (IoC) and *Dependency Injection* (DI). If you use your own framework or one without *Dependency Injection Container* try [League/Container](http://container.thephpleague.com/) Answer below left as history of foolish answers. --- The correct way I f...
It would be easily possible with a simple constructor ``` <?php class One { public static $string = "HELLO"; } class Two extends One { function __construct() { parent::$string = "WORLD"; $this->string = parent::$string; } } $class = new Two; echo $class->string; // WORLD ?> ```
Using parent variables in a extended class in PHP
[ "", "php", "class", "object", "extends", "" ]
This error message is being presented, any suggestions? > Allowed memory size of 33554432 bytes exhausted (tried to allocate > 43148176 bytes) in php
If your script is **expected** to allocate that big amount of memory, then you can increase the memory limit by adding this line to your php file ``` ini_set('memory_limit', '44M'); ``` where `44M` is the amount you expect to be consumed. **However**, most of time this error message means that **the script is doing ...
Here are two simple methods to increase the limit on shared hosting: 1. If you have access to your PHP.ini file, change the line in PHP.ini If your line shows 32M try 64M: `memory_limit = 64M ; Maximum amount of memory a script may consume (64MB)` 2. If you don't have access to PHP.ini try adding this to an .hta...
Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php
[ "", "php", "memory-management", "memory-limit", "" ]
I got an error today while trying to do some formatting to existing code. Originally, the code had the `using` directives declared outside the namespace: ``` using System.Collections.Generic; namespace MyNamespace { using IntPair = KeyValuePair<int, int>; } ``` When I tried to insert the `using` directive inside ...
I used to think that it did not matter, but I always fully qualify using commands. Edit: Checked the [C# spec](http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx), section 9.4 says that: > The scope of a using-directive specifically does not include its peer using-directives. Thus, peer using-directives do not aff...
Yes, it does - to a small extent. There is an edge-case to do with scoping / local names, see [Eric Lippert's blog](http://blogs.msdn.com/ericlippert/archive/2007/06/25/inside-or-outside.aspx). For a concrete example (specific to alias usage): ``` using System; using Foo = Bar; public static class Bar { public s...
Does the location of the `using` directive make a difference in C#?
[ "", "c#", "syntax", "" ]
I have this class called Table: ``` class Table { public string Name { get { return this.wrapper.Eval(//some command); //wrapper is pass in by the ctor and is a COM object. } } } ``` which is used in this class: ``` class Map { public Map MapTable(Table ...
Beyond the fact that there is usually no *one* perfect testing solution, I'd first go for mocking the COM object: there should be a interface available and you'll probably want to test everything "above" it. If the `Table` contains non-trivial code (e.g. within the `Eval()`; anything with conditionals; or e.g. parsing...
**Yes** your sample looks fine, if you want to test the Map object you should be mocking the Table object. If you do it the other way around you will not test the Map constructor.
Should I create a interface and mock this class
[ "", "c#", "mocking", "" ]
There's a good discussion of Generics and what they really do behind the scenes over at [this question](https://stackoverflow.com/questions/31693/differences-in-generics), so we all know that `Vector<int[]>` is a vector of integer arrays, and `HashTable<String, Person>` is a table of whose keys are strings and values `...
Using the generified version of class Class allows you, among other things, to write things like ``` Class<? extends Collection> someCollectionClass = someMethod(); ``` and then you can be sure that the Class object you receive extends `Collection`, and an instance of this class will be (at least) a Collection.
All we know is "*All instances of a any class shares the same java.lang.Class object of that type of class*" e.g) ``` Student a = new Student(); Student b = new Student(); ``` Then `a.getClass() == b.getClass()` is true. Now assume ``` Teacher t = new Teacher(); ``` without generics the below is possible. ``` Cl...
How to use Class<T> in Java?
[ "", "java", "templates", "class", "generics", "" ]
Java `.class` files can be decompiled fairly easily. How can I protect my database if I have to use the login data in the code?
Never hard-code passwords into your code. This was brought up recently in the [Top 25 Most Dangerous Programming Mistakes](http://blog.codinghorror.com/top-25-most-dangerous-programming-mistakes/): > Hard-coding a secret account and > password into your software is > extremely convenient -- for skilled > reverse engin...
Put the password into a file that the application will read. NEVER embed passwords in a source file. Period. Ruby has a little-known module called [DBI::DBRC](https://rubygems.org/gems/dbi-dbrc) for such usage. I have no doubt that Java has an equivalent. Anyway, it is not difficult to write one.
How can I protect MySQL username and password from decompiling?
[ "", "java", "mysql", "security", "reverse-engineering", "decompiling", "" ]
*[The [only similar question](https://stackoverflow.com/questions/137933/what-is-the-best-scripting-language-to-embed-in-a-c-desktop-application) I can find was answered long ago and contains a reference to mostly IronPython. I want to consider other options as well]* We have a complex data analysis application writte...
I know the other question references [IronPython](http://www.codeplex.com/IronPython), but I still feel like it should be here because I think it's one of the best options. Another great option would be [IronRuby](http://www.ironruby.net/). The main difference I see would be if your developers/users had any experience...
[Boo](http://boo.codehaus.org) perhaps?
Scripting language for embedding into C#/.NET applications?
[ "", "c#", ".net", "scripting", "embed", "" ]
Say I have two script controls and one control has the other as a child control: ``` ParentControl : ScriptControl { ChildControl childControl; } ``` The script for the Child Control: ``` ChildControl = function(element) { ChildControl.initializeBase(this, [element]); } ChildControl.prototype = { callMeth...
On the client, you're using a field of your parent control object called \_childControlID by passing it into $get. There's a few problems with this: 1. How did \_childControlID get set? I would guess by adding it as a property in the parent control's descriptor on the server, but you don't show that code and you don't...
The problem is the "this." This, in javaScript, refers to the DOM object. You need to do something similar to what happens when you use Function.createDelegate, which is required when using $addHandler (which I know you're not using, just giving context).
ASP.Net ScriptControl - Call one method from another
[ "", "asp.net", "javascript", "ajax", "scriptcontrol", "extendercontrol", "" ]
I have an ASP.NET website (in C#) that takes in user data and then attempts to create a windows scheduled task. Of course, this works great on the DEV machine, but fails to run on the server. I'm trying to figure out what permission(s) are required on the ASPNET user (or anonymous web user) to create tasks. The error ...
I have been able to solve my particular problem, though not completely. I have still not identified the exact rights needed to create and run scheduled tasks, but the following seems to work: 1. Add the `<identity impersonate="true" />` to the Web.config 2. Add the IUSR user (which is the user the app will run as usin...
Instead of worrying about the ASPNET user permissions, would your internal process allow you to create a machine specific account and supply the credentials there?
.NET create scheduled task on server fails with E_ACCESSDENIED
[ "", "c#", ".net", "asp.net", "permissions", "scheduled-tasks", "" ]
Where would you place the SaveSettings method in your project when the user is done editing any settings on the Settings dialog in your program? Should it be in the return like: ``` using (frmSettings frmSettings = new frmSettings()) { if (frmSettings.ShowDialog() == DialogResult.OK) ...
``` // clicked OK, should I call SaveSettings() here? ``` That seems like a good place. =) EDIT: I suppose it depends on the framework of the application, but there's nothing wrong with putting it there. It's a logical (by all definitions of logic) place to put it.
Putting the save code in the calling form is, in my opinion, putting it in the incorrect place. Yes, it will work in this instance, but it means that the settings form is not reusable, and that any error in your save code will cause the settings form to dismount before you know of any errors. Additionally, if you add ...
C#: Where do you call your own save method after pressing OK on a Settings Dialog for your program?
[ "", "c#", "" ]
We have a C# application that connects to a FTP server, downloads some files, disconnects, and after a certain amount of time (selected by the user through the UI) reconnects and repeats the process. We implemented this using BackgroundWorker, but we noticed that after running for a longer time, the program stopped log...
If I'm understanding you correctly this `while(!stopped)` loop is the loop that is running for several hours? If that is the case, where are you terminating your ftp connection if anywhere? The only time you close it in the code you've posted is if an exception is thrown, otherwise you simply dereference the object and...
I would suggest putting anything that can go wrong in the catch block (in particular the bit which disconnects from the FTP server) in its own try/catch block. In addition, log something as soon as you've caught the exception, before doing anything else - that way you're more likely to be able to tell if the logging di...
Thread stops doing its job
[ "", "c#", "multithreading", "backgroundworker", "" ]
When I extract files from a ZIP file created with the Python [`zipfile`](http://docs.python.org/library/zipfile.html) module, all the files are not writable, read only etc. The file is being created and extracted under Linux and Python 2.5.2. As best I can tell, I need to set the `ZipInfo.external_attr` property for ...
This seems to work (thanks Evan, putting it here so the line is in context): ``` buffer = "path/filename.zip" # zip filename to write (or file-like object) name = "folder/data.txt" # name of file inside zip bytes = "blah blah blah" # contents of file inside zip zip = zipfile.ZipFile(buffer, "w", zipfile.Z...
[This link](http://trac.edgewall.org/attachment/ticket/8919/ZipDownload.patch) has more information than anything else I've been able to find on the net. Even the zip source doesn't have anything. Copying the relevant section for posterity. This patch isn't really about documenting this format, which just goes to show ...
How do I set permissions (attributes) on a file in a ZIP file using Python's zipfile module?
[ "", "python", "attributes", "zip", "file-permissions", "python-zipfile", "" ]
I have a Drupal module page where I am populating a form with a drop-down that contains a list of available parts of a set of files that the user can upload. Once the user uploads a file of a certain type, it removes that option from the list, and when all the available files are uploaded the form will not be rendered....
You modify your form so that it saves some information on the state of the form. Then you add a new case to the beginning of the submit function that returns immediately if you're not done uploading all the files, and it will redraw the form. ``` function modulename_uploader_form(&$form_stuff=null) { //the function th...
Setting $form\_state['redirect'] in your submit handler will just cause the form to reload, fresh, without the old data. It's a way of clearing out the form so that old values don't hang around as defaults. You probably want to use $form\_state['rebuild'], which gives your form-building functions an opportunity to reb...
Drupal form being rendered before submit action
[ "", "php", "drupal", "drupal-6", "drupal-fapi", "" ]
I have a 100 classes that have some similar elements and some unique. I've created an interface that names those similar items eg: interface IAnimal. What i would normally do is: ``` class dog : IAnimal ``` But there are 100 classes and i don't feel like going though them all and looking for the ones that i can apply...
You might solve this problem with **partial classes**: let the machine-generated/regenerated code be in one source file of each class, and the hand-coded part (defining the subclassing from IAnimal) in another.
What you are asking for is called duck typing and is not part of C# I am afraid. Any solution will involve reflection and looking at the properties, It will be quicker to check the classes by hand I think. It would be an interesting project to try though.
Treat a class as if it was defined with an interface
[ "", "c#", "casting", "interface", "enumeration", "" ]
What is the latest version of gcc that still uses libstdc++.so.5 (as opposed to libstdc++.so.6)?
After searching all over for the answer, and failing to find it. I compiled several different versions and the last version to use libstdc++.so.5 is version 3.3 (more specifically 3.3.6). Version 3.4.X uses libstdc++.so.6.
In the [Gnu ABI policy](http://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html "Gnu ABI Policy"), you can find this: * ... * gcc-3.3.3: libstdc++.so.5.0.5 * gcc-3.4.0: libstdc++.so.6.0.0 (Incompatible with previous) * ... So unless they didn't list a version, gcc-3.3.3 is the one you want.
The latest version of gcc to use libstdc++.so.5
[ "", "c++", "gcc", "libstdc++", "" ]
I want to limit a report to return records from Date A through Date B. This is what I have been doing: ``` declare @startDate varchar(20) declare @endDate varchar(20) set @startDate = '01/01/2008' set @endDate = '04/01/2008' -- test what are the start and end dates select min(date),max(date) from view_Inspections whe...
There's always the easy option: ``` declare @startDate varchar(20) declare @endDate varchar(20) set @startDate = '01/01/2008' set @endDate = '04/01/2008' -- test what are the start and end dates select min(date),max(date) from view_Inspections where date >= @startDate and date < @endDate ```
I suspect that the date column in view\_Inspections is a SmallDateTime data type. This data type has 1 minute accuracy, which explains your unexpected results (rounding the seconds to the nearest minute). The method Roland Shaw suggests is the best way to modify your query to accommodate your requirements.
Limiting a date range with exactness in MS SQL / SQL Server 2005
[ "", "sql", "datetime", "rounding", "date-range", "" ]
If i create a program, which in one small out of the way area, uses Excel automation: will the application fail when Excel is needed or will the application fail to start? --- ## Update Let me ask the same question, but in a more drawn out way: Will the application be usable by * > 99.9% of the users who never u...
The code will properly execute until it tries to make a call to the automation libraries, at that time it will generate an exception.
I have an app that uses Excel automation and I can definitively say that it will fail at runtime, not at load time. In fact we check to see if it's even installed and only show the "Show data in Excel" button if we find it (but the PIAs are deployed to all installs).
.NET: If my .NET automates Office, does the customer have to have Office installed?
[ "", "c#", "com", "ms-office", "" ]
I moved a typed dataset from one project to an ASP Web Application project. I put the typed dataset into one of the existing directories as it was in the App\_Code directory of the previous site but don't see the option to create that asp.net folder in this project. Now, when I try to instantiate the typed dataset, th...
You may need to re-gen the DataSet. When you move the .xsd, you've only moved the xml layout of the DataSet. Delete any generated code file, open the xsd, move something, and then save it. The save operation calls the generator. Or you can right-click on the .xsd file and call the generator directly.
I moved my web site to a Web Application Project and experienced the same issues. I took the approach mentioned in the first answer and was able to get the project to compile eventually. I would like to add a little more detail to the first answer. To be explicit: I first deleted all of the files associated with the x...
Typed dataset not recognized when moved to another project
[ "", "c#", "asp.net", "ado.net", "dataset", "strongly-typed-dataset", "" ]