Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
How can I hook up an event to a function name I have defined as a string? I'm using Prototype.js, although this is not Prototype-speficic. ``` $(inputId).observe('click', formData.fields[x].onclick); ``` This would result in JavaScript complaining that my handler is not a function. I would prefer not us use `eval()`...
[Property accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) can be used to access any object's properties or functions. If the function is in the global scope, you can get it using the window object: ``` var myFunc = window[myFuncName]; ``` This also works wit...
I have worked on this problem, as I needed a function like this. Here is my sandbox code, not thoroughly tested, but can be a startpoint for others. Note that there is one eval() in the code as I couldn't figure out how to bypass that step, maybe a javascript quirk and cannot be done in any other way. Let me know if th...
Call a JavaScript function name using a string?
[ "", "javascript", "" ]
I'm somewhat new to the ASP.NET MVC architecture and I'm trying to sort out how I could return multiple sets of data to the view. ``` public ActionResult Index(string SortBy) { var actions = from a in dbActions.Actions orderby a.action_name ascending ...
You could pass them through ViewData, an object that is passed from the controller to the view. The controller would look like this: ``` ViewData["ActionList"] = actions.ToList(); ``` Retrieving it in the view: ``` <% foreach (var action in (List)ViewData["ActionList"]) %> ```
ViewData as described above is the quick way. But I beleieve it makes more sense to wrap the lists in a single object model which you then pass to the View. You will also get intellisense...
Returning Multiple Lists in ASP.NET MVC (C#)
[ "", "c#", "asp.net-mvc", "" ]
What is a good javascript (book or site) that is not just focused on syntax but does a good job explaining how javascript works behind the scenes? Thanks!
If you don't want a book that starts with explaining JavaScript syntax, then: * Watch the **video lectures of Douglas Crockford** in [YUI Theater](http://developer.yahoo.com/yui/theater/): + [The JavaScript Programming Language](http://video.yahoo.com/video/play?vid=111593), + [Advanced JavaScript](http://video.y...
The [JavaScript resources at the Mozilla Developer Center](https://developer.mozilla.org/en/JavaScript) are pretty nice. They have a [guide to JavaScript](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide) as well as a a [reference](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference). The guide is...
Good javascript reference
[ "", "javascript", "" ]
Is a ``` select * from myView ``` faster than the query itself to create the view (in order to have the same resultSet): ``` select * from ([query to create same resultSet as myView]) ``` ? It's not totally clear to me if the view uses some sort of caching making it faster compared to a simple query.
**Yes**, views *can* have a clustered index assigned and, when they do, they'll store temporary results that can speed up resulting queries. Microsoft's own documentation makes it very clear that Views can improve performance. First, most views that people create are *simple* views and do not use this feature, and ar...
**Generally speaking, no.** Views are primarily used for convenience and security, and won't (by themselves) produce any speed benefit. That said, SQL Server 2000 and above do have a feature called **Indexed Views** that *can* greatly improve performance, with a few caveats: 1. Not every view can be made into an inde...
Is a view faster than a simple query?
[ "", "sql", "sql-server", "performance", "" ]
I am testing a simple query to get data from an AS400 database. **I am not sure if the way I am using the SQL query is correct.** I get an error: "The parameter is incorrect." ``` Select FIELD1, FIELD2 From Mylibrary.MyTable WHERE FIELD1 = @Field1 ``` I don't get an error when I run the following query: ``` Select ...
Ok, I got the solution by playing around and trying different things. As I said before, I am used to OLEDB and ADO.Net so I am used to doing things like: ``` Select FIELD1, FIELD2 From Mylibrary.MyTable WHERE FIELD1 = @Field1 ``` which work in Access and SQL Server but not in AS/400. I got the following to work: `...
If you're going to connect to the AS400 using .NET, first of all you should use the [IBM.Data.DB2.iSeries](http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=/rzaik/rzaikdotnetprovider.htm) .NET provider from IBM. According IBM's [documentation](http://www.redbooks.ibm.com/abstracts/sg246440.html), t...
AS400 SQL query with Parameter
[ "", "sql", "ibm-midrange", "" ]
Surely there is a better way to do this? ``` results = [] if not queryset is None: for obj in queryset: results.append((getattr(obj,field.attname),obj.pk)) ``` The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I just want result to be set...
``` results = [(getattr(obj, field.attname), obj.pk) for obj in queryset or []] ```
How about ``` for obj in (queryset or []): # Do your stuff ``` It is the same as J.F Sebastians suggestion, only not implemented as a list comprehension.
Refactor this Python code to iterate over a container
[ "", "python", "django", "refactoring", "iterator", "" ]
I am writing a GAE application and am having some difficulty with the following problem. I've created multiple python files (say a.py and b.py) which are both stored in the same folder. I am able to call code in a.py or b.py by mapping URL's to them (using app.yaml). What I haven't figured out how to do is import the ...
Have you tried importing as if you were starting at the top level? Like ``` import modules.b ```
If the files a.py and b.py aren't located, be sure to include the respective paths in `sys.path`. ``` import sys sys.path.append(r"/parent/of/module/b") ```
Google App Engine - Importing my own source modules (multiple files)
[ "", "python", "google-app-engine", "" ]
I'm trying to parse a date/time string using `DateTime.ParseExact`. It works everywhere, except on one machine - it just will not parse on that machine. The question is: Why? What could be different on that machine so that it will cause this behaviour? Here are some things that I've already looked at: * The `CultureI...
I always find that regional settings can be tricky, and you can never assume that the users of your application will even have their machines setup correctly in the first place! A catch-all that I've been using to parse dates in if they have to be strings is to parse it in the "dd/MMM/yyyy" format, e.g. "14/JAN/2009" ...
It's really hard to guess what the solution could be without exception information (which Marc Gravell asked about) and/or some sample code. In my experience, i've had problems with date/times because of cultural issues. You've said you've already had a go at hard-coding that. what about the actual culture the proces...
Unable to parse a DateTime
[ "", "c#", "datetime", "parsing", "settings", "date", "" ]
I keep getting this error ever so often when I launch the debugger to debug my site. I'm using the Telerik controls, and usually the error is in my tab strip. Here is an example of the error I'm looking at right now: ``` Compiler Error Message: CS0433: The type 'ASP.controls_motorvehiclegeneral_ascx' exists in both 'c...
killing Cassini instances as above didn't work for me. [ScottGu posted about this issue](http://weblogs.asp.net/scottgu/public-hotfix-patch-available-for-asp-net-compilation-issues) setting the batch="false" attribute on the compilation section in web.config worked for me. ``` <configuration> <system.web> ...
For me, closing the IDE, shutting the web site (IIS or Cassini), deleting all of my temporary asp.net files, launching the IDE and doing a full compile does the trick.
Compile Error CS0433 on pre-compiled ASP.NET 2.0 site
[ "", "c#", "asp.net", "compiler-construction", "asp.net-2.0", "telerik", "" ]
I'm looking to make a recursive method iterative. I have a list of Objects I want to iterate over, and then check their subobjects. Recursive: ``` doFunction(Object) while(iterator.hasNext()) { //doStuff doFunction(Object.subObjects); } ``` I want to change it to something like this ``` doFunction(Object) iI...
I would use two data structures --- a **queue** (e.g. [`ArrayDeque`](http://java.sun.com/javase/6/docs/api/java/util/ArrayDeque.html)) for storing objects whose subobjects are to be visited, and a **set** (e.g. [`HashSet`](http://java.sun.com/javase/6/docs/api/java/util/HashSet.html)) for storing all visited objects wi...
I think your problem is inherently a problem that needs to be solved via a List. If you think about it, your Set version of the solution is just converting the items into a List then operating on that. Of course, List.contains() is a slow operation in comparison to Set.contains(), so it may be worth coming up with a h...
Modifying a set during iteration java
[ "", "java", "iterator", "hashset", "" ]
I have a python script that can approach the 2 GB process limit under Windows XP. On a machine with 2 GB physical memory, that can pretty much lock up the machine, even if the Python script is running at below normal priority. Is there a way in Python to find out my own process size? Thanks, Gerry
try: ``` import win32process print win32process.GetProcessMemoryInfo(win32process.GetCurrentProcess()) ```
By using psutil <https://github.com/giampaolo/psutil> : ``` >>> import psutil, os >>> p = psutil.Process(os.getpid()) >>> p.memory_info() meminfo(rss=6971392, vms=47755264) >>> p.memory_percent() 0.16821255914801228 >>> ```
Process size in XP from Python
[ "", "python", "windows-xp", "" ]
I'm developing an ASP.NET 2.0 app using Visual Studio 2008. If I want to run a really quick test on a method that's way in my back-end, is there a way for me to just call a main function in that class via command line? Thanks
The answer is no, You cannot do that. You can only have one main function per assembly. The fact is, you shouldn't do testing like that. C# is not Java, regardless of its origin in Java. Use NUnit or MSUnit and build unit tests instead. They'll test your methods for you without needing deployment to a website or anyt...
Short answer: [NUnit](http://www.nunit.org/). You may not know how to use it, but you should. It's not hard to use and learn. It's fast and has a GUI.
How to run a C# main in an ASP.NET app
[ "", "c#", "asp.net", "testing", "" ]
I have a simple html block like: ``` <span id="replies">8</span> ``` Using jquery I'm trying to add a 1 to the value (8). ``` var currentValue = $("#replies").text(); var newValue = currentValue + 1; $("replies").text(newValue); ``` What's happening is it is appearing like: 81 then 811 not 9, which would be the...
parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion. ``` var currentValue = parseInt($("#replies").text(),10); ``` The second paramter (radix) makes sure it is parsed as a decimal number.
Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used ``` var currentValue = parseInt($("#replies").text(),10); ```
How do I add an integer value with javascript (jquery) to a value that's returning a string?
[ "", "javascript", "jquery", "casting", "" ]
I want to implement an atomic transaction like the following: ``` BEGIN TRAN A SELECT id FROM Inventory WITH (???) WHERE material_id = 25 AND quantity > 10 /* Process some things using the inventory record and eventually write some updates that are dependent on the fact that that specific inventory record had suffic...
You may actually be better off setting the transaction isolation level rather than using a query hint. The following reference from Books Online provides details of each of the different Isolation levels. <http://msdn.microsoft.com/en-us/library/ms173763.aspx> Here is good article that explains the various types of ...
[table hints](http://msdn.microsoft.com/en-us/library/ms187373(SQL.90).asp) `WITH (HOLDLOCK)` allows other readers. UPDLOCK as suggested elsewhere is exclusive. HOLDLOCK will prevent other updates but they may use the data that is updated later. UPDLOCK will prevent anyone reading the data until you commit or rollba...
Which lock hints should I use (T-SQL)?
[ "", "sql", "sql-server", "t-sql", "concurrency", "locking", "" ]
What is [`__init__.py`](https://docs.python.org/3/tutorial/modules.html#packages) for in a Python source directory?
It used to be a required part of a package ([old, pre-3.3 "regular package"](https://docs.python.org/3/reference/import.html#regular-packages), not [newer 3.3+ "namespace package"](https://docs.python.org/3/reference/import.html#namespace-packages)). [Here's the documentation.](https://docs.python.org/3/reference/impo...
Files named `__init__.py` are used to mark directories on disk as Python package directories. If you have the files ``` mydir/spam/__init__.py mydir/spam/module.py ``` and `mydir` is on your path, you can import the code in `module.py` as ``` import spam.module ``` or ``` from spam import module ``` If you remove...
What is __init__.py for?
[ "", "python", "module", "package", "python-packaging", "" ]
I have an class which has a enum property and a boolean property, based on that it calls a specific method with specific parameters. I use a switch statement for the enum and an if for the boolean within each case of the switch. It is a long list and doesn't feel to me to be the most elegant solution. Anyone got a more...
An often used convention is that a timeout of zero means no timeout. Maybe you could drop the UseTimeout (property?) and use the value zero instead. That'd eliminate some stuff.
Depending on what `queue` is, could you change the signature of `Peek()` and `Peek(bool)` to `Peek(bool?)`? (The rest of the methods should follow as well.) That way, instead of: ``` if (UseTimeout) { Message = queue.Peek(Timeout); } else { Message = queue.Peek(); } ``` you could have: ``` Message = queue.P...
C# enums and booleans - looking for a more elegant way
[ "", "c#", "enums", "" ]
I have a relatively simple select statement in a VB6 program that I have to maintain. (Suppress your natural tendency to shudder; I inherited the thing, I didn't write it.) The statement is straightforward (reformatted for clarity): ``` select distinct b.ip_address from code_table a, location b where ...
Some random ideas: * Are you sure you committed the changes that invalidate the ip-address? Can someone else (using another db connection / user) see the changed code\_status? * Are you sure that the results are not modified after they are returned from the database? * Are you sure that you are using the "same" databa...
In addition to the suggestions that IronGoofy has made, have you tried swapping round the last two clauses? ``` where a.code_item = b.wich_id and a.code_status = 'R' and a.location_type_code = '15' ``` If you get a different set of results then this might point to some sort of wrangling going on that results...
Oracle9i: Filter Expression Fails to Exclude Data at Runtime
[ "", "sql", "oracle", "" ]
I've been going over and over this in my head, and I can't seem to come up with a good reason why C# closures are mutable. It just seems like a good way to get some unintended consequences if you aren't aware of exactly what's happening. Maybe someone who is a little more knowledgeable can shed some light on why the d...
C# and JavaScript, as well as O'Caml and Haskell, and many other languages, have what is known as *lexical closures*. This means that inner functions can access the *names* of local variables in the enclosing functions, not just copies of the *values*. In languages with immutable symbols, of course, such as O'Caml or H...
Not all closures behave the same. There are [differences in semantics](http://en.wikipedia.org/wiki/Closure_(computer_science)#Differences_in_semantics). Note that the first idea presented matches C#'s behavior... your concept of closure semantics may not be the predominate concept. As for reasons: I think the key he...
Are there any good reasons why closures aren't immutable in C#?
[ "", "c#", "closures", "mutable", "" ]
How do you find which SPs are declared WITH RECOMPILE, either in INFORMATION\_SCHEMA, sys.objects or some other metadata? (I'm adding some code to my system health monitoring and want to warn on ones which are declared that way where it is not justifiable.) **Note: I'm not looking for general text search for 'WITH RE...
Thanks to [GSquared](http://www.sqlservercentral.com/Forums/UserInfo480409.aspx) on [SQL Server Central Forums](http://www.sqlservercentral.com/Forums/Topic634987-338-1.aspx), I found it, there is a flag called `is_recompiled` in `sys.sql_modules`.
For a quick and dirty way I would use: ``` SELECT o.name FROM syscomments c INNER JOIN sys.objects o ON o.object_id = c.id WHERE c.text LIKE '%WITH RECOMPILE%' ``` That's probably not a good idea for use in an actual application though. If I have a few minutes I'll try to dig up a cleaner way. The...
How to find WITH RECOMPILE metadata in SQL Server (2005)?
[ "", "sql", "sql-server", "metadata", "" ]
In Java, an array IS AN Object. My question is... is an Object constructor called when new arrays is being created? We would like to use this fact to instrument Object constructor with some extra bytecode which checks length of array being constructed. Would that work?
As far as the Java Language Specification is concerned, although both use the `new` keyword, [Class Instance Creation Expressions](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.9) and [Array Creation Expressions](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.10.1) are differe...
Per the [JVM spec](http://java.sun.com/docs/books/jvms/second_edition/html/Compiling.doc.html#4091): "Arrays are created and manipulated using a distinct set of instructions." So, while arrays are instances of Objects, they aren't initialized the same way that other objects are (which you can see if you scroll up from ...
Is Object constructor called when creating an array in Java?
[ "", "java", "arrays", "object", "instrumentation", "construction", "" ]
I'm looking for a good way to do a vertical wrap. My goal is to fit a list of checkboxes into a div. I have the checkboxes sorted alphabetically, and I want the list to flow from the top of the div to the bottom and then begin again in a new column when they reach the bottom. Right now, I can do this by breaking the li...
I ended up using a little server-side preprocessing. This site, and this particular page, ended up needing a fair amount of preprocessing anyway, and I don't expect the size of the data to get too huge.
I'd use [CSS3 columns](http://www.w3.org/TR/css3-multicol/). However, only WebKit (Safari, Chrome, ...) and Gecko (Firefox, ...) have implemented it so far, and you'll have to add their respective vendor prefixes (`-moz-column-width:...; -webkit-column-width:...;`) for it to work. If IE *has* to get columns, floated d...
Vertical Wrapping in HTML
[ "", "javascript", "html", "css", "" ]
This problem involved me not knowing enough of C++. I am trying to access a specific value that I had placed in the Heap, but I'm unsure of how to access it. In my problem, I had placed a value in a heap from a data member function in an object, and I am trying to access it in another data member function. Problem is I...
pValue needs to be a member-variable of the class Grid. ``` class Grid { private: int* pValue; public: void HeapValues(); void AccessHeap(); }; ``` Now the member-variable pValue is accessible from any member-function of Grid.
Don't forget to delete your pointer in the destructor when you are done. For more information visit: * <http://www.cplusplus.com/doc/tutorial/variables.html> <-- Variable scope * <http://www.cplusplus.com/doc/tutorial/pointers.html> <-- Pointers * <http://www.cplusplus.com/doc/tutorial/dynamic.html> <-- Dynamic memory
C++ Accessing the Heap
[ "", "c++", "heap-memory", "data-access", "" ]
I'm trying to use Spring IoC with an interface like this: ``` public interface ISimpleService<T> { void someOp(T t); T otherOp(); } ``` Can Spring provide IoC based on the generic type argument T? I mean, something like this: ``` public class SpringIocTest { @Autowired ISimpleService<Long> longSvc; ...
I do not believe this is possible due to erasure. We generally switched to strongly typed sub-interfaces when going for full-autowiring: ``` public interface LongService extends ISimpleService<Long> {} public interface StringService extends ISimpleService<String> {} ``` Upon doing this switch we found we actually lik...
i don't think thats possible without Qualifier ill try to show my Solutions with a genericDAO, sorry if it's a bit detailed the Interface and Implementation Class Definition ``` public interface GenericDAO<T, ID extends Serializable> (...) public class GenericDAOImpl<T, ID extends Serializable> implements Gener...
Spring IoC and Generic Interface Type
[ "", "java", "spring", "inversion-of-control", "types", "generics", "" ]
How do I expand/collapse an html field in Firefox? I incorporated a few JavaScript examples from the web, but they only worked in IE. (I'm limited to HTML and JS) Suggestions are appreciated. Thanks. Yes, I would like to show/hide divs and such.
If your input field has an ID attribute, you can use CSS to style it as needed. I recommend using a library like jQuery, but I have provided an example without as well: ``` // hiding without jQuery document.getElementById('myInput').style.display = 'none' // showing without jQuery document.getElementById('myIn...
What you probably want to do is change css property [display](http://www.w3schools.com/css/pr_class_display.asp) of the element to "none" to hide the element and change it back to "block" or "inline" to show it again. It can be done with javascript. If you want a fancy animation, you could use some kind of [javascript...
expand collapse html field Firefox
[ "", "javascript", "html", "firefox", "" ]
How can I test if a RegEx matches a string *exactly*? ``` var r = /a/; r.test("a"); // returns true r.test("ba"); // returns true testExact(r, "ba"); // should return false testExact(r, "a"); // should return true ```
Either modify the pattern **beforehand** so that it only matches the entire string: ``` var r = /^a$/ ``` or check **afterward** whether the pattern matched the whole string: ``` function matchExact(r, str) { var match = str.match(r); return match && str === match[0]; } ```
Write your regex differently: ``` var r = /^a$/; r.test('a'); // true r.test('ba'); // false ```
Matching exact string with JavaScript
[ "", "javascript", "regex", "" ]
I would like to find out, in JavaScript, which element currently has focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this, and how? The reason I was looking for this: I'm trying to make keys like the arrows and `enter` navigate through a table of input elements. Tab w...
Use [`document.activeElement`](https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement), it is supported in all major browsers. Previously, if you were trying to find out what form field has focus, you could not. To emulate detection within older browsers, add a "focus" event handler to all fields and ...
As said by JW, you can't find the current focused element, at least in a browser-independent way. But if your app is IE only (some are...), you can find it the following way: ``` document.activeElement ``` It looks like IE did not have everything wrong after all, this is part of HTML5 draft and seems to be supported ...
How do I find out which DOM element has the focus?
[ "", "javascript", "dom", "" ]
I'm creating an AIR application which connects to a SQLite database. The database balks at this insert statement, and I simply cannot figure out why. There is no error, it simply does not move on. ``` INSERT INTO Attendee (AttendeeId,ShowCode,LastName,FirstName,Company,Address,Address2,City,State,ZipCode,Country,Phone...
``` insert into Attendee ("AttendeeId", "ShowCode", "LastName", "FirstName", "Company", "Address", "Address2", "City", "State", "ZipCode", "Country", "Phone", "Fax", "Email", "BuyNum", "PrimaryBusiness", "Business", "Employees", "Job", "Value", "Volume", "SpouseBusiness", "DateAdded", "ConstructionWorkType", "UserPurch...
Have you tried running smaller statements? Like, a really simple INSERT on a really simple table? Have you tried quoting the column names? Maybe one of them is a reserved word.
What is wrong with this SQLite query?
[ "", "sql", "flash", "actionscript-3", "sqlite", "air", "" ]
Is it possible to trigger an action in Windows Service, or is it possible to raise an event that can be caught in a Service from a stored procedure. If you imagine a service runs every 5 minutes thats performs some action. What if something happens in a database or a stored procedure is executed and I want to trigger ...
Following on from Mehrdad's comments, I was able to solve the problem using the SqlDependancy Class in the .NET framework. This Class allows you to register a SQL query and connection with it, when the result of that query changes an event is raised to indicate a change in the data. This allowed me to catch data chan...
It sounds like you shouldn't be using a windows service at all. I'd setup a SQL job to run every 5 minutes, then setup a trigger or whatever you expect to happen to run the job manually if necessary. EDIT: However, if the service is doing something outside of the database, you can use xp\_cmdshell to run system comman...
Raise Event from store procedure to Windows Service
[ "", "c#", "sql-server", "clr", "" ]
I have a website with a contact form. User submits name, email and message and the site emails me the details. Very occasionally my server has a problem with it's email system and so the user gets an error and those contact details are lost. (Don't say: get a better server, any server can have email go down now and th...
When we implement email sending functionality in our environment we do it in a decoupled way. So for example a user would submit their data which would get stored in a database. We then have a separate service that runs, queries the database and sends out email. That way if there are ever any email server issues, the s...
try [sqlite](http://www.sqlite.org/). It has default [python bindings](http://docs.python.org/library/sqlite3.html) in the standard library and should work for a useful level of load (or so I am told)
Ensuring contact form email isn't lost (python)
[ "", "python", "email", "race-condition", "data-formats", "" ]
In Perl, I can replicate strings with the 'x' operator: ``` $str = "x" x 5; ``` Can I do something similar in Python?
``` >>> "blah" * 5 'blahblahblahblahblah' ```
Here is a reference to the official Python3 docs: <https://docs.python.org/3/library/stdtypes.html#string-methods> > Strings implement all of the [*common*](https://docs.python.org/3/library/stdtypes.html#typesseq-common) sequence operations... ... which leads us to: <https://docs.python.org/3/library/stdtypes.html...
Is there a Python equivalent of Perl's x operator (replicate string)?
[ "", "python", "perl", "replicate", "" ]
I'd like to populate the homepage of my user-submitted-illustrations site with the "hottest" illustrations uploaded. Here are the measures I have available: * How many people have favourited that illustration + `votes` table includes date voted * When the illustration was uploaded + `illustration` table has date ...
Many sites that use some type of popularity ranking do so by using a standard algorithm to determine a score and then decaying eternally over time. What I've found works better for sites with less traffic is a multiplier that gives a bonus to new content/activity - it's essentially the same, but the score stops changin...
Obviously there is some subjectivity in this - there's no one "correct" algorithm for determining the proper balance - but I'd start out with something like votes per unit age. MySQL can do basic math so you can ask it to sort by the quotient of votes over time; however, for performance reasons, it might be a good idea...
Popularity Algorithm
[ "", "php", "mysql", "algorithm", "" ]
I'd like to be able to call "getProgram" on objects which have that method, without knowing which class they belong to. I know I should use an interface here, but I'm working with someone else's code and can't redesign the classes I'm working with. I thought BeanUtils.getProperty might help me, but it seems it only ret...
Presumably you have a finite number of classes implementing this method, and you can link to them directly. So you don't need reflection. Reflection is evil. Say you have a set of classes with the method: ``` public class LibA { public Program getProgram() { return program; } ... }; public class LibB { public Program...
Use PropertyUtils (from apache commons-beanutils) instead of BeanUtils. It has a getProperty(Object bean, String name) method that returns an Object instead of a String. See the [JavaDoc](http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/PropertyUtils.html) for more information.
getting a property of a java bean of unknown class
[ "", "java", "javabeans", "" ]
I'm sure that almost everyone programming in .net has ran into similar issues with the dynamic creation of buttons.. Example scenario.. I have a gridview and in one of the gridview fields I have a button. Normally in .net using visual studio you can easily grab the click event of the button, however since these butto...
Sadly, the answer was much simpler than I ever thought.. I didn't realize that the ItemCommand event was usable for buttons created in a TemplateField. All I really had to do was.. ``` Private Sub GridView1_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewCommandEventArgs) Handles ...
In the gridview, there is an event called [RowDatabound](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx). Put an event handler on that: > ``` > gv.RowDataBound += new EventHandler(rowBound); > ``` Now inside that function, you'll use FindControl to locate the button and a...
.net development dynamically created controls need their own methods
[ "", "asp.net", "javascript", "code-behind", "server-side", "" ]
For two threads manipulating a container map for example, what the correct way to test whether an iterator still valid (for performance reason) ? Or would be of only indirect way that this can be done. The sample code for this : ``` #define _SECURE_SCL 1 //http://msdn2.microsoft.com/en-us/library/aa985973.aspx #defi...
`std::map`s are not at all thread-safe. You'll end up with much worse problems than invalidated iterators, if you have more than one thread at a time modifying the same map. I don't even think you have a guarantee that you can read anything out of a map while it's being modified by another thread. Some pages on the ST...
If your STL does not offer a thread safe `std::map`, [Intel's TBB offers a thread-safe `concurrent_hash_map`](http://softwarecommunity.intel.com/isn/downloads/softwareproducts/pdfs/301114.pdf) (pages 60 and 68). Putting thread safety issues aside, `std::map` *does* guarantee that deletions do not invalidate iterators ...
Is there any way to check if an iterator is valid?
[ "", "c++", "performance", "stl", "iterator", "" ]
Why should I use templating system in PHP? The reasoning behind my question is: PHP itself is feature rich templating system, why should I install another template engine? The only two pros I found so far are: 1. A bit cleaner syntax (sometimes) 2. Template engine is not usually powerful enough to implement business...
Yes, as you said, if you don't force yourself to use a templating engine inside PHP ( the templating engine ) it becomes easy to slip and stop separating concerns. **However**, the same people who have problems separating concerns end up generating HTML and feeding it to smarty, or executing PHP code in Smarty, so Sma...
The main reason people use template systems is to separate logic from presentation. There are several benefits that come from that. Firstly, you can hand off a template to a web designer who can move things around as they see fit, without them having to worry about keeping the flow of the code. They don't need to unde...
Why should I use templating system in PHP?
[ "", "php", "smarty", "template-engine", "" ]
As a "learn Groovy" project, I'm developing a site to manage my media collection (MP3, MP4, AVI, OGG) and I wasn't able to find any open source library to retrieve meta data from this files. I was thinking of something like Linux's file command. I've found few libraries on Java that do one or the other (like mp3info), ...
You can try [Entagged](http://entagged.sourceforge.net/) Library for getting metadata from media files
If you're willing to exec an external process, [ExifTool](http://www.sno.phy.queensu.ca/~phil/exiftool/) can extract metadata from just about every file format ever invented. Dispite the name, it can pull metadata from more than just jpgs with exif tags.
Media analysis java library
[ "", "java", "groovy", "media", "analysis", "" ]
I'm writing a script that has to move some file around, but unfortunately it doesn't seem `os.path` plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory: [![alt text](https://i.stack.imgur.com/ypP2Z.png)](https://i.stack.im...
Hmm, after [some digging](http://www.amk.ca/python/howto/unicode) it appears that when supplying os.listdir a unicode string, this kinda works: ``` files = os.listdir(u'test_source') for f in files: pf = os.path.join(u'test_source', f) print pf.encode('ascii', 'replace'), os.path.exists(pf) ``` ===> ``` te...
It looks like a Unicode vs ASCII issue - `os.listdir` is returning a list of ASCII strings. Edit: I tried it on Python 3.0, also on XP SP2, and `os.listdir` simply omitted the Hebrew filenames instead of listing them at all. According to the docs, this means it was unable to decode it: > Note that when os.listdir() ...
Python's os.path choking on Hebrew filenames
[ "", "python", "internationalization", "hebrew", "" ]
I'm gettting the following exception when performing an insert to an Oracle Databse using JDBC. ``` java.sql.SQLRecoverableException: Io exception: Unexpected packet ``` What could cause this and how can I recover from it? The application I'm writing performs an aweful lot of updates the the databse in rapid success...
Are you per any chance using multiple threads and forgot synchronization?
Sounds like a driver problem, is there an updated driver for the server version you're using? Also, make sure you don't have older versions of the ojdbc jar in your classpath.
Can someone explain this JDBC Exception to me?
[ "", "java", "oracle", "exception", "jdbc", "" ]
I'm doing some performance tuning on my application and would like to know a good way of measuring the size of the object that I am sending over RMI. The aim is to make my object leaner.
the easiest way to do this is to put in some test code which writes the object to a file. then, look at the size of the file. or, if you don't want to write to disk (and your objects are not going to blow out memory): ``` ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOut...
Because your object is serializable already - you can use the size() method on ObjectOutputStream to do this.
How can I measure the size of the object I send over RMI?
[ "", "java", "performance", "rmi", "" ]
I'm trying to perform a *group by* action on an aliased column (example below) but can't determine the proper syntax. ``` SELECT LastName + ', ' + FirstName AS 'FullName' FROM customers GROUP BY 'FullName' ``` What is the correct syntax? Extending the question further (I had not expected the answer...
You pass the expression you want to group by rather than the alias ``` SELECT LastName + ', ' + FirstName AS 'FullName' FROM customers GROUP BY LastName + ', ' + FirstName ```
This is what I do. ``` SELECT FullName FROM ( SELECT LastName + ', ' + FirstName AS FullName FROM customers ) as sub GROUP BY FullName ``` --- This technique applies in a straightforward way to your "edit" scenario: ``` SELECT FullName FROM ( SELECT CASE WHEN LastName IS NULL THEN FirstName ...
How do I perform a GROUP BY on an aliased column in SQL Server?
[ "", "sql", "sql-server", "t-sql", "syntax", "" ]
Could somebody please elaborate on the differences?
The difference is that (int)foo can mean half a dozen different things. It might be a static\_cast (convert between statically known types), it might be a const\_cast (adding or removing const-ness), or it might be a reinterpret\_cast (converting between pointer types) The compiler tries each of them until it finds on...
Look at what [Stroustrup has to say about that](http://www.stroustrup.com/bs_faq2.html#static-cast), including the following: > Because the C-style cast (T) can be used to express many logically different operations, the compiler has only the barest chance to catch misuses. [...] > > The "new-style casts" were introdu...
static_cast<int>(foo) vs. (int)foo
[ "", "c++", "casting", "" ]
I need to create a demo version of an existing large application consisting of multiple projects. I'd like to use the existing projects, and just neuter the functionality via preprocessor directives ``` #if DEMO mycode.NeuterNow(); #endif ``` We are building our app using MSBuild, and I'd ideally use something al...
[That's a duplicate of this one](https://stackoverflow.com/questions/479979/), and yes, /p:DefineConstants does work fine, and configurator is right, this will override ALL conditional symbols already defined in the Project File (which is good IMHO), so you'll have to define them all.
Try ``` msbuild /p:DefineConstants=DEBUG;DEMO MySolution.sln ``` You have to include DEBUG or RELEASE and any other constants already defined in the solution file, but I think this should work. Disclaimer: I've never actually tried it myself.
Define a preprocessor value from command line using MSBuild
[ "", "c#", "compiler-construction", "msbuild", "c-preprocessor", "" ]
When running the following Java code, I get very accurate and consistent results in determining if the web page I'm testing is up. ``` protected synchronized boolean checkUrl(HttpURLConnection connection){ boolean error = false; //HttpURLConnection connection = null; GregorianCalendar calendar = new Gregor...
Simply change this: ``` res = webreq.GetResponse(); connectedToUrl = processResponseCode(res); ``` to ``` using (WebResponse res = webreq.GetResponse()) { connectedToUrl = processResponseCode(res); } ``` (Remove the declaration from earlier.) Until you haven't closed/disposed the response (or it's been finali...
I believe this is because you're not closing any of the request objects.
Different performance between Java and c# code when testing URL
[ "", "c#", "http", "timeout", "" ]
I have this program in c++: ``` #include <iostream> using namespace std; int main() { char buf[50]; cin.getline(buf,49); system(buf); return 0; } ``` When I run and compile it and type for example "helo", my program prints the error: ``` "helo" not found. ``` Can I stop this error from being displayed? Is there a...
You can't change the way `system` displays errors. C and C++ put very little to no requirements on implementations in that regard, so that large parts of it are left unspecified, to allow them to be as flexible as possible. If you want more precise control, you should use the functions of your runtime library or opera...
Are you on linux? Try typing "./hello" If this works, the reason is that the current directory (".") is not in the search path. You must indicate that the compiled program is "there" in the directory. Alternatively, you can do something like export PATH=$PATH:. This adds "." (current directory) to the search path. ...
Blocking the standard error output of a programmatically run system command
[ "", "c++", "external-process", "standard-error", "" ]
I often want to grab the first element of an `IEnumerable<T>` in .net, and I haven't found a nice way to do it. The best I've come up with is: ``` foreach(Elem e in enumerable) { // do something with e break; } ``` Yuck! So, is there a nice way to do this?
If you can use LINQ you can use: ``` var e = enumerable.First(); ``` This will throw an exception though if enumerable is empty: in which case you can use: ``` var e = enumerable.FirstOrDefault(); ``` `FirstOrDefault()` will return `default(T)` if the enumerable is empty, which will be `null` for reference types or...
Well, you didn't specify which version of .Net you're using. Assuming you have 3.5, another way is the ElementAt method: ``` var e = enumerable.ElementAt(0); ```
How do I get the first element from an IEnumerable<T> in .net?
[ "", "c#", ".net", "" ]
Yesterday I made a simulation using Python. I had a few difficulties with **variables and debugging**. Is there any software for Python, which provides a decent debugger? Related question: [What is the best way to debug my Python code?](https://stackoverflow.com/questions/299704/what-is-the-best-way-to-debug-my-pytho...
Don't forget about post-mortem debugging! After an exception is thrown, the stack frame with all of the locals is contained within `sys.last_traceback`. You can do `pdb.pm()` to go to the stack frame where the exception was thrown then p(retty)p(rint) the `locals()`. Here is a function that uses this information to ex...
`Winpdb` ([archived link](https://web.archive.org/web/20090126223735/http://winpdb.org/) / [SourceForge.net](https://sourceforge.net/projects/winpdb/files/winpdb/) / [Google Code Archive](https://code.google.com/archive/p/winpdb/downloads)) is a **platform independent** graphical GPL Python debugger with support for re...
Suggestions for Python debugging tools?
[ "", "python", "debugging", "simulation", "" ]
When does it become unavoidable and when would you want to choose JavaScript over server side when you have a choice?
Designer perspective: * When you want to give more interactivity to your web page * When you want to load stuff without reloading (i.e.: ajax for example) When you shouldn't use: * When You don't want to spend 1000 hours in pointless tries to disable the back arrow of your browser :)
When you need to change something on your page without reloading it.
Do I have to use JavaScript?
[ "", "asp.net", "javascript", "" ]
I'm building a desktop application right now that presents its human-readable output as XHTML displayed in a WebBrowser control. Eventually, this output is going to have to be converted from an XHTML file to a document image in an imaging system. Unlike XHTML documents, the document image has to be divided into physica...
**Edit** (2010-11-28 12:30 PM PST) Please +1 this answer if you download my code. I notice my Codeplex sample has been downloaded hundreds of times. The code isn't spectacular, but it works as a great starting point, with lots of links to source help included. Thanks! +tom **Edit** (2009-03-29 9:00 AM PST) Posted [samp...
Just my 2p but if you are an XSLT ninja I'd suggest sticking with that. You can avoid the nasty java program by looking at nFop which is a C# port of the apache FOP project. What's great is that you can simply take the assembly and use directly passing your XML and XSLT to it to get the PDF output you want. <http://so...
What page-image generating technology should I use?
[ "", "c#", ".net", "formatting", "printing-web-page", "" ]
I'm creating an implementation that performs conversion from one form to another. The design problem I am facing now is whether the Encoder and Decoder API should be in one interface or in separate ones. e.g. Apache MINA uses [separate interfaces](http://mina.apache.org/report/1.1/apidocs/org/apache/mina/filter/codec/...
Having separate interfaces doesn't mean you can't centralize the implementation. For example you could have one class implement both interfaces. Or each class could reference a common class which implements the protocol. So what I'd do is have separate interfaces, and at least to begin with, have one class implement b...
Only thing is that you usually have one code part that will use the decoder and a separate using the encoder. So a change to the encoding part of the interface will force an unnecessary recompile of the decoding part and vice versa. True for c/c++ etc. with header file include. Search for solid principles and see Int...
Separate decode/encode interfaces or in one interface
[ "", "java", "api", "oop", "fluent-interface", "" ]
I am using SQL Server 2005, I want to find out what all the grants are on a specific database for all tables. It would also help to find out all tables where the delete grant has been given for a specific user. Note: this may be similar to [this question](https://stackoverflow.com/questions/212681/how-do-i-generate-a-...
The given solution does not cover where the permission is granted against the schema or the database itself, which do grant permissions against the tables as well. This will give you those situations, too. You can use a WHERE clause against permission\_name to restrict to just DELETE. ``` SELECT class_desc , C...
I liked the answer from K. Brian Kelly but I wanted a little more information (like the schema) as well as generating the corresponding GRANT and REVOKE statements so I could apply them in different environments (e.g. dev/test/prod). note you can easily exclude system objects, see commented where clause ``` select ...
How can I view all grants for an SQL Database?
[ "", "sql", "sql-server-2005", "permissions", "" ]
I ran a pen-testing app and it found a ton of XSS errors, specfically, I'm guilty of echo'ing unverified data back to the browser through the querystring. Specifically, running this puts javascript into my page. <http://www.mywebsite.com/search.php?q=%00>'" [ScRiPt]%20%0a%0d>alert(426177032569)%3B[/ScRiPt]. Thankfull...
HTML-escaping on the way in is obviously The Wrong Thing, but could be a temporary fix until you replace the code with something proper. In the long term it would be unmaintainable and you'll have loads of weird application-level errors anywhere you start doing substring manipulations (including truncation, which your ...
Blindly escaping all input on the front end would mean that any part of your program that dealt with that input would have to handle html-escaped versions of <, >, &, etc. If you're storing data in a database, then you would have html-escaped data in your database. If you use the data in a non-html context (like sendin...
taking care of XSS
[ "", "php", "security", "xss", "" ]
I've been using javascript for a while, but have never learned the language past the basics. I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc. John gives this example in his book: **Function #1** ``` func...
Every time a function() {} is evaluated, it creates a new function object. Therefore, in #1 all of the User objects are sharing the same getName and getAge functions, but in #2 and #3, each object has its own copy of getName and getAge. All of the different getName functions all behave exactly the same, so you can't se...
If you want to do OOP in JavaScript I'd highly suggest looking up closures. I began my learning on the subject with these three web pages: <http://www.dustindiaz.com/javascript-private-public-privileged/> <http://www.dustindiaz.com/namespace-your-javascript/> <http://blog.morrisjohns.com/javascript_closures_for_dumm...
Object Oriented questions in Javascript
[ "", "javascript", "oop", "" ]
Is there a C/C++ library, and documentation about how to collect system and process information on Solaris? Although I could parse command-line tools, I'd rather use a library that makes the task easier to do. Thanks **Edit:** It has been suggested to use the /proc virtual directory to collect information, however i...
You can get this kind of information with [kstat API](http://developers.sun.com/solaris/articles/kstatc.html). ``` man -s 3KSTAT kstat ``` You can see how it is used in OpenSolaris [vmstat](http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/cmd/stat/vmstat/) and [iostat](http://cvs.opensolaris.org/source/...
Solaris has the [/proc virtual directory](http://en.wikipedia.org/wiki/Procfs), which allows you to gather all sorts of information about processes using filesystem I/O functions.
How to get process info programmatically in C/C++ from a Solaris system?
[ "", "c++", "c", "process", "solaris", "system", "" ]
In Java, I'm trying to log into an FTP server and find all the files newer than x for retrieval. Currently I have an input stream that's reading in the directory contents and printing them out, line by line, which is all well and good, but the output is fairly vague... it looks like this... ``` -rw------- 1 vuser...
Maybe worth having a look at the [Jakarta Commons Net](http://commons.apache.org/net/) API which has FTP functionality. I think with it you can use [list files](http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html#listFiles()) which will give you file objects that you can do [getTimeStamp](http:...
Unfortunately, the output of an FTP servers directory listing is not mandated by the standard. In fact, it is explicitly described as not intended for machine parsing. The format will vary quite a bit between servers on some operating systems. RFC 3659 describes some extensions to the FTP standard including the "MDTM"...
Obtain timestamp of items from FTP file list
[ "", "java", "ftp", "" ]
If my understanding is correct, they do exactly the same thing. Why would anyone use for the "for" variant? Is it just taste? **Edit:** I suppose I was also thinking of for (;;).
``` for (;;) ``` is often used to prevent a compiler warning: ``` while(1) ``` or ``` while(true) ``` usually throws a compiler warning about a conditional expression being constant (at least at the highest warning level).
Yes, it is just taste.
for(;true;) different from while(true)?
[ "", "c++", "c", "" ]
So I have a ResourceManager that points to a resource file with a bunch of strings in it. When I call `GetString()` with a key that doesn't exist in the file, I get a `System.Resources.MissingManifestResourceException`. I need to find out whether the Resource contains the specified key without using exception handling ...
Note that by default, it appears that a new .net project's Resources.resx is going to be in the Properties folder, so you'll need to create the ResourceManager like this: ``` rm = new ResourceManager("MyNamespace.Properties.MyResource", assembly); ``` Alternatively, by getting frustrated and deleting/recreating Resou...
Calling the GetString method with a key that doesn't exist does not raise an exception, it just returns null. However, the MissingManifestResourceException occurrs when trying to create a ResourceManager with the wrong name. The most common error is to forget to include the namespace in the name of the resources. For...
How do I find out whether a ResourceManager contains a key without calling ResourceManager.GetString() and catching the exception?
[ "", ".net", "c++", "localization", "" ]
I can find all sorts of stuff on how to program for DCOM, but practically nothing on how to set/check the security programmatically. I'm not trying to recreate dcomcnfg, but if I knew how to reproduce all the functionality of dcomcnfg in C# (preferred, or VB.net) then my goal is in sight. I can't seem to be able to f...
The answer posted by Daniel was HUGELY helpful. Thank you so much, Daniel! An issue with [Microsoft's documentation](http://msdn.microsoft.com/en-us/library/windows/desktop/ms678417%28v=vs.85%29.aspx) is that they indicate that the registry values contain an ACL in binary form. So, for instance, if you were trying to ...
Facing similar circumstances (configuring DCOM security from an MSI) I managed to create a solution that does what I want by altering registry key values in HKEY\_CLASSES\_ROOT\AppID{APP-GUID-GOES-HERE}. Thanks to Arnout's answer for setting me on the right path. In specific, I created a method to edit the security pe...
dcomcnfg functionality programmatically
[ "", "c#", ".net", "security", "permissions", "dcom", "" ]
I know this seams a trivial question, but how can I disable the annoying JavaScript error messages? I am inserting data into an unfinished web application and I keep getting about 30 errors for every form I submit. It's driving me crazy. I'm using IE7. Please note that I already tried "Internet options - Advanced - ...
After some Googling it seems you might get this if your user-agent string is too long. See [here](http://blogs.msdn.com/scicoria/archive/2009/01/15/adding-web-parts-via-ie-7-and-the-not-enough-storage-is-available-to-complete-this-operation-javascript-error-message.aspx) and [here](http://social.msdn.microsoft.com/Foru...
If you want to turn them off in code, you can do this: ``` window.onerror = null; ```
How to disable JavaScript error messages?
[ "", "javascript", "internet-explorer", "error-handling", "" ]
I am trying to work out the format of a password file which is used by a LOGIN DLL of which the source cannot be found. The admin tool was written in AFX, so I hope that it perhaps gives a clue as to the algorithm used to encode the passwords. Using the admin tool, we have two passwords that are encoded. The first is ...
Well, I did a quick cryptanalysis on it, and so far, I can tell you that each password appears to start off with it's ascii value + 26. The next octet seems to be the difference between the first char of the password and the second, added to it's ascii value. The 3d letter, I haven't figured out yet. I think it's safe ...
But since the output is equal in length with the input this looks like some fixed key cipher. It may be a trivial xor. I suggest testing the following passwords: ``` * AAAAAAAA * aaaaaaaa * BBBBBBBB * ABABABAB * BABABABA * AAAABBBB * BBBBAAAA * AAAAAAAAAAAAAAAA * AAAAAAAABBBBBBBB * BBBBBBBBAAAAAAAA ``` Thi...
What function was used to code these passwords in AFX?
[ "", "c++", "encoding", "afx", "" ]
I'm working on some JQuery to hide/show some content when I click a link. I can create something like: ``` <a href="#" onclick="jquery_stuff" /> ``` But if I click that link while I'm scrolled down on a page, it will jump back up to the top of the page. If I do something like: ``` <a href="" onclick="jquery_stuff" ...
Put a "return false;" on the second option: ``` <a href="" onclick="jquery_stuff; return false;" /> ```
You need to `return false;` after the `jquery_stuff`: ``` <a href="no-javascript.html" onclick="jquery_stuff(); return false;" /> ``` This will cancel the default action.
How can I create an empty HTML anchor so the page doesn't "jump up" when I click it?
[ "", "javascript", "jquery", "anchor", "" ]
Our build is annoyingly slow. It's a Java system built with [Ant](http://en.wikipedia.org/wiki/Apache_Ant), and I'm running mine on Windows XP. Depending on the hardware, it can take between 5 to 15 minutes to complete. Watching overall performance metrics on the machine, as well as correlating hardware differences wi...
If you *only* need it for Windows, SysInternals [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) should show you everything you need to know. You can select the process, then see each operation as it goes and get a summary of file operation as well.
Back when I still used Windows I used to get good results speeding my build up by having all build output written to a separate partition if maybe 3 GB in size, and periodically formatting that at night once a week via a scheduled task. It's just build output, so it doesn't matter if it gets unilaterally flattened occa...
How can I profile file I/O?
[ "", "java", "windows", "build-process", "profiling", "" ]
Can anyone explain why this code gives the error: ``` error C2039: 'RT' : is not a member of 'ConcreteTable' ``` (at least when compiled with VS2008 SP1) ``` class Record { }; template <class T> class Table { public: typedef typename T::RT Zot; // << error occurs here }; class ConcreteTable : public Table<Con...
That's because the class ConcreteTable is not yet instantiated when instantiating Table, so the compiler doesn't see T::RT yet. I'm not really sure how exactly C++ standard handles this kind of recursion (I suspect it's undefined), but it doesn't work how you'd expect (and this is probably good, otherwise things would ...
you are trying to use class CponcreateTable as a template parameter before the class is fully defined. The following equivalent code would work just fine: ``` class Record { }; template <class T> Table { public: typedef typename T::RT Zot; // << error occurs here }; class ConcreteTableParent { public: t...
Template typedef error
[ "", "c++", "templates", "" ]
Two tables: ***`COURSE_ROSTER`*** - contains * `COURSE_ID` as foreign key to `COURSES` * `USER_ID` as field I need to insert into `COURSES` ***`COURSES`*** - contains * `COURSE_ID` as primary key * `INSTRUCTOR_ID` as field that needs to be updated with `USER_ID` field from `COURSE_ROSTER` What would the `UPDAT...
Not all database vendors (SQL Server, Oracle, etc.) Implement Update syntax in the same way... You can use a join in SQL Server, but Oracle will not like that. I believe just about all will accept a correclated subquery however ``` Update Courses C SET Instructor_ID = (Select User_ID from Course_Rost...
``` Update Courses SET Courses.Instructor_ID = Course_Roster.User_ID from Courses Inner Join Course_Roster On Course_Roster.CourseID = Courses.Course_ID ``` This is assuming that your DBMS allows for joins on your update queries. SQL Server definitely allows this. If you cannot do something like this ...
How can I update a field in one table with a field from another table? (SQL)
[ "", "sql", "sql-update", "" ]
I'm fairly new to the Zend Framework and MVC and I'm a bit confused by Zend\_DB and the proper way to interact with the database. I'm using the PDO MySQL adapter and have created some classes to extend the abstract classes: ``` class Users extends Zend_Db_Table_Abstract { protected $_name = 'users'; protected...
Using Zend\_Db you probably don't want to get into the details of prepared statements and the like. You just want to use the model objects to do basic CRUD (Create, Read, Update and Delete). I know the [Programmer's Reference Guide](http://framework.zend.com/manual/en/zend.db.html) is extensive, but its a great introdu...
In general, people prefer to access the database through the Table and Row objects, to match their habits of object-oriented programming. The OO approach is useful if you need to write code to transform or validate query inputs or outputs. You can also write custom methods in a Table or Row class to encapsulate freque...
Zend Framework: Proper way to interact with database?
[ "", "php", "mysql", "database", "zend-framework", "zend-db-table", "" ]
I've been pondering this for a while but cannot come up with a working solution. I can't even psuedo code it... Say, for example, you have a page with a heading structure like this: ``` <h1>Heading level 1</h1> <h2>Sub heading #1</h2> <h2>Sub heading #2</h2> <h3>Sub Sub heading</h3> <h2>Sub he...
First, build a tree. Pseudocode (because I'm not fluent in Javascript): ``` var headings = array(...); var treeLevels = array(); var treeRoots = array(); foreach(headings as heading) { if(heading.level == treeLevels.length) { /* Adjacent siblings. */ if(heading.level == 1) { treeRoots...
The problem here is that there is not any good way to retrieve the headings in document order. For example the jQuery call `$('h1,h2,h3,h4,h5,h6')` will return all of your headings, but all `<h1>`s will come first followed by the `<h2>`s, and so on. No major frame work yet returns elements in document order when you us...
Produce heading hierarchy as ordered list
[ "", "javascript", "html", "methodology", "" ]
Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like `del somelist[0]`, followed by `del somelist[2]`, the second statement will actually delete `somelist[3]`. I suppose I could always delete the higher numbered elements first bu...
You can use `enumerate` and remove the values whose index matches the indices you want to remove: ``` indices = 0, 2 somelist = [i for j, i in enumerate(somelist) if j not in indices] ```
For some reason I don't like any of the answers here. Yes, they work, but strictly speaking most of them aren't deleting elements in a list, are they? (But making a copy and then replacing the original one with the edited copy). Why not just delete the higher index first? Is there a reason for this? I would just do: ...
Deleting multiple elements from a list
[ "", "python", "list", "" ]
I'm trying to send a WOL package on all interfaces in order to wake up the gateway(which is the DHCP server, so the machine won't have an IP yet). And it seems that I can only bind sockets to IP and port pairs... So the question is: How can a create a socket(or something else) that is bound to a NIC that has no IP? (...
It seems that I have found a solution. One can use winpcap to inject packets to any interface. And there is good wrapper for .net: <http://www.tamirgal.com/home/dev.aspx?Item=SharpPcap> (I would have prefered a solution which requires no extra libraries to be installed...) **UPDATE:** Here is what I came up for sendi...
WOL is a very flexible protocol that can be implemented in multiple different ways. **The most common are:** * Sending a WOL as the payload of an ethernet packet. * Sending a WOL as the payload of a UDP packet (for routing across the net). Once it lands on the local network it's passes to all the hosts on the networ...
How to send a WOL package(or anything at all) through a nic which has no IP address?
[ "", "c#", "network-programming", "network-protocols", "ethernet", "winpcap", "" ]
In my project there are situations where we have to send xml messages (as char \*) among modules. They are not really large ones, just 10-15 lines. Right now everybody just creates the string themselves. I dont think this is the right approach. We are already using xerces DOM library. So why not create a Dom tree, seri...
If you are really just creating small XML messages, Xerces is an overkill, IMHO. It is a parser library and you are not parsing anything.
You could use the DOM or write you own small C++ XML generation framework. The Xerces API was ported from Java and by using object scope you can make generating XML from C++ code even easier: ``` XmlWriter w; Elem book = w.Element("book"); book.addAttrib("title", "Lord of the Rings"); Elem author = e.addChild("author...
Creating XML in C++ Code
[ "", "c++", "xml", "dom", "" ]
I'd like to update a set of rows based on a simple criteria and get the list of PKs that were changed. I thought I could just do something like this but am worried about possible concurrency problems: ``` SELECT Id FROM Table1 WHERE AlertDate IS NULL; UPDATE Table1 SET AlertDate = getutcdate() WHERE AlertDate IS NULL;...
Consider looking at the [OUTPUT clause](http://msdn.microsoft.com/en-us/library/ms177564.aspx): ``` USE AdventureWorks2012; GO DECLARE @MyTableVar table( EmpID int NOT NULL, OldVacationHours int, NewVacationHours int, ModifiedDate datetime); UPDATE TOP (10) HumanResources.Employee SET...
Many years later... The accepted answer of using the OUTPUT clause is good. I had to dig up the actual syntax, so here it is: ``` DECLARE @UpdatedIDs table (ID int) UPDATE Table1 SET AlertDate = getutcdate() OUTPUT inserted.Id INTO @UpdatedIDs WHERE AlertDate IS NULL; ``` **ADDED** SEP 14, 2...
Is there a way to SELECT and UPDATE rows at the same time?
[ "", "sql", "sql-server", "t-sql", "sql-server-2008", "" ]
I am currently developing a site and have a need for a javascript-based carousel/slider hybrid on the home page that fades between 3 or 4 different images automatically, giving the user the chance to click on one and go to another page on the site. I also need the different slides to have some sort of navigation, denot...
Unless I'm missing something, the navigation on iLife looks like a photo gallery where the large photo links to the destination. I've used the [jQuery Galleria](http://devkick.com/lab/galleria/) for photo galleries because the animation effects are superb. Also the forum provides helpful community-based support. If yo...
jQuery animate or [jCarousel](http://sorgalla.com/projects/jcarousel/)
Javascript carousel/slider with customizable navgation
[ "", "javascript", "slider", "" ]
I'm wondering if it's possible to restore an element's style to it's "default" state, with Javascript or otherwise. I need to do this because I'm inserting HTML into 3rd party web pages and cannot control what styles they attribute to different elements. For instance, they may have: ``` div { margin: 10px; paddin...
It appears that someone has already asked this question on SO. [CSS Reset, default styles for common elements](https://stackoverflow.com/questions/99643/css-reset-default-styles-for-common-elements)
The default styles are defined by each browser, and as you can guess, all the browsers have it styled a bit differently. You may be able to define each style attribute and assign it to inherit !important: ``` div { margin: inherit !important; padding: inherit !important; line-height: inherit !important; font-s...
Is it possible to "remove" styling from HTML elements?
[ "", "javascript", "html", "css", "styles", "" ]
I'm a bit confused from what I've heard Java doesn't do events. But I know that it does GUI events. Am I missing something? Does java have an event handling mechanism? I'm aware that I can implement a publisher subscriber pattern, but I'm looking for native support within Java. I seem to remember something about Ja...
As you already stated, you can do the exact same thing with the publisher-subscriber/Observer pattern. It just requires a bit more legwork. And no, Java does not have native support for events, like C# does with delegates.
The Subscribe/Publish mechanism proposed by others here will let you implement **synchronous** events. For asynchronous event loops (fire and forget) You may want to look at "actors". An `Actor<A>` consists of a handler for messages (events) of type A, as well as a threading strategy for executing the handler. This let...
Does Java have native support for events, similar to that of C#?
[ "", "java", "events", "" ]
I am allowing the users to be able to make their own font choices for a listview. What would you consider the best approach for this. Should I save it to the registry or to a file in the application folder, and what properties should be saved to make sure that the font is redisplayed properly when the application is re...
Regarding where/how to save application settings see [this answer](https://stackoverflow.com/questions/453161/best-pratice-to-save-application-settings-in-windows-application#453230) You can save your font as a string and load it later using following code: ``` Font font1 = new Font("Arial", 12, FontStyle.Italic); Ty...
You could also use [isolated storage](http://msdn.microsoft.com/en-us/library/3ak841sy(VS.80).aspx). Really, you need to know if the application is ever shared across user profiles on the same machine. If not, you can get away with storing it in a config file. If it is, then you can use the registry (maintainable), or...
C# How do I save runtime font settings
[ "", "c#", "" ]
Can someone please explain why this program outputs 0x00000004? ``` class AndAssignment { static void Main() { int a = 0x0c; a &= 0x06; Console.WriteLine("0x{0:x8}", a); } } /* Output: 0x00000004 */ ```
0x0c = 1100 in binary 0x06 = 0110 in binary & operation is a binary AND which sets a bit to 1 if it's set in both operands, so: 0x0c & 0x06 = 1100 & 0110 = 0100 = 0x04 You can use windows calculator to see how integers is presented in different forms (hex and binary in your case). [More info](http://en.wikipedi...
You have to know the basics of converting from number bases. Decimals are base 10. Binary is base 2. Hexadecimal is base 16. Look at the following table for hexadecimal: ``` 16^0 = 1 16^1 = 16 16^2 = 256 16^3 = 4096 ``` Hexadecimals have the following numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f. so you hav...
Can someone explain the output of this program?
[ "", "c#", "" ]
This is probably a simple question but I can't seem to find the solution. I have a time string that is 8 digits long (epoch seconds), when I try to format this using the Java DateFormat, it always assumes that my time contains milliseconds as well, so 16315118 converts to: 4:31:55.118 instead of the correct time of 19...
> I also do not want to multiply by 1000 > since I am using this for formatting > of other times that includes > milliseconds. You're out of luck. You can't use the same DateFormat to format two different time values. Either use two different formatters or (more correctly) convert your time values. Your time values s...
A Java Date is milliseconds since the epoch. Multiply your value by 1000 before you convert it to a Date. Then you can customize the DateFormat you use by creating a new [SimpleDateFormat](http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html) with the format string you want.
DateFormat with no milliseconds
[ "", "java", "" ]
I have a generic class in my project with derived classes. ``` public class GenericClass<T> : GenericInterface<T> { } public class Test : GenericClass<SomeType> { } ``` Is there any way to find out if a `Type` object is derived from `GenericClass`? ``` t.IsSubclassOf(typeof(GenericClass<>)) ``` does not work.
Try this code ``` static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) { while (toCheck != null && toCheck != typeof(object)) { var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck; if (generic == cur) { return true; } toCheck = toChec...
(Reposted due to a massive rewrite) JaredPar's code answer is fantastic, but I have a tip that would make it unnecessary if your generic types are not based on value type parameters. I was hung up on why the "is" operator would not work, so I have also documented the results of my experimentation for future reference....
Check if a class is derived from a generic class
[ "", "c#", "generics", "reflection", "" ]
In a Windows Forms app I set the ContextMenuStrip property on a TabControl. 1. How can I tell the user clicked a tab other then the one that is currently selected? 2. How can I restrict the context menu from showing only when the top Tab portion with the label is clicked, and not elsewhere in the tab?
Don't bother setting the contextMenuStrip property on the TabControl. Rather do it this way. Hook up to the tabControl's MouseClick event, and then manually show the context menu. This will only fire if the tab itself on top is clicked on, not the actual page. If you click on the page, then the tabControl doesn't recei...
Opening event of context menu can be used to solve both problems ``` private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) { Point p = this.tabControl1.PointToClient(Cursor.Position); for (int i = 0; i < this.tabControl1.TabCount; i++) { Rectangle r = this.tabControl1...
TabControl Context Menu
[ "", "c#", "winforms", "tabcontrol", "contextmenu", "" ]
I'm using VBScript (ASP Classic) and SQL Server; I'm trying to have a section on the website where you can see a count of products at certain price levels. Something like: ``` $50 - $100 (4) $100 - $500 (198) $500 - $1000 (43) ``` For the love of me I cannot figure out a good way to do a query like this. I mean... I ...
The most efficient way of doing this in SQL (I believe) is to use a `sum case` construct: ``` select sum(case when Price >= 50 and Price < 100 then 1 else 0 end) as 50to100, sum(case when Price >= 100 and Price < 500 then 1 else 0 end) as 100to500, sum(case when Price >= 500 and Price < 1000 then 1 el...
Table drive it: ``` SELECT pr.MinPrice, pr.MaxPrice, COUNT(*) FROM Products AS p INNER JOIN PriceRanges AS pr ON p.UnitPrice BETWEEN pr.MinPrice AND pr.MaxPrice GROUP BY pr.MinPrice, pr.MaxPrice ORDER BY pr.MinPrice, pr.MaxPrice ``` If you need different price ranges for different product categories: ``` SELECT ...
How do I create a "filter by price" type of query?
[ "", "sql", "filtered-lookup", "" ]
I want to create a SQL Select to do a unit test in MS SQL Server 2005. The basic idea is this: ``` select 'Test Name', foo = 'Result' from bar where baz = (some criteria) ``` The idea being that, if the value of the "foo" column is "Result", then I'd get a value of true/1; if it isn't, I'd get false/0. Unfortunately...
Use the case construct: ``` select 'Test Name', case when foo = 'Result' then 1 else 0 end from bar where baz = (some criteria) ``` Also see [the MSDN Transact-SQL CASE documentation](http://msdn.microsoft.com/en-us/library/ms181765.aspx).
``` SELECT 'TestName', CASE WHEN Foo = 'Result' THEN 1 ELSE 0 END AS TestResult FROM bar WHERE baz = @Criteria ```
Boolean Expressions in SQL Select list
[ "", "sql", "unit-testing", "t-sql", "expression", "assert", "" ]
I have backed up and restored a MS SQL Server 2005 database to a new server. **What is the best way of recreating the login, the users, and the user permissions?** On SQL Server 2000's Enterprise Manager I was able to script the logins, script the users and script the user permissions all seperately. I could then run...
The easiest way to do this is with Microsoft's `sp_help_revlogin`, a stored procedure that scripts all SQL Server logins, defaults and passwords, and keeps the same SIDs. You can find it in this knowledge base article: <http://support.microsoft.com/kb/918992>
Run this: ``` EXEC sp_change_users_login 'Report' ``` This will show a list of all Orphaned users, for example: ![enter image description here](https://i.stack.imgur.com/OOaLL.png) Now execute this script here for each user, for example ``` exec sp_change_users_login 'Update_One', 'UserNameExample', 'UserNameExamp...
Restoring a Backup to a different Server - User Permissions
[ "", "sql", "sql-server", "backup", "ssms", "database-restore", "" ]
I have data that looks like this: ``` entities id name 1 Apple 2 Orange 3 Banana ``` Periodically, a process will run and give a score to each entity. The process generates the data and adds it to a scores table like so: ``` scores id entity_id score date_added 1 1 ...
I do it this way: ``` SELECT e.*, s1.score, s1.date_added FROM entities e INNER JOIN scores s1 ON (e.id = s1.entity_id) LEFT OUTER JOIN scores s2 ON (e.id = s2.entity_id AND s1.id < s2.id) WHERE s2.id IS NULL; ```
Just to add my variation on it: ``` SELECT e.*, s1.score FROM entities e INNER JOIN score s1 ON e.id = s1.entity_id WHERE NOT EXISTS ( SELECT 1 FROM score s2 WHERE s2.id > s1.id ) ```
How do I join the most recent row in one table to another table?
[ "", "sql", "date", "join", "greatest-n-per-group", "" ]
I am trying to ensure that the text in my control derived from TextBox is always formatted as currency. I have overridden the Text property like this. ``` public override string Text { get { return base.Text; } set { double tempDol...
Instead of "C" put "{0:c}" For more string formatting problems go [here](http://blog.stevex.net/index.php/string-formatting-in-csharp/)
You can also use tempDollarAmount.ToString("C").
string.Format "C" (currency) is returning the string "C" instead of formatted text
[ "", "c#", "format", "" ]
I'm trying to create a cache in a webservice. For this I've created a new Stateless Bean to provide this cache to other Stateless beans. This cache is simply a static ConcurrentMap where MyObject is a POJO. The problem is that it seems as there are different cache objects. One for the client beans, and another locally....
As far as I remember you cant be certain that the stateless bean is global enough for you to keep data in static fields. There exist several caching frameworks that would help you with this. Maybe [memcache](http://www.whalin.com/memcached/)? EDIT: <http://java.sun.com/blueprints/qanda/ejb_tier/restrictions.html#stati...
On the surface, this seems like a contradiction in terms, as a cache is almost certainly something I would not consider stateless, at least in the general sense.
Share static singletons through EJB's
[ "", "java", "jakarta-ee", "static", "singleton", "ejb", "" ]
I have a really strange enum bug in Java. ``` for(Answer ans : assessmentResult.getAnswersAsList()) { //originally stored in a table //AnswerStatus stat = ans.getStatus(); if (ans.getStatus() == AnswerStatus.NOT_ASSESSED) { assessed = false; } } ``` An answer is an answer to a question on a test. ...
Solved. It was the NetBeans debugger that tricked me. It does not pass the if test (although NetBeans says that). Sorry for the inconvenience :-)
> I've debugged the above code, and > ans.getStatus() returns > AnswerStatus.ASSESSED. Still, the if > line returns true, and assessed is set > to false. > > But, the thing I think is most > strange; When I declare the > AnswerStatus stat variable, it works, > even if I don't use the stat variable > in the if test. Cou...
Strange java enum bug
[ "", "java", "enums", "" ]
I'm trying to make Javascript change the style of certain DIV IDs by changing their background every few seconds. Basically, a fading header...here's my code, and it just doesn't change the background, at all. How do you call a function? <http://pixolia.net/sandbox/morph/index.php>
Your javascript is in functions and isn't being called from anywhere. Try calling one of the functions from window.onload, or $(document).ready(function(){ }); if you're using jQuery
you could do something like this ``` <body onload="Appear(id1, id2);"> ``` that way when the page loads it starts the fadein/out
What's wrong with my javascript? Fading images
[ "", "javascript", "image", "coding-style", "" ]
My visual assist x didn't work after I installed visual c# 2008. Is there any good add-ins like VAX?
The [Visual Studio 2008 Comparison Chart](http://msdn.microsoft.com/en-us/vstudio/aa700921.aspx) shows that the Express editions do not support addins. You will have to purchase at least the Standard edition to use addins.
It really depends on what you want to do with the add-ins. My personal favorite is [ViEmu](http://www.viemu.com/) which makes Visual Studio respect the Vim keybindings. It takes some getting used to, but once you have it down, the Vim way of doing things is extremely efficient.
Is there any good add-ins in Visual C#2008?
[ "", "c#", "visual-studio-2008", "add-in", "" ]
I've been informed that my library is slower than it should be, on the order of 30+ times too slow parsing a particular file (text file, size 326 kb). The user suggested that it may be that I'm using `std::ifstream` (presumably instead of `FILE`). I'd rather not blindly rewrite, so I thought I'd check here first, sinc...
I don't think that'd make a difference. Especially if you're reading char by char, the overhead of I/O is likely to completely dominate *anything* else. Why do you read single bytes at a time? You know how extremely inefficient it is? On a 326kb file, the fastest solution will most likely be to just read it into memor...
It should be slightly slower, but like what you said, it might not be the bottleneck. Why don't you profile your program and see if that's the case?
Is std::ifstream significantly slower than FILE?
[ "", "c++", "optimization", "file-io", "ifstream", "" ]
I have two professional programmer friends who are going to teach me, and they both love the language (C#). I know that their specific skills and enthusiasm more than out-weigh any drawbacks to the language, but they seem like such fanboys I'm left wondering what the catch is. I only have experience of XHTML and CSS, ...
There's a lot you'll be learning way before you get to object oriented concepts. If all you know is HTML and CSS then you'll be learning all the basics way before you touch objects. For that reason, C# is a fine choice, as it's got a great IDE and IMO makes it very easy for beginners. As for testing small snippets of c...
You have to start somewhere, I'd go for it. However I'd also buy a C# for beginners book. Experienced developers often "forget" what it was like starting off, and might "rush" you into things you're not properly prepared for. If they're not experienced developers, then **REALLY BUY THE BOOK**, without a book it's a ca...
As a novice, is there anything I should beware of before learning C#?
[ "", "c#", "" ]
I know of two methods of setting a default parameter, but I would like to know what the preferred method is. ``` function Foo(par1, par2) { if(par2 == null) par2 = "my default" } ``` or ``` function Foo(par1, par2) { par2 = par2 || "my default" } ``` or is there a better way than either of these? E...
Personally I think the second form is just outright cleaner and more readable, certainly moreso than sergey's arguments inspection - though that can have it's place - but I prefer to pass extensible objects for args than have to maintain arg signatures. *e.g.* ``` function Foo(myArgs) { myArgs.par1 = myArgs.par1 ...
first one is actually wrong, since they would be undefined, not null. `par2 !== null` would return true for this case. since javascript, if loosely compared, compare null, undefined, false to the same value, I would suggest checking explicitly for an undefined value. ``` if (par2 !== undefined) par2 = "my de...
What is the most efficient method of setting default parameter values in javascript?
[ "", "javascript", "parameters", "default-value", "" ]
Has anyone encountered such a beastie? I'm thinking about a tree-like display, database, login and registration etc. Ideally ready to bake as time is short. Ideally BSD or similar license but if neccessary might persuade the beancounters to cough up some beans. Alternatively if anyone is interested in creating someth...
I haven't seen any Silverlight Forum components in my travels around the internet. I think you might be stuck rolling your own.
There is an app now in Silverlight made by Myer check this out, <http://www.mher.info/blog/?p=136> hope this helps :)
C# Silverlight Forum component
[ "", "c#", "silverlight", "controls", "forum", "" ]
I am trying to stick to the practice of keeping the database normalized, but that leads to the need to run multiple join queries. Is there a performance degradation if many queries use joins vs having a call to a single table that might contain redundant data?
Keep the Database normalised UNTIL you have discovered a bottleneck. Then only after careful profiling should you denormalise. In most instances, having a good covering set of indexes and up to date statistics will solve most performance and blocking issues without any denormalisation. Using a single table could lead...
Michael Jackson (not *that* one) is [famously believed to have said](http://en.wikiquote.org/wiki/Michael_A._Jackson), * The First Rule of Program Optimization: Don't do it. * The Second Rule of Program Optimization – For experts only: Don't do it yet. That was probably before RDBMSs were around, but I think he'd hav...
SQL Joins vs Single Table : Performance Difference?
[ "", "sql", "join", "normalization", "" ]
I am running tomcat 6.0.18 as a windows service. In the service applet the jvm is configured default, i.e. it is using jvm.dll of the JRE. I am trying to monitor this application with JConsole but cannot connect to it locally. I added the parameter -Dcom.sun.management.jmxremote (which works when starting tomcat with ...
There's a nice GUI to edit the options, no need to muck around in the registry. Open up the C:\Program Files\Apache Software Foundation\Tomcat 6.0\bin\tomcat6.exe (or just double-click on the monitor icon in the task bar). Go to the Java pane, add the following to the list of arguments, and restart Tomcat. ``` -Dcom....
Here's the prescribed way for changing jvmoptions & interacting with the service: <http://tomcat.apache.org/tomcat-5.5-doc/windows-service-howto.html> I would try going into your registry at HKLM/Software/Apache Software Foundation/Procrun 2.0//Parameters/Java and editing the "Options" multi-string value directly.
Unable to use JConsole with Tomcat running as windows service
[ "", "java", "tomcat", "jmx", "jconsole", "" ]
I'm trying to run my junit tests using ant. The tests are kicked off using a JUnit 4 test suite. If I run this direct from Eclipse the tests complete without error. However if I run it from ant then many of the tests fail with this error repeated over and over until the junit task crashes. ``` [junit] java.util.zi...
Found my problem. I had included my classes directory in my path using a **fileset** as opposed to a **pathelement** this was causing .class files to be opened as ZipFiles which of course threw an exception.
This error is caused specifically because the class path contains explicit references to one or more [files] that are not JAR's. The reference to "error in opening zip file" is of course that a JAR is in effect a ZIP file where as other files [JUNIT] has found like class files are *not* and as such do not have a zip fo...
Configuring ant to run unit tests. Where should libraries be? How should classpath be configured? avoiding ZipException
[ "", "java", "ant", "junit", "" ]
How do these 2 classes differ? ``` class A(): x=3 class B(): def __init__(self): self.x=3 ``` Is there any significant difference?
`A.x` is a *class variable*. `B`'s `self.x` is an *instance variable*. i.e. `A`'s `x` is shared between instances. It would be easier to demonstrate the difference with something that can be modified like a list: ``` #!/usr/bin/env python class A: x = [] def add(self): self.x.append(1) class B: ...
Just as a side note: `self` is actually just a randomly chosen word, that everyone uses, but you could also use `this`, `foo`, or `myself` or anything else you want, it's just the first parameter of every non static method for a class. This means that the word `self` is not a language construct but just a name: ``` >>...
Python - why use "self" in a class?
[ "", "python", "oop", "" ]
In unbiased coin flip H or T occurs 50% of times. But I want to simulate coin which gives H with probability 'p' and T with probability '(1-p)'. something like this: ``` def flip(p): '''this function return H with probability p''' # do something return result >> [flip(0.8) for i in xrange(10)] [H,H,T,H,H,H...
`random.random()` returns a *uniformly distributed* pseudo-random floating point number in the range [0, 1). This number is less than a given number `p` in the range [0,1) with probability `p`. Thus: ``` def flip(p): return 'H' if random.random() < p else 'T' ``` Some experiments: ``` >>> N = 100 >>> flips = [fl...
Do you want the "bias" to be based in symmetric distribuition? Or maybe exponential distribution? Gaussian anyone? Well, here are all the methods, extracted from random documentation itself. First, an example of triangular distribution: ``` print random.triangular(0, 1, 0.7) ``` > **`random.triangular(low, high, mo...
How do I simulate flip of biased coin?
[ "", "python", "random", "probability", "coin-flipping", "" ]
I have an application that runs on a terminal. The terminal is registered on a database table. During all session that application is running on a terminal, I need to ensure that the line of the table corresponding to the terminal is locked and nobody can update that. What is the best way to do this? I use C#.NET a...
In general, I try to work with short-lived locks where I can do an entire unit of work in a single (serializable) transaction; this avoids the need for an additional locking mechanism, as the db locks will do everything needed. When working with long-lived locks: It is a bad idea to use rdbms-locks for that purpose - ...
Databases do not work for this kind of locking. You can lock items, but its only for the duration of the operation (SELECT, INSERT, UPDATE, DELETE). Perhaps you should try adding a bit column called "inUse" and set it to True(1) when the terminal is using it. Program the terminals to respect the inUse value if its alr...
How to lock a line of a table
[ "", ".net", "sql", "" ]
I have a list of values like this ``` 1000, 20400 22200, 24444 ``` The ranges don't overlap. What I want to do is have a c# function that can store (loaded values from db then cache it locally) a relatively large list of these values then have a method for finding if a supplied value is in any of the ranges? Does t...
You've specified values, but then talked about ranges. For just values, I'd use a `HashSet<int>`. For ranges it gets more complicated... Let us know if that's actually what you're after and I'll think about it more. If they *are* ranges, do you have any extra information about them? Do you know if they'll overlap or n...
A binary search will do just fine. Keep the list of ranges in sorted order, making sure that none of them intersect (if they do, merge them). Then write a binary search which, rather than testing against a single value, tests against either end of the range when looking to choose above or below.
How would I search a range of ranged values using C#
[ "", "c#", "algorithm", "" ]
Does anyone know a way to open a 2nd form in a .NET application with a certain tab selected in a tab control on that form? This is what my current code looks like which just opens the form: ``` SettingsForm TheSettingsForm = new SettingsForm(this); TheSettingsForm.Show(); ``` SettingsForm.cs is the name of the 2nd f...
You just need to expose a property on your form that allows the calling code to set the desired tab. You might do it just by index like this: ``` var form = new SettingsForm(this); form.SelectedTab = 2; form.Show(); ``` The property on the form would just set the appropriate property on the tab control: ``` public i...
Do something like this: ``` SettingsForm TheSettingsForm = new SettingsForm(this); TheSettingsForm.TabPanel.SelectedIndex = SettingsFormTabIndexes.MyDesiredTab; TheSettingsForm.Show(); ``` where you've made a property in TheSettingsForm that exposes the tab control and SettingsFormTabIndexes is a friendly enum naming...
In C#, is there a way to open a 2nd form with a tab selected?
[ "", "c#", ".net", "winforms", "" ]
There are some text files(Records) which i need to access using C#.Net. But the matter is those files are larger than 1GB. (minimum size is 1 GB) what should I need to do? What are the factors which I need to be concentrate on? Can some one give me an idea to over come from this situation. EDIT: Thanks for the fast...
Expanding on CasperOne's answer Simply put there is no way to reliably put a 100GB file into memory at one time. On a 32 bit machine there is simply not enough addressing space. In a 64 bit machine there is enough addressing space but during the time in which it would take to actually get the file in memory, your user...
You aren't specifically listing the problems you need to overcome. A file can be 100GB and you can have no problems processing it. If you have to process the file *as a whole* then that is going to require some creative coding, but if you can simply process sections of the file at a time, then it is relatively easy to...
Larger File Streams using C#
[ "", "c#", "filestream", "" ]
I have a base class with a virtual function and I want to override that function in a derived class. Is there some way to make the compiler check if the function I declared in the derived class actually overrides a function in the base class? I would like to add some macro or something that ensures that I didn't accide...
Since g++ 4.7 it does understand the new C++11 `override` keyword: ``` class child : public parent { public: // force handle_event to override a existing function in parent // error out if the function with the correct signature does not exist void handle_event(int something) override; }; ```
Something like C#'s `override` keyword is not part of C++. In gcc, `-Woverloaded-virtual` warns against hiding a base class virtual function with a function of the same name but a sufficiently different signature that it doesn't override it. It won't, though, protect you against failing to override a function due to m...
Safely override C++ virtual functions
[ "", "c++", "overriding", "virtual-functions", "" ]