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 within the `this` scope:
```
var myFunc = this[myFuncName];
``` | 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 there is a way to get rid of eval() here!
```
executeFunctionByName = function(functionName)
{
var args = Array.prototype.slice.call(arguments).splice(1);
//debug
console.log('args:', args);
var namespaces = functionName.split(".");
//debug
console.log('namespaces:', namespaces);
var func = namespaces.pop();
//debug
console.log('func:', func);
ns = namespaces.join('.');
//debug
console.log('namespace:', ns);
if(ns == '')
{
ns = 'window';
}
ns = eval(ns);
//debug
console.log('evaled namespace:', ns);
return ns[func].apply(ns, args);
}
core = {
paragraph: {
titlebar: {
user: "ddd",
getUser: function(name)
{
this.user = name;
return this.user;
}
}
}
}
var testf = function()
{
alert('dkdkdkd');
}
var x = executeFunctionByName('core.paragraph.titlebar.getUser', 'Ikon');
executeFunctionByName('testf');
``` | 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
select a;
return View(actions.ToList());
}
```
This code works very well for returning a single dataset. The situation I have is a that I've got a list of objects, each of which has a subset of objects that I want to display in a hierarchy on the output page. I'm not sure whether I'm looking for the quick way or the right way, thoughts on both avenues would be very much appreciated.
Thanks! | 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.yahoo.com/video/play?vid=111585),
+ [An Inconvenient API: The Theory of the DOM](http://video.yahoo.com/video/play?vid=111582).
* Read **[Pro JavaScript Techniques](http://jspro.org/)** by John Resig (the author of jQuery library).
+ This book already assumes, that you are pretty familiar with JavaScript syntax and goes in-depth to the really hard and important issues you face in your life with JavaScript. It teaches you what goes on under the hood of a JavaScript library like jQuery and how you would go to implement your own. | 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 isn't really that great, but the reference is awesome. If I'm looking for something, I just use google with 'mdc' (or 'mdc javascript' in ambiguous cases) + keyword as search terms.
---
It might also be a good idea to read the 3 1/2 page long sections 4.2 and 4.3 of ECMA-262. Also, consider reading chapter 10. | 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 are therefore no different to querying the base tables directly. Simple views are expanded in place and so **do not directly contribute to performance improvements** - that much is true. **However,** indexed views can *dramatically* improve performance.
Let me go directly to the documentation:
> After a unique clustered index is created on the view, the view's result set is materialized immediately and persisted in physical storage in the database, saving the overhead of performing this costly operation at execution time.
Second, these indexed views can work *even when they are not directly referenced by another query* as the optimizer will use them in place of a table reference when appropriate.
Again, the documentation:
> The indexed view can be used in a query execution in two ways. The query can reference the indexed view directly, or, more importantly, the query optimizer can select the view if it determines that the view can be substituted for some or all of the query in the lowest-cost query plan. In the second case, the indexed view is used instead of the underlying tables and their ordinary indexes. The view does not need to be referenced in the query for the query optimizer to use it during query execution. This allows existing applications to benefit from the newly created indexed views without changing those applications.
This documentation, as well as charts demonstrating performance improvements, can be found [here](http://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx).
**Update 2:** the answer has been criticized on the basis that it is the "index" that provides the performance advantage, not the "View." However, this is easily refuted.
Let us say that we are a software company in a small country; I'll use Lithuania as an example. We sell software worldwide and keep our records in a SQL Server database. We're very successful and so, in a few years, we have 1,000,000+ records. However, we often need to report sales for tax purposes and we find that we've only sold 100 copies of our software in our home country. By creating an indexed view of just the Lithuanian records, we get to keep the records we need in an indexed cache as described in the MS documentation. When we run our reports for Lithuanian sales in 2008, our query will search through an index with a depth of just 7 (Log2(100) with some unused leaves). If we were to do the same without the VIEW and just relying on an index into the table, we'd have to traverse an index tree with a search depth of 21!
Clearly, the View itself would provide us with a performance advantage (3x) over the simple use of the index alone. I've tried to use a real-world example but you'll note that a simple list of Lithuanian sales would give us an even greater advantage.
Note that I'm just using a straight b-tree for my example. While I'm fairly certain that SQL Server uses some variant of a b-tree, I don't know the details. Nonetheless, the point holds.
**Update 3:** The question has come up about whether an Indexed View just uses an index placed on the underlying table. That is, to paraphrase: "an indexed view is just the equivalent of a standard index and it offers nothing new or unique to a view." If this was true, of course, then the above analysis would be incorrect! Let me provide a quote from the Microsoft documentation that demonstrate why I think this criticism is not valid or true:
> Using indexes to improve query performance is not a new concept; however, indexed views provide additional performance benefits that cannot be achieved using standard indexes.
Together with the above quote regarding the persistence of data in physical storage and other information in the documentation about how indices are created on Views, I think it is safe to say that an Indexed View is **not** just a cached SQL Select that happens to use an index defined on the main table. Thus, I continue to stand by this answer. | **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 indexed view; they have to follow a [specific set of guidelines](http://msdn.microsoft.com/en-us/library/ms187864.aspx), which (among other restrictions) means you can't include common query elements like `COUNT`, `MIN`, `MAX`, or `TOP`.
2. Indexed views use physical space in the database, just like indexes on a table.
This article describes additional [benefits and limitations of indexed views](https://www.brentozar.com/archive/2013/11/what-you-can-and-cant-do-with-indexed-views/):
> **You Can…**
>
> * The view definition can reference one or more tables in the
> same database.
> * Once the unique clustered index is created, additional nonclustered
> indexes can be created against the view.
> * You can update the data in the underlying tables – including inserts,
> updates, deletes, and even truncates.
>
> **You Can’t…**
>
> * The view definition can’t reference other views, or tables
> in other databases.
> * It can’t contain COUNT, MIN, MAX, TOP, outer joins, or a few other
> keywords or elements.
> * You can’t modify the underlying tables and columns. The view is
> created with the WITH SCHEMABINDING option.
> * You can’t always predict what the query optimizer will do. If you’re
> using Enterprise Edition, it will automatically consider the unique
> clustered index as an option for a query – but if it finds a “better”
> index, that will be used. You could force the optimizer to use the
> index through the WITH NOEXPAND hint – but be cautious when using any
> hint. | 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 FIELD1, FIELD2 From Mylibrary.MyTable WHERE FIELD1 = 'myvalue'
```
I am using ADODB, VBScript to test.
```
Set Param1 = cmd.CreateParameter("@Field1", 129, 1, 9, "myvalue") ' 129 String
cmd.Parameters.Append Param1
```
I am coming from MS Sql environment, so writing for AS400 is totally new for me.
Thanks | 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:
```
Select FIELD1, FIELD2 From Mylibrary.MyTable WHERE FIELD1 = ?
cmd.ActiveConnection = connstr
cmd.CommandType = 1'4 'Stored Procedures '1 Text
cmd.CommandText = sql
Set Param1 = cmd.CreateParameter("@Field1", 129, 1, 9, "myvalue") ' 129 String
cmd.Parameters.Append Param1
Set rs = cmd.Execute()
```
This is all VbScript. The trick was to add the question mark(?) in the sql statement. | 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), this is the preferred method for calling sql:
```
iDB2Connection conn = new IDB2Connnection(connectionstring);
iDB2Command cmd = null;
try
{
conn.Open();
string sql = "select * from somelibrary.sometable where a = @A and b = @B";
cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.DeriveParameters(); //this will talk to the AS400 to determine the param types
cmd.Parameters["@A"].Value = Avalue;
cmd.Parameters["@B"].Value = Bvalue;
//execute the query
cmd.ExecuteScalar(); //doesn't have to be Scalar but you get the idea
}
catch (Exception ex)
{
//handle your exceptions
}
finally
{
cmd.Dispose();
conn.Close();
}
``` | 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 to an empty list. This code is from a Django view, but I don't think that matters--this seems like a more general Python question.
**EDIT:** I turns out that it was my code that was turning an empty queryset into a "None" instead of returning an empty list. Being able to assume that queryset is always iteratable simplifies the code by allowing the "if" statement to be removed. The answers below maybe useful to others who have the same problem, but cannot modify their code to guarantee that queryset is not "None". | ```
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 code from one into another.
Can anyone help me with the syntax and/or any config that is required here? For instance, I am under the impression that I can include the code from b.py in the file a.py by issuing the following statement in a.py
```
import b
```
I'm not having any success with this approach. Specifically I receive this error:
```
ImportError: No module named b
```
Any suggestions?
Thanks,
Matt | 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 `CultureInfo` is passed to `DateTime.ParseExact`, namely `CultureInfo.InvariantCulture`
* The regional settings on the rogue machine is the same as the settings on a machine where the parsing works.
* Yes, the string is in the correct format, which is `dd/MM/yyyy HH:mm:ss` | 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" will translate nicely no matter what the settings are.
Incidentally this trick also works with SQL Server as well :) | 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 process is being run within? if this code is in an asp.net website, the culture is set based upon the users browser settings (passed along in the request).
try doing this in your code to hard-code the current threads culture to see if this help as a way to debug this issue further.
```
// Replace the culture with whatever you required.
System.Threading.Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture("en-GB");
```
tell us what happens when you try that?
\*\* I hate entering answers when we don't have enough info. this is more a suggestion than an answer :) | 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:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_6wlqh1iy.dll' and 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_ro_sgchs.dll'
Source Error:
Line 48: </telerik:RadTabStrip>
Line 49: <telerik:RadMultiPage ID="RadMultiPageControls" Runat="server" SelectedIndex="0">
Line 50: <telerik:RadPageView ID="PageGeneral" runat="server"><uc1:General ID="GeneralControl" runat="server" /></telerik:RadPageView>
Line 51: <telerik:RadPageView ID="PageVehicle" runat="server"><uc1:VehicleList ID="VehicleList" runat="server" /></telerik:RadPageView>
Line 52: <telerik:RadPageView ID="PagePerson" runat="server"><uc1:PersonList ID="PersonList" runat="server" /></telerik:RadPageView>
```
The thing that bothers me most, is if I just keep hitting F5, the page WILL refresh and work as it should. Sometimes it takes several refreshes to do this, others it happens pretty quick. I have not been able to find a solution on the net, as most of the people with this error are upgrading from VS2005 to Web Application, and thus the fix seems to be "Remove your app\_code directory, and change the CodeFile= to CodeBehind=. But, the CodeBehind is old, and not used anymore.
In this instance, I'm getting the error on my General tab, but it can happen of ANY of my user controls when it DOES happen.
Has anyone else seen this with pre-compiled pages? I'm using VS2008 SP1.
The other effect I've seen related to this is when I have a GridView setup with a datasource, and the datasource changes, but the page does not update until several other operations, then all at once all the data is filled in... This makes me think there is some sort of cache issue, or compile-time, time-out or something...
I am using a site.master page, and have checked the @Page and @Master directives... Just for the sake of argument, here are the compiler options it's using...
```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE> "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe" /t:library /utf8output /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\6614ff9a\005164fc_423cc801\PetersDatePackage.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.IdentityModel\3.0.0.0__b77a5c561934e089\System.IdentityModel.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.ReportViewer.Common\9.0.0.0__b03f5f7f11d50a3a\Microsoft.ReportViewer.Common.dll" /R:"C:\WINDOWS\assembly\GAC_32\System.EnterpriseServices\2.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_0-em44qa.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_6wlqh1iy.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_ro_sgchs.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.Build.Utilities\2.0.0.0__b03f5f7f11d50a3a\Microsoft.Build.Utilities.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.ServiceModel\3.0.0.0__b77a5c561934e089\System.ServiceModel.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\6fe979bb\0056bc44_4b94c701\Microsoft.Practices.EnterpriseLibrary.Common.DLL" /R:"C:\WINDOWS\assembly\GAC_32\System.Web\2.0.0.0__b03f5f7f11d50a3a\System.Web.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\ad70f8ed\0010f920_4b94c701\Microsoft.Practices.EnterpriseLibrary.Data.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.ServiceModel.Web\3.5.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\d61e8194\009ae0bd_854ec901\Telerik.Web.UI.DLL" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\98ba2ae7\211fb135_e674c901\CoreAPI.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Extensions\1.0.61025.0__31bf3856ad364e35\System.Web.Extensions.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Management\2.0.0.0__b03f5f7f11d50a3a\System.Management.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\62fa267e\9888875e_bb5cc901\AjaxControlToolkit.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.Build.Framework\2.0.0.0__b03f5f7f11d50a3a\Microsoft.Build.Framework.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Drawing\2.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Code.nufffrfb.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Services\2.0.0.0__b03f5f7f11d50a3a\System.Web.Services.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\52f6447d\f90fd1c8_b475c901\StatisticsAPI.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\955f38e7\982cdc0f_bc5cc901\Validators.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.ReportViewer.WebForms\9.0.0.0__b03f5f7f11d50a3a\Microsoft.ReportViewer.WebForms.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Runtime.Serialization\3.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_nv7t8gs_.dll" /R:"C:\WINDOWS\assembly\GAC_32\System.Data\2.0.0.0__b77a5c561934e089\System.Data.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Configuration\2.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Design\2.0.0.0__b03f5f7f11d50a3a\System.Design.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.WorkflowServices\3.5.0.0__31bf3856ad364e35\System.WorkflowServices.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Mobile\2.0.0.0__b03f5f7f11d50a3a\System.Web.Mobile.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\assembly\dl3\a5daf5e0\0071b5e7_909cc701\Microsoft.Practices.ObjectBuilder.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\Microsoft.ReportViewer.ProcessingObjectModel\9.0.0.0__b03f5f7f11d50a3a\Microsoft.ReportViewer.ProcessingObjectModel.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_atcckswk.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Xml\2.0.0.0__b77a5c561934e089\System.Xml.dll" /out:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_zva2jsmk.dll" /D:DEBUG /debug+ /optimize- /win32res:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\zva2jsmk.res" /nowarn:1659;1699;1701 /d:DBCONVERTPUBLIC;CRYSTALSUPPORT "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_zva2jsmk.0.cs" "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_zva2jsmk.1.cs" "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\statisticsweb\30c716d3\eebad209\App_Web_zva2jsmk.2.cs"
```
Anyone have any ideas where I can even start to look? | 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>
<compilation debug="false" batch="false"></compilation>
</system.web>
</configuration>
```
> This tells ASP.NET to dynamically
> compile individual .aspx/.ascx files
> into separate assemblies. This avoids
> the circular reference issue that
> triggers the exception. | 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)
iIterator = hashSet.iterator();
while(Iterator.hasNext()
{
//doStuff
hashSet.addAll(Object.subObjects);
}
```
Sorry for the poor psuedo code, but basically I want to iterate over subobjects while appending new objects to the end of the list to check.
I could do this using a list, and do something like
```
while(list.size() > 0)
{
//doStuff
list.addAll(Object.subObjects);
}
```
But I would really like to not add duplicate subObjects.
Of course I could just check whether list.contains(each subObject) before I added It.
But I would love to use a Set to accomplish that cleaner.
So Basically is there anyway to append to a set while Iterating over it, or is there an easier way to make a List act like a set rather than manually checking .contains()?
Any comments are appreciated.
Thanks | 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 without duplication.
```
Set visited = new HashSet(); // all visited objects
Queue next = new ArrayDeque(); // objects whose subobjects are to be visited
// NOTE: At all times, the objects in "next" are contained in "visited"
// add the first object
visited.add(obj);
Object nextObject = obj;
while (nextObject != null)
{
// do stuff to nextObject
for (Object o : nextObject.subobjects)
{
boolean fresh = visited.add(o);
if (fresh)
{
next.add(o);
}
}
nextObject = next.poll(); // removes the next object to visit, null if empty
}
// Now, "visited" contains all the visited objects
```
**NOTES:**
* [`ArrayDeque`](http://java.sun.com/javase/6/docs/api/java/util/ArrayDeque.html) is a space-efficient queue. It is implemented as a cyclic array, which means you use less space than a [`List`](http://java.sun.com/javase/6/docs/api/java/awt/List.html) that keeps growing when you add elements.
* "`boolean fresh = visited.add(o)`" combines "`boolean fresh = !visited.contains(o)`" and "`if (fresh) visited.add(o)`". | 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 hybrid if speed is a concern:
```
while(list.size() > 0)
{
//doStuff
for each subObject
{
if (!set.contains(subObject))
{
list.add(subObject);
set.add(subObject)
}
}
}
```
This solution is fast and also conceptually sound - the Set can be thought of as a list of all items seen, whereas the List is a queue of items to work on. It does take up more memory than using a List alone, though. | 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 anything like that. That's the best way to test a method. Here are some links:
[NUnit](http://www.nunit.org/index.php)
[MSUnit](http://msdn.microsoft.com/en-us/library/ms243147.aspx) | 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 correct answer. What am I doing wrong? | 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 sufficient quantity (greater than 10).
*/
COMMIT TRAN A
```
The problem is that there are other transactions happening that consume quantity from our inventory, so between the time that the record is selected and the updates are written in transaction A that record could become an invalid selection because it's quantity might have been lowered below the threshold in the WHERE clause.
So the question is what locking hints should I use in the WITH clause to prevent the selected inventory record from being changed before I finish my updates and commit the transaction?
EDIT:
So thanks to John, a good solution seems to be to set the transaction isolation level to REPEATABLE READ. This will will make sure that "no other transactions can modify data that has been read by the current transaction until the current transaction completes." | 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 locking behaviour in SQL Server and provides examples too.
<http://www.sqlteam.com/article/introduction-to-locking-in-sql-server> | [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 rollback.
Have you looked at [sp\_getapplock](http://msdn.microsoft.com/en-us/library/ms189823(SQL.90).aspx)?
This would allow you to serialise this code (if it's the only update bit) without UPDLOCK blocking
Edit: The problem lies mainly in this code running in 2 different sessions.
With HOLDLOCk or REPEATABLE\_READ, the data will be read in the 2nd session before the 1st session update. With UPDLOCK, noone can read the data in any session. | 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/import.html#regular-packages)
> Python defines two types of packages, regular packages and namespace packages. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an `__init__.py` file. When a regular package is imported, this `__init__.py` file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The `__init__.py` file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.
But just click the link, it contains an example, more information, and an explanation of namespace packages, the kind of packages without `__init__.py`. | 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 the `__init__.py` file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.
The `__init__.py` file is usually empty, but can be used to export selected portions of the package under more convenient name, hold convenience functions, etc.
Given the example above, the contents of the init module can be accessed as
```
import spam
```
This answer is based on [this webpage](https://web.archive.org/web/20200721150953/http://effbot.org/pyfaq/what-is-init-py-used-for.htm). | 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 elegant or simpler way to implement this?
```
switch (ReadDecision)
{
case ReadDecisions.ReadNext:
{
if (UseTimeout)
{
Message = queue.Receive(Timeout);
}
else
{
Message = queue.Receive();
}
break;
}
case ReadDecisions.PeekNext:
{
if (UseTimeout)
{
Message = queue.Peek(Timeout);
}
else
{
Message = queue.Peek();
}
break;
}
case ReadDecisions.ReadMessageId:
{
if (UseTimeout)
{
Message = queue.ReceiveById(Id, Timeout);
}
else
{
Message = queue.ReceiveById(Id);
}
break;
}
case ReadDecisions.PeekMessageId:
{
if (UseTimeout)
{
Message = queue.PeekById(Id, Timeout);
}
else
{
Message = queue.PeekById(Id);
}
break;
}
case ReadDecisions.ReadCorrelationId:
{
if (UseTimeout)
{
Message = queue.ReceiveByCorrelationId(Id, Timeout);
}
else
{
Message = queue.ReceiveByCorrelationId(Id);
}
break;
}
case ReadDecisions.PeekCorrelationId:
{
if (UseTimeout)
{
Message = queue.PeekByCorrelationId(Id, Timeout);
}
else
{
Message = queue.PeekByCorrelationId(Id);
}
break;
}
default:
{
throw new Exception("Unknown ReadDecisions provided");
}
}
``` | 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.Peek(UseTimeout ? Timeout : null);
```
The other idea is you could push the decision structure to the queue class:
```
if(UseTimeout)
Message = queue.PerformAction(ReadDecision, Timeout)
else
Message = queue.PerformAction(ReadDecision)
``` | 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
a.code_item = b.which_id and
a.location_type_code = '15' and
a.code_status = 'R'
```
The table in question returns a list of IP addresses from the database. The key column in question is `code_status`. Some time ago, we realized that one of the IP addresses was no longer valid, so we changed its status to `I` (invalid) to exclude it from appearing in the query's results.
When you execute the query above in SQL Plus, or in SQL Developer, everything is fine. But when you execute it from VB6, the check against `code_status` is ignored, and the invalid IP address appears in the result set.
My first guess was that the results were cached somewhere. But, not being an Oracle expert, I have no idea where to look.
This is *ancient* VB6 code. The SQL is embedded in the application. At the moment, I don't have time to rewrite it as a stored procedure. (I will some day, given the chance.) But, I need to know what would cause this disparity in behavior and how to eliminate it. If it's happening here, it's likely happening somewhere else.
If anyone can suggest a good place to look, I'd be very appreciative. | 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" database connection in SQLPlus as in the code (database, user etc.)?
* Are you sure that that is indeed the SQL sent to the database? (You may check by tracing on the Oracle server or by debugging the VB code). Reformatting may have changed "something".
Off the top of my head I can't think of any "caching" that might "re-insert" the unwanted ip. Hope something from the above gives you some ideas on where to look at. | 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 in dodgy SQL actually be sent to the database. | 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 designers of C# would allow state to change in a closure?
Example:
```
var foo = "hello";
Action bar = () => Console.WriteLine(foo);
bar();
foo = "goodbye";
bar();
```
This will print "hello" for the first call, but the outside state changes for the second call, printing "goodbye." The closure's state was updated to reflect the changes to the local variable. | 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 Haskell, closing over names is identical to closing over values, so the difference between the two types of closure disappears; these languages nevertheless have lexical closures just like C# and JavaScript. | 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 here is ECMA, a standards group. Microsoft is just following their semantics in this case. | 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 RECOMPILE' - I can already do that, but it will give false positive for any commented or literal versions of the text.** | 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 above will also catch procs that have that string commented out, it uses the MS SQL Server specific table syscomments, etc. | 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 different forms of expression, each with its own rules. The description of Array Creation Expressions does not mention calling a constructor. | 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 that link anchor). | 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 list into chunks of a predefined size on the server-side before feeding it into my html template. But things get messy when the list gets so long that you have to scroll. I'm hoping to force it to scroll horizontally only. This is not so easy, since I'm holding each chunk in a floating div, so white-space:nowrap doesn't seem to cut it. Currently, I'm using javascript count the number of list chunks and extend the width of an intermediary container (inside the div that serves as the viewport but containing the divs that contain the data). I want something that looks roughly like this:
```
__________________________
| []..... []..... []..... |
| []..... []..... []..... |
| []..... []..... |
| []..... []..... |
|__________________________|
|<|_____________|___||___|>|
```
So I guess I have two questions:
1. Is there a good way to vertically wrap a list?
2. Is there a good way to force horizontal scrolling when the data gets too large for the viewport? | 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 divs would probably be the best way. | 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 do not know how, and I had searched examples online, but none were what I needed as they were all in int main() and were not specifically what I needed.
In the first data member function, I declare the value I want to be sent to the Heap;
Here's an example of what my first data member function.
```
void Grid::HeapValues()
{
//Initializing Variable
value = 2; //The type is already declared
//Pointers point a type towards the Heap
int* pValue = new int;
//Initialize an a value of in the Heap
*pValue = value;
}
```
And in data member function This is what want:
```
void Grid::AccessHeap()
{
//Extracting heap:
int heap_value = *pValue; //*pValue does not exist in this function
cout << heap_value; //Delays the value 2, which is found
//in the first data member function
}
```
I feel foolish for asking, but I am unable to find the answers and do not how. Does anyone know how to access a value from the heap in a simple way? And I would need it to be able to access in more then two data member function. | 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;
@Autowired
ISimpleService<String> strSvc;
//...
}
```
Of course, my example above does not work:
```
expected single matching bean but found 2: [serviceLong, serviceString]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:243)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:957)
```
My Question: is it possible to provide a similar functionality with minimum modifications to either the Interface or the implementing classes? I know for instance I can use @Qualifiers, but I want to keep things as simple as possible. | 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 liked this pretty well, because it allows us to do "find usage" tracking much better, something you loose with the generics interfaces. | 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 GenericDAO<T, ID>
(...) important is this constructor
public GenericDAOImpl(Class<T> persistentClass) {
this.persistentClass = persistentClass;
}
```
the spring bean definition, notice the abstract="true"
```
<bean id="genericHibernateDAO" class="de.optimum24.av.pers.ext.hibernate.dao.GenericDAOImpl"
abstract="true">
<description>
<![CDATA[
Definition des GenericDAO.
]]>
</description>
<property name="sessionFactory" ref="sessionFactory" />
</bean>
```
**Using this genericDAO without special implementation Class**
```
<bean id="testHibernateChildDao" class="de.optimum24.av.pers.ext.hibernate.dao.GenericDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
<constructor-arg>
<value>de.optimum24.av.pers.test.hibernate.domain.TOChild</value>
</constructor-arg>
</bean>
```
notice the constructor-arg with an concrete Class, if you work with Spring Annotation you need to do:
```
@Autowired
@Qualifier(value = "testHibernateChildDao")
private GenericDAO<TOChild, Integer> ToChildDAO;
```
to distinguish the various versions of genericDao Beans (notice the Qualifier with direct Reference to the Beanname)
**Using this genericDAO with special implementation Class**
the Interface and Class
```
public interface TestHibernateParentDAO extends GenericDAO<TOParent, Integer>{
void foo();
}
public class TestHibernateParentDAOImpl extends GenericDAOImpl<TOParent, Integer>
implements TestHibernateParentDAO {
@Override
public void foo() {
//* no-op */
}
}
```
the Bean Definition, notice the "parent" Reference to the abstract genericDAO above
```
<bean id="testHibernateParentDao" class="de.optimum24.av.pers.test.hibernate.dao.TestHibernateParentDAOImpl"
parent="genericHibernateDAO" />
```
and usage with Spring Annotation
```
@Autowired
private TestHibernateParentDAO ToParentDAO;
``` | 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('myInput').style.display = 'block'
// hiding with jQuery
$('#myInput').hide()
// showing with jQuery
$('#myInput').show()
```
jQuery: <http://jquery.com> | 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 library](http://en.wikipedia.org/wiki/List_of_JavaScript_libraries#JavaScript) which offers different [effects](http://docs.jquery.com/Effects/) (you may want to check out [toggle](http://docs.jquery.com/Effects/toggle)) or components (for example [Accordion](http://docs.jquery.com/UI/Accordion)). | 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 works now, but enter, and arrows do not by default it seems. I've got the key handling part set up but now I need to figure out how to move the focus over in the event handling functions. | 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 record the last-focused field in a variable. Add a "blur" handler to clear the variable upon a blur event for the last-focused field.
If you need to remove the `activeElement` you can use blur; `document.activeElement.blur()`. It will change the `activeElement` to `body`.
Related links:
* [activeElement Browser Compatibility](https://developer.mozilla.org/en/DOM/document.activeElement#Browser_compatibility)
* [jQuery alternative for document.activeElement](https://stackoverflow.com/questions/3328320/jquery-alternative-for-document-activeelement) | 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 by the latest version of Chrome, Safari and Firefox at least. | 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,Fax,Email,BuyNum,PrimaryBusiness,Business,Employees,Job,Value,Volume,SpouseBusiness,DateAdded,ConstructionWorkType,UserPurchaser,DecisionMaker,SafetyProducts,NearFuturePurchase,RepContact,Winner) VALUES('39610','111111','SMITH','JIM','COMPANY','1000 ROAD STREET','','PITTSBURGH','PA','15219','','5555555555','5555555555','PERSON@EXAMPLE.NET','','','0000000000000000000','','','','','0?','Fri Jan 30 14:20:08 GMT-0500 2009','other','neither','no','gas_detection','no','no','winner')
```
I know that the app can connect to the database, because it creates the table just fine. Here's the schema for the table for your reference:
```
CREATE TABLE Attendee (AttendeeId TEXT PRIMARY KEY,ShowCode TEXT,LastName TEXT,FirstName TEXT,Company TEXT,Address TEXT,Address2 TEXT,City TEXT,State TEXT,ZipCode TEXT,Country TEXT,Phone TEXT,Fax TEXT,Email TEXT,BuyNum TEXT,PrimaryBusiness TEXT,Business TEXT,Employees TEXT,Job TEXT,Value TEXT,Volume TEXT,SpouseBusiness TEXT,DateAdded TEXT,ConstructionWorkType TEXT,UserPurchaser TEXT,DecisionMaker TEXT,SafetyProducts TEXT,NearFuturePurchase TEXT,RepContact TEXT, Winner TEXT)
```
There is a good chance that there is an error in the INSERT statement, because if I try to execute it on a separate Adobe Air SQLite admin program, it throws an ambiguous error (#3115).
Thanks for any insight you might have.
EDIT:
For those wondering, if I make a simple table, thus:
```
CREATE TABLE Attendee (AttendeeId TEXT)
```
And try to insert, thus:
```
INSERT INTO Attendee (AttendeeId) VALUES('09283A')
```
I still get error #3115. | ```
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", "UserPurchaser", "DecisionMaker", "SafetyProducts", "NearFuturePurchase", "RepContact", "Winner") values ('39610', '111111', 'SMITH', 'JIM', 'COMPANY', '1000 ROAD STREET', '', 'PITTSBURGH', 'PA', '15219', '', '5555555555', '5555555555', 'PERSON@EXAMPLE.NET', '', '', '0000000000000000000', '', '', '', '', '0?', 'Fri Jan 30 14:20:08 GMT-0500 2009', 'other', 'neither', 'no', 'gas_detection', 'no', 'no', 'winner');
```
Try this one, it was computer generated. | 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 this action earlier than the 5 minutes.
Does anybody have any ideas?
Thanks
Ed | 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 changes almost instantaneously and deal with appropriately.
In order to use this Class you will need to Enable Query Notifications on the database you wish to query see: [Enabling Query Notifications](http://msdn.microsoft.com/en-us/library/ms172133(VS.80).aspx)
A good example of how to use this class in a Windows Application is found [here](http://msdn.microsoft.com/en-us/library/a52dhwx7(VS.80).aspx). | 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 commands (not the best option though). | 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 then and we do get a lot of submissions).
I would like to implement a system that could store the user's details if the mail sending function returns with an error code. Then on every further submission, check for any stored submissions and try to send them off to me.
But how to store the data?
I'm using python so I thought about using [shelve](http://docs.python.org/library/shelve.html) (single file semi-database). Or maybe someone could suggest a better data format? (I do think a full database solution would be overkill.)
The problem I see with a single file approach is *race-conditions*: two or more failed emails at the same time would cause two edits to the data file resulting in data corruption.
So what to do? Multi-file solution, file locking or something else? | 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 service will just try again later, data and user confidence is never lost. | 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#typesseq-common>
```
Operation | Result
s * n or n * s | n shallow copies of s concatenated
```
Example:
```
>>> 'a' * 5
'aaaaa'
>>> 5 * 'b'
'bbbbb'
``` | 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 created
* Number of comments (not so good as max comments total about 10 at the moment)
+ `comments` table has comment date
I have searched around, but don't want user authority to play a part, but most algorithms include that.
I also need to find out if it's better to do the calculation in the MySQL that fetches the data or if there should be a PHP/cron method every hour or so.
I only need 20 illustrations to populate the home page. I don't need any sort of paging for this data.
How do I weight age against votes? Surely a site with less submission needs less weight on date added? | 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 changing after a period of time of your choosing.
For instance, here's a pseudo-example of something you might want to try. Of course, you'll want to adjust how much weight you're attributing to each category based on your own experience with your site. Comments are rare, but take more effort from the user than a favorite/vote, so they probably should receive more weight.
```
score = (votes / 10) + comments
age = UNIX_TIMESTAMP() - UNIX_TIMESTAMP(date_created)
if(age < 86400) score = score * 1.5
```
This type of approach would give a bonus to new content uploaded in the past day. If you wanted to approach this in a similar way only for content that had been favorited or commented on recently, you could just add some WHERE constraints on your query that grabs the score out from the DB.
There are actually two big reasons NOT to calculate this ranking on the fly.
1. Requiring your DB to fetch all of that data and do a calculation on every page load just to reorder items results in an expensive query.
2. Probably a smaller gotcha, but if you have a relatively small amount of activity on the site, small changes in the ranking can cause content to move pretty drastically.
That leaves you with either caching the results periodically or setting up a cron job to update a new database column holding this score you're ranking by. | 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 to cache the result of the query. Maybe something like
```
SELECT images.url FROM images ORDER BY (NOW() - images.date) / COUNT((SELECT COUNT(*) FROM votes WHERE votes.image_id = images.id)) DESC LIMIT 20
```
but my SQL is rusty ;-)
Taking a simple average will, of course, bias in favor of new images showing up on the front page. If you want to remove that bias, you could, say, count only those votes that occurred within a certain time limit after the image being posted. For images that are more recent than that time limit, you'd have to normalize by multiplying the number of votes by the time limit then dividing by the age of the image. Or alternatively, you could give the votes a continuously varying weight, something like `exp(-time(vote) + time(image))`. And so on and so on... depending on how particular you are about what this algorithm will do, it could take some experimentation to figure out what formula gives the best results. | 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 returns strings. Is there something like Beanutils.getProperty that will return a cast-able object? Or another, smarter way to work with two similar classes that don't share an interface?
thanks,
-Morgan | 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 getProgram() { return program; } ... };
...
```
Then you just need instanceof/cast pairs. You can put this in a method so that you only need to do it once.
```
public static Program getProgram(Object obj) {
if (obj instanceof LibA) {
return ((LibA)obj).getProgram();
} else if (obj instanceof LibB) {
return ((LibB)obj).getProgram();
} else {
throw new IllegalArgumentException(obj+" doesn't have a known getProgram");
// Or an appropriate application exception.
}
}
```
Alternatively you might want to use an adapter:
```
public interface ProgramContainer {
Program getProgram();
...
}
public class LibAContainer implements ProgramContainer {
private final LibA libA;
public LibAContainer(LibA libA) {
this.libA = libA;
}
public Program getProgram() {
return libA.getProgram();
}
...
}
``` | 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 buttons are dynamically created they're not as easy to grab. I was curious to what the best method for grabbing the button's click event would be.
I understand its possible using dopostback; however, I'm not sure how to implement it nor have I tried because I have also read dopostback method is not a very good one to use. Why is that? | 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 DetailsView1.ItemCommand
If e.CommandName = "myButton" Then
//'myButton press event logic here
End If
End Sub
```
Thanks for your help guys.. I really appreciate it. Your answers will be helpful in the future I'm sure. | 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 add a handler:
> ```
> function rowbound(Object sender, GridViewRowEventArgs e)
> {
> if(e.Row.RowType == DataControlRowType.DataRow)
> {
> var b = e.Row.FindControl("btn") as Button;
> b.Click += new EventHandler(handleBtnClick);
> }
> }
> ``` | .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
#define _SECURE_SCL_THROWS 1
#include "map"
#include "string"
#include "exception"
#include "iostream"
using namespace std;
void main(void)
{
map<string, string> map_test;
map<string, string>::iterator iter_map_test;
map_test [ "AAAAA" ] = "11111";
map_test [ "BBBBB" ] = "22222";
map_test [ "CCCCC" ] = "33333";
iter_map_test = map_test.find ("BBBBB");
map_test.erase ("BBBBB");
try
{
string value = (*iter_map_test).second;
}
catch ( exception & e )
{
cout << e.what() << endl;
}
catch ( ... )
{
cout << "generic exception." << endl;
}
}
``` | `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 STL and threading:
* [MSDN](http://msdn.microsoft.com/en-us/library/c9ceah3b.aspx)
* [SGI](http://www.sgi.com/tech/stl/thread_safety.html)
* [GCC](http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch03s05.html#manual.intro.using.concurrency.thread_safety) | 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 other than the one being deleted. Unfortunately there isn't a `is_iterator_valid()` method to validate iterators that you hold.
It may be possible to implement something like [hazard pointers](http://en.wikipedia.org/wiki/Hazard_pointer), and TBB has some workarounds to the problem as well. | 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 logic so it forces you to separate concerns. Templating with PHP can lure you to walk around the templating principles and start writing code soup again.
... and both are quite negligible when compared to cons.
Small example:
**PHP**
```
<h1><?=$title?></h1>
<ul>
<? foreach ($items as $item) {?>
<li><?=$item?></li>
<? } ?>
</ul>
```
**Smarty**
```
<h1>{$title}</h1>
<ul>
{foreach item=item from=$items}
<li>{$item}</li>
{/foreach}
</ul>
```
I really don't see any difference at all. | 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 Smarty's hardly solving your concern separation problem.
See also:
* [PHP as a template language or some other templating script](https://stackoverflow.com/questions/62605/php-as-a-template-language-or-some-other-php-templating-script)
* [What is the best way to insert HTML via PHP](https://stackoverflow.com/questions/261338/what-is-the-best-way-to-insert-html-via-php) | 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 understand PHP, just to know to leave the special tags alone. They may have to learn a few simple semantics for a few tags but that is a lot simpler than learning the whole language.
Also, by splitting the page into separate files, both programmer and designer can work on the same 'page' at once, checking in to source control as they need, without conflicts. Designers can test their template visuals against a stable version of the code while the programmer is making other, potentially breaking changes, against their own copy. But if these people were both editing the same file and had to merge in different changes, you can encounter problems.
It also enforces good programming practice in keeping business logic away from presentation logic. If you put your business logic mixed in with the presentation then you have a more difficult time extracting it if you need to present it differently later. Different modes of presentation in web apps are increasingly popular these days: RSS/ATOM feeds, JSON or AJAX responses, WML for handheld devices, etc. With a template system these can often be done entirely with a template and no or little change to anything else.
Not everybody will need or appreciate these benefits however. PHP's advantage over Java/Python/Ruby/etc is that you can quickly hack up web pages with some logic in them, and that's all well and good. | 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), but not a total solution even for just music files.
Does such a library exists? Will this become another hobby project?
Thanks for the answers | 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:
[](https://i.stack.imgur.com/ypP2Z.png)
(source: [thegreenplace.net](http://eli.thegreenplace.net/files/temp/hebfilenameshot.png))
Now consider this code that goes over the files in this directory:
```
files = os.listdir('test_source')
for f in files:
pf = os.path.join('test_source', f)
print pf, os.path.exists(pf)
```
The output is:
```
test_source\ex True
test_source\joe True
test_source\mie.txt True
test_source\__()'''.txt True
test_source\????.txt False
```
Notice how `os.path.exists` thinks that the hebrew-named file doesn't even exist?
How can I fix this?
ActivePython 2.5.2 on Windows XP Home SP2 | 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)
```
===>
```
test_source\ex True
test_source\joe True
test_source\mie.txt True
test_source\__()'''.txt True
test_source\????.txt True
```
Some important observations here:
* Windows XP (like all NT derivatives) stores *all* filenames in unicode
* `os.listdir` (and similar functions, like `os.walk`) should be passed a unicode string in order to work correctly with unicode paths. Here's a quote from the aforementioned link:
> os.listdir(), which returns filenames,
> raises an issue: should it return the
> Unicode version of filenames, or
> should it return 8-bit strings
> containing the encoded versions?
> os.listdir() will do both, depending
> on whether you provided the directory
> path as an 8-bit string or a Unicode
> string. If you pass a Unicode string
> as the path, filenames will be decoded
> using the filesystem's encoding and a
> list of Unicode strings will be
> returned, while passing an 8-bit path
> will return the 8-bit versions of the
> filenames.
* And lastly, `print` wants an ascii string, not unicode, so the path has to be encoded to ascii. | 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() returns a
> list of strings, filenames that cannot
> be decoded properly are omitted rather
> than raising UnicodeError. | 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 succession. Judging from the exception I'd assume it's a network issue, however the Database is on the same box as my Application.
I don't have a stack trace and this is one of those irritating "Works on my machine" problems" where it Borks when I put it on a client site.
Unfortunately I've got to throw together something that will fix this/diagnose but the client site only throws data to my app between 5pm and 9 pm when I'm out of the office...
I've got a few hours to work out my contingencies though...
Any thoughts.
**Problem solved:**
It was a synchronization issue. | 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 ObjectOutputStream(bout);
oos.writeObject(theObjectIWantTheSizeOf);
oos.close();
System.out.println("The object size is: " + bout.toByteArray().length:
``` | 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 answers I had received) would the solution still apply for a CASEed aliased column?
```
SELECT
CASE
WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS 'FullName'
FROM customers
GROUP BY
LastName, FirstName
```
And the answer is yes it does still apply. | 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
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS FullName
FROM customers
) as sub
GROUP BY FullName
``` | 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 one that works. Which means that it may not always pick the one you expect, so it can become a subtle source of bugs.
Further, static\_cast is a lot easier to search for or do search/replace 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 introduced to give programmers a chance to state their intentions more clearly and for the compiler to catch more errors. [...]
In particular, C++ makes the distinction between `static_cast` and `reinterpret_cast`:
> The idea is that conversions allowed by static\_cast are somewhat less likely to lead to errors than those that require reinterpret\_cast. In principle, it is possible to use the result of a static\_cast without casting it back to its original type, whereas you should always cast the result of a reinterpret\_cast back to its original type before using it to ensure portability. | 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 along the lines of:
```
MSBuild -DefineProperty:DEMO MySolution.sln
```
Does such functionality exist? | [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 GregorianCalendar();
try{
if(connection != null){
connection.connect();
//200 is the expected HTTP_OK response
error = processResponseCode(connection.getResponseCode());
connection.disconnect();
} else{
error = false;
}
}catch(java.net.UnknownHostException uhe){
... }
catch(Exception e){
... }
return error;
}
```
The closest match to the Java pattern in c# has much higher results of false positives (mostly due to timeouts - which has a default period of 100000ms).
```
protected bool connectedToUrl = false;
response = null;
HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(this.getUri());
webreq.Credentials = CredentialCache.DefaultCredentials;
WebResponse res = null;// webreq.GetResponse();
try
{
WebRequest request = WebRequest.Create(this.getUri()) as WebRequest;
request.Credentials = CredentialCache.DefaultCredentials;
if (request != null)
{
// Get response
res = webreq.GetResponse();
connectedToUrl = processResponseCode(res);
}
else
{
logger.Fatal(getFatalMessage());
string error = string.Empty;
}
}
catch (Exception e)
{
throw e;
}
return connectedToUrl;
}
```
I have tried various patterns in c# to match the effectiveness of the quoted Java code, to no avail.
Any ideas? | 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 finalized), it's holding onto the connection. You can only have a certain number (2 by default, I believe) of connections to any one host at a time, hence the timeouts. When you dispose the response, it allows another request to use the same connection. | 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 any way to disable the error from the system command? | 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 operation system interface. Try `execvp` (see `man execvp`) in linux/unix or the CreateProcess function for windows systems, which uses the Windows API that allows great control over error handling and other stuff. | 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.
If you are on windows, try "hello.exe" | 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 the default 'zero-value' for value types.
If you can't use LINQ, then your approach is technically correct and no different than creating an enumerator using the `GetEnumerator` and `MoveNext` methods to retrieve the first result (this example assumes enumerable is an `IEnumerable<Elem>`):
```
Elem e = myDefault;
using (IEnumerator<Elem> enumer = enumerable.GetEnumerator()) {
if (enumer.MoveNext()) e = enumer.Current;
}
```
[Joel Coehoorn](https://stackoverflow.com/users/3043/joel-coehoorn) mentioned `.Single()` in the comments; this will also work, if you are expecting your enumerable to contain exactly one element - however it will throw an exception if it is either empty or larger than one element. There is a corresponding `SingleOrDefault()` method that covers this scenario in a similar fashion to `FirstOrDefault()`. However, [David B](https://stackoverflow.com/users/8155/david-b) explains that `SingleOrDefault()` may still throw an exception in the case where the enumerable contains more than one item.
Edit: Thanks [Marc Gravell](https://stackoverflow.com/users/23354/marc-gravell) for pointing out that I need to dispose of my `IEnumerator` object after using it - I've edited the non-LINQ example to display the `using` keyword to implement this pattern. | 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-python-code) | 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 extract the local variables from the stack.
```
def findlocals(search, startframe=None, trace=False):
from pprint import pprint
import inspect, pdb
startframe = startframe or sys.last_traceback
frames = inspect.getinnerframes(startframe)
frame = [tb for (tb, _, lineno, fname, _, _) in frames
if search in (lineno, fname)][0]
if trace:
pprint(frame.f_locals)
pdb.set_trace(frame)
return frame.f_locals
```
Usage:
```
>>> def screwyFunc():
a = 0
return 2/a
>>> screwyFunc()
Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
screwyFunc()
File "<pyshell#55>", line 3, in screwyFunc
return 2/a
ZeroDivisionError: integer division or modulo by zero
>>> findlocals('screwyFunc')
{'a': 0}
``` | `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 remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.
Features:
* GPL license. Winpdb is Free Software.
* Compatible with CPython 2.3 through 2.6 and Python 3000
* Compatible with wxPython 2.6 through 2.8
* Platform independent, and tested on Ubuntu Gutsy and Windows XP.
* User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.
Alternative: `Fork of the official winpdb` ([winpdb-reborn · PyPI](https://pypi.org/project/winpdb-reborn/) / [GitHub](https://github.com/bluebird75/winpdb))
[](https://i.stack.imgur.com/1oveL.jpg)
(source: [winpdb.org](http://winpdb.org/images/screenshot_winpdb_small.jpg)) | 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 physical pages; additionally - and this is the part that's killing me - there need to be headers and footers on these pages.
Much as I would like to, I can't simply make the WebBrowser print to a file - the header/footer options it supports aren't anywhere near sophisticated enough. So I'm casting about trying to figure out what the right technology is for generating these images.
It seems likely to me (though it's not mandatory) that what I'll end up doing is producing PDF versions of the HTML documents (so that I can add headers and footers) and then rendering the PDFs as TIFFs, which is the ultimate format that the imaging system wants. So what I'm considering:
* Use some kind of XHTML-to-PDF conversion software. The problem with this is that without doing a lot of evaluation and testing I can't figure out if the products I've looked at even have the ability to do what I need, which is to take existing XHTML documents, decorate them with headers and footers and paginate them.
* Use XSL-FO to generate the PDFs. Being a ninja-level XSLT geek helps here (that's how I'm producing the XHTML in the first place), but it still seems like an awkward and slow solution with a lot of moving parts. Also this means I'm sticking a big clunky Java program into the middle of my nice clean .NET system, though I'm certainly enough of a grownup to do that if it's the right answer.
* Use some other technology that I haven't even thought of yet, like LaTeX. Maybe there's some miraculous page-imaging tool that turns XHTML directly into TIFFs with page headers and footers. That would be ideal.
My primary concerns are:
* I'm building a commercial product; whatever technology I use needs to be affordable and supportable. It doesn't have to be free.
* I don't want to disappear down a rabbit hole for three months banging on this stuff to get it to work. This intuitively seems like the kind of problem space where I can lose a lot of time just evaluating and rejecting tools.
* Whatever solution I adopt needs to be relatively immune to formatting changes in the XHTML. The whole reason I'm using XSLT and producing XHTML in the first place is that the documents I'm producing are being dynamically assembled using business rules that change all the time.
I've spent a lot of time searching for alternatives and haven't found anything that's obviously the answer. But maybe one of you fine people has already solved this problem, and if so, I would like to stand on your shoulders. | **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 [sample conversion](http://cricketsoft.com/SampleConversion.aspx).
**Edit** (2009-03-23 12:30 PM PST, published to CodePlex)
I developed a solution for this and posted it to [CodePlex](http://www.codeplex.com/XhtmlToTiff). The published [version 2.0](http://xhtmltotiff.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=25117) is written using the WPF MVVP pattern. TIFF files (one per page) are output to c:\Temp\XhtmlToTiff. XAML and XPS formats are created as well. A compiled,installable version is available at **[CricketSoft.com](http://cricketsoft.com)**
---
Have you tried the "[Microsoft XPS Document Writer](http://www.microsoft.com/whdc/xps/viewxps.mspx)"? This a software-only printer that generates paged output from a variety of sources, including web pages.
There is an SDK for working with XPS documents and Open XML docs in general. Here is a How-to article by Beth Massi: "[Accessing Open XML Document Parts with the Open XML SDK](http://blogs.msdn.com/bethmassi/archive/2008/07/30/accessing-openxml-document-parts-with-the-openxml-sdk.aspx)".
+tom | 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://sourceforge.net/projects/nfop/>
Hope that helps. | 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/package-summary.html)
I am currently doing something like this:
```
interface Convertor
{
A encode( B b );
B decode( A a );
}
```
The rationale for putting them in one interface is that you can centralize the implementations and fix any protocol changes in one place. Any thoughts on this ? | 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 both. So the implementation is shared, but user code sees the encoder and decoder as separate and independent concepts. | 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 Interface Segregation Principle. | 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-table-of-permissions-granted-to-database-tables-for-a-databas), but I could not get the selected answer's solution working (if someone could provide a better example of how to use that, it would help as well) | 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
, CASE WHEN class = 0 THEN DB_NAME()
WHEN class = 1 THEN OBJECT_NAME(major_id)
WHEN class = 3 THEN SCHEMA_NAME(major_id) END [Securable]
, USER_NAME(grantee_principal_id) [User]
, permission_name
, state_desc
FROM sys.database_permissions
```
Also, db\_datawriter would need to be checked for membership because it gives implicit INSERT, UPDATE, and DELETE rights, meaning you won't see it show up in the permission DMVs or their derivatives. | 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
class_desc
,USER_NAME(grantee_principal_id) as user_or_role
,CASE WHEN class = 0 THEN DB_NAME()
WHEN class = 1 THEN ISNULL(SCHEMA_NAME(o.uid)+'.','')+OBJECT_NAME(major_id)
WHEN class = 3 THEN SCHEMA_NAME(major_id) END [Securable]
,permission_name
,state_desc
,'revoke ' + permission_name + ' on ' +
isnull(schema_name(o.uid)+'.','')+OBJECT_NAME(major_id)+ ' from [' +
USER_NAME(grantee_principal_id) + ']' as 'revokeStatement'
,'grant ' + permission_name + ' on ' +
isnull(schema_name(o.uid)+'.','')+OBJECT_NAME(major_id)+ ' to ' +
'[' + USER_NAME(grantee_principal_id) + ']' as 'grantStatement'
FROM sys.database_permissions dp
LEFT OUTER JOIN sysobjects o
ON o.id = dp.major_id
-- where major_id >= 1 -- ignore sysobjects
order by
class_desc desc
,USER_NAME(grantee_principal_id)
,CASE WHEN class = 0 THEN DB_NAME()
WHEN class = 1 THEN isnull(schema_name(o.uid)+'.','')+OBJECT_NAME(major_id)
WHEN class = 3 THEN SCHEMA_NAME(major_id) end
,permission_name
``` | 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].
Thankfully, no where do I let users save data to a database and display back to other uesrs, so I THINK people would only be able to hack themselves with this problem, but I still want to fix it.
The recommendation is to do this:
```
echo htmlentities($_POST[‘input’], ENT_QUOTES, ‘UTF-8’);
```
But currently I need to get this patched up asap, then go fix on a case by case basis.
I have a header file I include on every page on the site, I know it's bad form, but what could blow up if I did:
```
array_walk($_POST, 'htmlentities');
```
I'll need to do it for COOKIE and GET as well. I never use \_REQUEST.
Thanks | 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 database may do automatically) across &-encoded characters. It's not that likely to lead to security breaches, although you can't tell without looking at the app in a lot more detail.
If you start encoding things in $\_SESSION each time, you'll get multiply-encoded too-long strings like &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp; very quickly.
> I THINK people would only be able to hack themselves
Or, an attacker on another web page could redirect or iframe to yours, with enough script injected to display a fake login box that looks just like your site's, harvest the username and password or automatically delete their account. Stuff like that. Not very good.
> The recommendation is to do this: echo htmlentities($\_POST[‘input’], ENT \_QUOTES, ‘UTF-8’);
No need for htmlentities and all those parameters - use htmlspecialchars.
You can save yourself a few keypresses using something like:
```
function h($s) { echo(htmlspecialchars($s)); }
...
<?php h($POST['input']) ?>
```
It's really not that much extra hassle. | 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 sending an email), people would see < instead of <, etc.
You probably just want to escape when outputting. | 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**
```
function User( name, age ){
this.name = name;
this.age = age;
}
// Add a new function to the object prototype
User.prototype.getName = function(){
return this.name;
};
User.prototype.getAge = function(){
return this.age;
};
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
```
I'm still learning about the *prototype* property, so I tried writing something similar:
**Function #2**
```
function User (name, age ) {
this.name = name;
this.age = age;
this.getName = function() {
return this.name;
};
this.getAge = function() {
return this.age;
};
}
var user = new User( "Bob", 44 );
console.log("User: " + user.getName() + ", Age: " + user.getAge());
```
It doesn't use the *prototype* property to create the getName and getAge functions, but the output is the same as John's example.
I took it one step further, and created this:
**Function #3**
```
var User = {
name: "",
age: 0,
setName: function(name) {
this.name = name;
},
setAge: function(age) {
this.age = age;
},
getName: function() {
return this.name;
},
getAge: function() {
return this.age;
}
};
User.setName("Bob");
User.setAge(44);
console.log("User: " + User.getName() + ", Age: " + User.getAge());
```
Again - it looks different than John's example (and I had to add setter methods), but the output is the same.
**Question #1** - what is the difference between the 3 functions? What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).
**Question #2** - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand? Can the {...} shorthand have constructors?
Thanks in advance for helping me learn!
**EDIT**
I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:
```
var user = new User("Bob", 44);
```
Just like in Function #1 - or is that not possible?
**EDIT #2**
Wow! Thanks everyone for the awesome answers. That really makes it a lot more clear to me. So if I understand correctly, the difference between #1 and #2 aren't too much. If I only ever create one "User" object - they probably aren't different at all. But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.
I really appreciate all of the great answers - Thanks! | 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 see any difference in the output.
The {...} shorthand *is* a constructor. When evaluated, it constructs a new "Object" with the given properties. When you run "new User(...)", it constructs a new "User". You happen to have created an Object with the same behavior as a User, but they are of different types.
Response to comment:
You can't, directly. You could make a function that creates a new object as per #3. For example:
```
function make_user(name, age) {
return {
name: name,
age: age,
getName: function() { return name; },
getAge: function() { return age; },
};
}
var user = make_user("Joe", "18");
``` | 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_dummies>
The differences between 1, 2, and 3 are as follows:
1) Is an example of adding new methods to an existing object.
2) Is the same as #1 except some methods are included in the object in the User function.
3) Is an example of defining an object using [JSON](http://en.wikipedia.org/wiki/JSON). The shortcoming is that you cannot use new (at least not with that example) to define new instances of that object. However you do get the benefit of the convenient JSON coding style.
You should definitely read up on JSON if you don't know it yet. JavaScript will make a lot more sense when you understand JSON.
*edit*
If you want to use new in function #3 you can write it as
```
function User() {
return {
name: "",
age: 0,
setName: function(name) {
this.name = name;
},
setAge: function(age) {
this.age = age;
},
getName: function() {
return this.name;
},
getAge: function() {
return this.age;
}
};
}
```
Of course all of those functions and properties would then be public. To make them private you need to use closures. For example you could make age and name private with this syntax.
```
function User() {
var age=0;
var name="";
return {
setName: function(name_) {
name = name_;
},
setAge: function(age_) {
age = age_;
},
getName: function() {
return name;
},
getAge: function() {
return age;
}
};
}
``` | 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 its not much better than parsing command-line tools, in the sense that I'll need to implement some sort of custom parsing for every piece of data I need.
I'm looking for something along the lines of c libraries for Windows or MacOS that provides this information through a c-based systems API, however I'm having no luck with Google. | 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/xref/onnv/onnv-gate/usr/src/cmd/stat/iostat/iostat.c) source.
For information about processus, I'd look at [ps](http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/cmd/ps/ps.c). | 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 4773 Jun 10 2008 .bash_history
-rw-r--r-- 1 vuser 1012 Dec 9 2007 .bashrc
lrwxrwxrwx 1 root 7 Dec 9 2007 .profile -> .bashrc
drwx------ 2 vuser 4096 Jan 30 01:08 .spamassassin
drwxr-xr-x 2 vuser 4096 Dec 9 2007 backup.upgrade_3_7
dr-xr-xr-x 2 root 4096 Dec 10 2007 bin
```
etc...
however, I need the actual timestamp in seconds or milliseconds so that I can determine if I want that file or not.
I assume this has something to do with the FTP server's configuration? but I'm kind of stumped. | 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://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPFile.html#getTimestamp())'s on, you then should be able to get just the ones you need. | 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" command for querying modification times. If you are lucky, the servers that you want to talk to have implemented this extension. | 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 to control program flow. Is there a keys.exists() method or something? | 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 Resources.resx, you'll probably create it in the root of the project, in which case the thing you were doing before, namely this:
```
rm = new ResourceManager("MyNamespace.MyResource", assembly);
```
will work. This is exactly what happened to me today, and I'm adding this post in the hope that it will spare someone some grief. | 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 example, doing :
```
var r = new ResourceManager("MyResource", assembly);
```
instead of
```
var r = new ResourceManager("MyNamespace.MyResource", assembly);
```
will result in a MissingManifestResourceException. | 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 find any good resource on this, no open source API's or even quick examples of how to do each step. Even here DCOM or dcomcnfg returns few results and none really about how to set/verify/list security.
If anybody has some pointers to an open API or some examples I would appreciate it. | 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 set the machine's default access (rather than per-process), you would be accessing registry key HKEY\_LOCAL\_MACHINE\SOFTWARE\Microsoft\Ole\DefaultAccessPermission. However, in my initial attempts to access this key using the System.Security.AccessControl.RawACL class were failing.
As Daniel's code indicate's the value is not actually an ACL, but really is a SecurityDescriptor with the ACL in it.
So, even though I know this post is old, I'm going to post my solution for checking and setting the security settings and adding NetworkService for Default local access. Of course, you could take this and make it better I'm sure, but to get started you would simply need to change the key and the access mask.
```
static class ComACLRights{
public const int COM_RIGHTS_EXECUTE= 1;
public const int COM_RIGHTS_EXECUTE_LOCAL = 2;
public const int COM_RIGHTS_EXECUTE_REMOTE = 4;
public const int COM_RIGHTS_ACTIVATE_LOCAL = 8;
public const int COM_RIGHTS_ACTIVATE_REMOTE = 16;
}
class Program
{
static void Main(string[] args)
{
var value = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Ole", "DefaultAccessPermission", null);
RawSecurityDescriptor sd;
RawAcl acl;
if (value == null)
{
System.Console.WriteLine("Default Access Permission key has not been created yet");
sd = new RawSecurityDescriptor("");
}else{
sd = new RawSecurityDescriptor(value as byte[], 0);
}
acl = sd.DiscretionaryAcl;
bool found = false;
foreach (CommonAce ca in acl)
{
if (ca.SecurityIdentifier.IsWellKnown(WellKnownSidType.NetworkServiceSid))
{
//ensure local access is set
ca.AccessMask |= ComACLRights.COM_RIGHTS_EXECUTE | ComACLRights.COM_RIGHTS_EXECUTE_LOCAL | ComACLRights.COM_RIGHTS_ACTIVATE_LOCAL; //set local access. Always set execute
found = true;
break;
}
}
if(!found){
//Network Service was not found. Add it to the ACL
SecurityIdentifier si = new SecurityIdentifier(
WellKnownSidType.NetworkServiceSid, null);
CommonAce ca = new CommonAce(
AceFlags.None,
AceQualifier.AccessAllowed,
ComACLRights.COM_RIGHTS_EXECUTE | ComACLRights.COM_RIGHTS_EXECUTE_LOCAL | ComACLRights.COM_RIGHTS_ACTIVATE_LOCAL,
si,
false,
null);
acl.InsertAce(acl.Count, ca);
}
//re-set the ACL
sd.DiscretionaryAcl = acl;
byte[] binaryform = new byte[sd.BinaryLength];
sd.GetBinaryForm(binaryform, 0);
Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Ole", "DefaultAccessPermission", binaryform, RegistryValueKind.Binary);
}
}
``` | 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 permissions for DCOM objects, which are stored in the LaunchPermission and AccessPermission registry key values. These are serialized security descriptors, which you can access by passing the binary data through `RawSecurityDescriptor`. This class simplifies a lot of the details in a delicious .NET-y fashion, but you still have to attend to all the logical details regarding Windows ACL, and you have to make sure to write the security descriptor back to the registry by using `RawSecurityDescriptor.GetBinaryForm`.
The method I created was called `EditOrCreateACE`. This method will either edit an existing ACE for an account, or insert a new one, and ensure that the access mask has the passed flags set. I attach it here as an **example**, this is by no means any authority on how to deal with it, since I know very little of Windows ACL stuff still:
```
// These are constants for the access mask on LaunchPermission.
// I'm unsure of the exact constants for AccessPermission
private const int COM_RIGHTS_EXECUTE = 1;
private const int COM_RIGHTS_EXECUTE_LOCAL = 2;
private const int COM_RIGHTS_EXECUTE_REMOTE = 4;
private const int COM_RIGHTS_ACTIVATE_LOCAL = 8;
private const int COM_RIGHTS_ACTIVATE_REMOTE = 16;
void EditOrCreateACE(string keyname, string valuename,
string accountname, int mask)
{
// Get security descriptor from registry
byte[] keyval = (byte[]) Registry.GetValue(keyname, valuename,
new byte[] { });
RawSecurityDescriptor sd;
if (keyval.Length > 0) {
sd = new RawSecurityDescriptor(keyval, 0);
} else {
sd = InitializeEmptySecurityDescriptor();
}
RawAcl acl = sd.DiscretionaryAcl;
CommonAce accountACE = null;
// Look for the account in the ACL
int i = 0;
foreach (GenericAce ace in acl) {
if (ace.AceType == AceType.AccessAllowed) {
CommonAce c_ace = ace as CommonAce;
NTAccount account =
c_ace.SecurityIdentifier.Translate(typeof(NTAccount))
as NTAccount;
if (account.Value.Contains(accountname)) {
accountACE = c_ace;
}
i++;
}
}
// If no ACE found for the given account, insert a new one at the end
// of the ACL, otherwise just set the mask
if (accountACE == null) {
SecurityIdentifier ns_account =
(new NTAccount(accountname)).Translate(typeof(SecurityIdentifier))
as SecurityIdentifier;
CommonAce ns = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed,
mask, ns_account, false, null);
acl.InsertAce(acl.Count, ns);
} else {
accountACE.AccessMask |= mask;
}
// Write security descriptor back to registry
byte[] binarySd = new byte[sd.BinaryLength];
sd.GetBinaryForm(binarySd, 0);
Registry.SetValue(keyname, valuename, binarySd);
}
private static RawSecurityDescriptor InitializeEmptySecurityDescriptor()
{
var localSystem =
new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
var new_sd =
new RawSecurityDescriptor(ControlFlags.DiscretionaryAclPresent,
localSystem, localSystem, null,
new RawAcl(GenericAcl.AclRevision, 1));
return new_sd;
}
```
Do note that this code is by no means perfect. If the entire registry key value for these ACL is missing in the registry, the ACL that is synthesized will ONLY grant access to the passed account and nothing else. I'm also sure there are lots of error conditions I've not handled properly and details I've glossed over. Again, it's an **example** of how to deal with DCOM ACL in .NET. | 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 - Browsing", disabled script debugging for IE and other and unchecked the "display a notification for every script error". All I got was a different error message, but I still have to close a LOT of alert messages.
I think I am going insane.
EDIT: Before and after Image(url omitted to protect the innocents):

I don't have access to the code, I am just inserting data, the application is still being built and the JavaScript is generated from codebehind. There is absolutely nothing I can do to remove this errors. | 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/Forums/en-US/iewebdevelopment/thread/d863c31c-8a50-4e9d-9482-ec479d330658/). I'm not convinced this will fix it but it might be worth a try. | 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 "dinosaur123456789" and the hex of the encryption is here:
The resulting hex values for the dinosaur password are
00h: 4A 6E 3C 34 29 32 2E 59 51 6B 2B 4E 4F 20 47 75 ; Jn<4)2.YQk+NO Gu
10h: 6A 33 09 ; j3.
20h: 64 69 6E 6F 73 61 75 72 31 32 33 34 35 36 37 38 ; dinosaur12345678
30h: 39 30 ; 90
Another password "gertcha" is encoded as
e8h: 4D 35 4C 46 53 5C 7E ; GROUT M5LFS\~
I've tried looking for a common XOR, but failed to find anything. The passwords are of the same length in the password file so I assume that these are a reversible encoding (it was of another age!). I'm wondering if the AFX classes may have had a means that would be used for this sort of thing?
If anyone can work out the encoding, then that would be great!
Thanks, Matthew
[edit:]
Okay, first, I'm moving on and going to leave the past behind in the new solution. It would have been nice to use the old data still. Indeed, if someone wants to solve it as a puzzle, then I would still like to be able to use it.
For those who want to have a go, I got two passwords done.
All 'a' - a password with 19 a's:
47 7D 47 38 58 57 7C 73 59 2D 50 ; G}G8XW|sY-P
79 68 29 3E 44 52 31 6B 09 ; yh)>DR1k.
All 'b' - a password with 16 b's.
48 7D 2C 71 78 67 4B 46 49 48 5F ; H},qxgKFIH\_
69 7D 39 79 5E 09 ; i}9y^.
This convinced me that there is no simple solution involved, and that there is some feedback. | 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 to say you are dealing with some kind of feedback cipher, which is why XOR turns up nothing. I think each octets value will depend on the previous.
I can go on, but this stuff takes a lot of time. Hopefully this may give you a start, or maybe give you a couple of ideas. | 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
```
This should maybe allow us to break the cipher without reverse engineering the DLL. | 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" />
```
The page will reload, which rids the page of all the changes that javascript has made.
Something like this:
```
<a onclick="jquery_stuff" />
```
Will give me the desired effect, but it no longer shows up as a link. Is there some way to specify an empty anchor so I can assign a javascript handler to the `onclick` event, without changing anything on the page or moving the scrollbar? | 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 with build times, indicates that the process is I/O bound. It also shows that the process does a lot more reading than writing.
However, I haven't found a good way to determine *which* files are being read or written, and how many times. My suspicion is that with our many subprojects and subsequent invocations of the compiler, the build is re-reading the same commonly used libraries many times.
What are some profiling tools that will tell me what a given process is doing with which files? Free is nice, but not essential.
---
Using [Process Monitor, as suggested by Jon Skeet,](https://stackoverflow.com/questions/493177/how-can-i-profile-file-i-o/493201#493201) I was able to confirm my suspicion: almost all of the disk activity was reading and re-reading of libraries, with the JDK's copies of "rt.jar" and other libraries at the top of the list. I can't make a RAM disk large enough to hold all the libraries I used, but mounting the "hottest" libraries on a RAM disk cut build times by about 40%; clearly, Windows file system caching isn't doing a good enough job, even though I've told Windows to optimize for that.
One interesting thing I noticed is that the typical 'read' operation on a [JAR](http://en.wikipedia.org/wiki/JAR_%28file_format%29) file is just a few dozen bytes; usually there are two or three of these, followed by a skip several kilobytes further on in the file. It appeared to be ill-suited to bulk reads.
I'm going to do more testing with *all* of my third-party libraries on a flash drive, and see what effect that has. | 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 occasionally.
But honestly, since moving to Linux, disk fragmentation is something I never worry about any more.
Another reason to try your build on Linux, at least once, is so that you can run [strace](https://en.wikipedia.org/wiki/Strace) (grepped for calls to *open*) to see what files your build is touching. | 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<ConcreteTable>
{
public:
typedef Record RT;
};
```
What can be done to fix it up. Thanks!
**Update:**
Thanks pointing out the issue, and for all the suggestions. This snippet was based on code that was providing an extensibility point within an existing code base, and the primary design goal was reducing the amount of work (typing) required to add new extensions using this mechanism.
A separate 'type traits' style class actually fits into the solution best. Especially as I could even wrap it in a C style macro if the style police aren't looking! | 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 be much more complicated - you could express a logical paradox with it - like a const bool which is false iff it is true).
## Fixing
With typedefs, I think you cannot hope for more than passing RT as additional template parameter, like this
```
template <class T, class RT>
class Table
{
public:
typedef typename RT Zot;
};
class ConcreteTable : public Table<ConcreteTable, Record>
{
public:
typedef Record RT;
};
```
If you don't insist on RT being available as `Table<>::Zot`, you can put it inside a nested struct
```
template <class T>
class Table
{
public:
struct S {
typedef typename RT Zot;
};
};
class ConcreteTable : public Table<ConcreteTable>
{
public:
typedef Record RT;
};
```
Or even external traits struct
```
template <class T>
struct TableTraits<T>;
template <class T>
struct TableTraits<Table<T> > {
typedef typename T::RT Zot;
};
```
If you only want the type be argument/return type of a method, you can do it by templatizing this method, eg.
```
void f(typename T::RT*); // this won't work
template <class U>
void f(U*); // this will
```
The point of all these manipulations is to postpone the need for T::RT as late as possible, particularly till after ConcreteTable is a complete class. | 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:
typedef Record RT;
};
class ConcreteTable: public Table<ConcreteTableParent>
{
public:
...
};
``` | 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 `UPDATE` sql syntax be? I am trying this, but no good... I'm missing something and I can't find it online.
```
UPDATE COURSES
SET COURSES.INSTRUCTOR_ID = COURSE_ROSTER.USER_ID
WHERE COURSE_ROSTER.COURSE_ID = COURSES.COURSE_ID
``` | 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_Roster
Where CourseID = C.Course_ID)
```
NOTE: The column User\_ID in Course\_Roster would probably be better named as InstructorId (or Instructor\_Id) to avoid confusion | ```
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 you need to look towards using a subquery. | 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 $_primary = 'user_id';
protected $_rowClass = 'User';
public function getUserbyID($id) { /* code */ }
// More code here
}
class User extends Zend_Db_Table_Row_Abstract {
// Code here
}
class Widgets extends Zend_Db_Table_Abstract {
protected $_name = 'widgets';
protected $_rowClass = 'Widget';
public function getWidgetsfromUser($userid) { /* code */ }
// More code here
}
class User extends Zend_Db_Table_Row_Abstract {
public function doSomethingWithWidget() { /* code */ }
// More code here
}
```
There seems to be so many ways to access the DB (fetchAll(), find(), fetchAll() through adapter, insert(), createRow() and save(), select() object) that I always find myself going back to the docs to figure out what I should be doing.
SO has taught me prepared statements are the way to go, and I've been trying to use rowsets and row (should I be?), but I'm still confused as to **what's the best way to interact with the database?**
(apologies for the terribly open ended question) | 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 introduction to Zend\_Db. You may want to take a closer look at the [Zend\_Db\_Table](http://framework.zend.com/manual/en/zend.db.table.html) documentation.
But to give a quick answer to your question. Unless you need to override some default behavior you shouldn't need to extend the Zend\_Db\_Table\_Row\_Abstract. Also you can probably simplify the Users class to just be:
```
class Users extends Zend_Db_Table_Abstract {
protected $_name = 'users';
// Code here
}
```
Then to use it you would do some of things you mentioned using the following:
```
//Create a Users Model Object
$usersDb = new Users();
//Find the record with user_id = 4 and print out their name
$row = $usersDb->find(4);
echo $row->first_name . ' ' . $row->last_name
//Change the first name of this user to Brian
$row->first_name = 'Brian';
$row->update();
//Insert a user into the database
$data = array(
'first_name' => 'Gilean',
'last_name' => 'Smith');
$usersDb->insert($data);
//Retrieve all users with the last name smith and print out their full names
$rows = $usersDb->fetchAll($usersDb->select()->where('last_name = ?', 'smith'));
foreach ($rows as $row) {
echo $row->first_name . ' ' . $row->last_name
}
``` | 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 frequently-needed queries.
But the object-oriented interface is simplified, unable to perform all the types of database operations you might need to do. So you can delve deeper and run a SQL query against the Zend\_Db\_Adapter methods like `query()` and `fetchAll()` when you require finer control over your SQL.
This is pretty common for object-oriented interfaces to databases. An OO layer that could duplicate *every* SQL feature would be insanely complex. So to compromise, an OO layer usually tries to provide easy ways to do the most common tasks, while giving you the ability to go under the covers when necessary.
That's a very general answer to your very general question. | 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 heading #3</h2>
<h3>Sub Sub heading #1</h3>
<h3>Sub Sub heading #2</h3>
<h4>Sub Sub Sub heading</h4>
<h2>Sub heading #4</h2>
<h3>Sub Sub heading</h3>
```
Using JavaScript (any framework is fine), how would you go about producing a list like this: (with nested lists)
```
<ol>
<li>Heading level 1
<ol>
<li>Sub heading #1</li>
<li>Sub heading #2
<ol>
<li>Sub Sub heading</li>
</ol>
</li>
<li>Sub heading #3
<ol>
<li>Sub Sub heading #1</li>
<li>Sub Sub heading #2
<ol>
<li>Sub Sub Sub heading (h4)</li>
</ol>
</li>
</ol>
</li>
<li>Sub heading #4
<ol>
<li>Sub Sub heading</li>
</ol>
</li>
</ol>
</li>
</ol>
```
Everytime I try and begin with a certain methodology it ends up getting very bloated.
The solution needs to traverse each heading and put it into its appropriate nested list - I keep repeating this to myself but I can't sketch out anything!
Even if you have a methodology in your head but haven't got time to code it up I'd still like to know it! :)
Thank you! | 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[] = heading; // Append.
} else {
treeLevels[treeLevels.length - 2].children[] = heading; // Add child to parent element.
}
treeLevels[treeLevels.length - 1] = heading;
} else if(heading.level > treeLevels.length) {
/* Child. */
while(heading.level - 1 > treeLevels.length) {
/* Create dummy headings if needed. */
treeLevels[] = new Heading();
}
treeLevels[] = heading;
} else {
/* Child of ancestor. */
treeLevels.remove(heading.level, treeLevels.length - 1);
treeLevels[treeLevels.length - 1].children[] = heading;
treeLevels[] = heading;
}
}
```
Next, we transverse it, building the list.
```
function buildList(root) {
var li = new LI(root.text);
if(root.children.length) {
var subUl = new UL();
li.children[] = subUl;
foreach(root.children as child) {
subUl.children[] = buildList(child);
}
}
return li;
}
```
Finally, insert the `LI` returned by `buildList` into a `UL` for each `treeRoots`.
In jQuery, you can fetch header elements in order as such:
```
var headers = $('*').filter(function() {
return this.tagName.match(/h\d/i);
}).get();
``` | 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 use comma delimited selectors.
You could overcome this issue by adding a common class to each heading. For example:
```
<h1 class="heading">Heading level 1</h1>
<h2 class="heading">Sub heading #1</h2>
<h2 class="heading">Sub heading #2</h2>
<h3 class="heading">Sub Sub heading</h3>
<h2 class="heading">Sub heading #3</h2>
...
```
Now the selector `$('.heading')` will get them all in order.
Here is how I would do it with jQuery:
```
var $result = $('<div/>');
var curDepth = 0;
$('h1,h2,h3,h4,h5,h6').addClass('heading');
$('.heading').each(function() {
var $li = $('<li/>').text($(this).text());
var depth = parseInt(this.tagName.substring(1));
if(depth > curDepth) { // going deeper
$result.append($('<ol/>').append($li));
$result = $li;
} else if (depth < curDepth) { // going shallower
$result.parents('ol:eq(' + (curDepth - depth - 1) + ')').append($li);
$result = $li;
} else { // same level
$result.parent().append($li);
$result = $li;
}
curDepth = depth;
});
$result = $result.parents('ol:last');
// clean up
$('h1,h2,h3,h4,h5,h6').removeClass('heading');
```
`$result` should now be your `<ol>`.
Also, note that this will handle an `<h4>` followed by an `<h1>` (moving more than one level down at once), but it will not handle an `<h1>` followed by an `<h4>` (more than one level up at a time). | 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 but I'm hoping there is a better way. | 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:
```
for i in sorted(indices, reverse=True):
del somelist[i]
```
If you really don't want to delete items backwards, then I guess you should just deincrement the indices values which are greater than the last deleted index (can't really use the same index since you're having a different list) or use a copy of the list (which wouldn't be 'deleting' but replacing the original with an edited copy).
Am I missing something here, any reason to NOT delete in the reverse order? | 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?
(Any languge is ok. c# is prefered)
@ctacke: I know that WOL is done by MAC address... My problem is that windows only sends UDP broadcasts on the NIC what Windows considers to be the primary NIC (which is not even the NIC with the default route on my Vista machine). And I can not seems to find a way to bind a socket to an interface which has no IP address. (like DHCP clients do this)
@Arnout: Why not? The clients know the MAC address of the gateway. I just want a send a WOL packet like a DHCP client does initially...(DHCP discover packets claim to come from 0.0.0.0) I don't mind if I have to construct the whole packet byte by byte... | 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 sending a WOL packet on all interfaces:
```
//You need SharpPcap for this to work
private void WakeFunction(string MAC_ADDRESS)
{
/* Retrieve the device list */
Tamir.IPLib.PcapDeviceList devices = Tamir.IPLib.SharpPcap.GetAllDevices();
/*If no device exists, print error */
if (devices.Count < 1)
{
Console.WriteLine("No device found on this machine");
return;
}
foreach (NetworkDevice device in devices)
{
//Open the device
device.PcapOpen();
//A magic packet is a broadcast frame containing anywhere within its payload: 6 bytes of ones
//(resulting in hexadecimal FF FF FF FF FF FF), followed by sixteen repetitions
byte[] bytes = new byte[120];
int counter = 0;
for (int y = 0; y < 6; y++)
bytes[counter++] = 0xFF;
//now repeat MAC 16 times
for (int y = 0; y < 16; y++)
{
int i = 0;
for (int z = 0; z < 6; z++)
{
bytes[counter++] =
byte.Parse(MAC_ADDRESS.Substring(i, 2),
NumberStyles.HexNumber);
i += 2;
}
}
byte[] etherheader = new byte[54];//If you say so...
var myPacket = new Tamir.IPLib.Packets.UDPPacket(EthernetFields_Fields.ETH_HEADER_LEN, etherheader);
//Ethernet
myPacket.DestinationHwAddress = "FFFFFFFFFFFFF";//it's buggy if you don't have lots of "F"s... (I don't really understand it...)
try { myPacket.SourceHwAddress = device.MacAddress; }
catch { myPacket.SourceHwAddress = "0ABCDEF"; }//whatever
myPacket.EthernetProtocol = EthernetProtocols_Fields.IP;
//IP
myPacket.DestinationAddress = "255.255.255.255";
try { myPacket.SourceAddress = device.IpAddress; }
catch { myPacket.SourceAddress = "0.0.0.0"; }
myPacket.IPProtocol = IPProtocols_Fields.UDP;
myPacket.TimeToLive = 50;
myPacket.Id = 100;
myPacket.Version = 4;
myPacket.IPTotalLength = bytes.Length - EthernetFields_Fields.ETH_HEADER_LEN; //Set the correct IP length
myPacket.IPHeaderLength = IPFields_Fields.IP_HEADER_LEN;
//UDP
myPacket.SourcePort = 9;
myPacket.DestinationPort = 9;
myPacket.UDPLength = UDPFields_Fields.UDP_HEADER_LEN;
myPacket.UDPData = bytes;
myPacket.ComputeIPChecksum();
myPacket.ComputeUDPChecksum();
try
{
//Send the packet out the network device
device.PcapSendPacket(myPacket);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
device.PcapClose();
}
}
``` | 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 network using the broadcast MAC address.
**For an Ethernet packet the structure is:**
* Destination MAC: FF:FF:FF:FF:FF:FF (Broadcast)
* A Magic Packet Payload
**For a UDP packet the structure is:**
* Destination MAC: FF:FF:FF:FF:FF:FF (Broadcast)
* UDP Port: 9
* A Magic Packet Payload
**The Magic Payload consists of:**
* The Synchronization Stream: FFFFFFFFFFFF (that's 6 pairs or 6 bytes of FF)
* 16 copies of the MAC of the computer you're signaling to WOL
* An optional passphrase of 0, 4, or 6 bytes.
**To receive WOL packets from the internet (through a firewall/router):**
* Configure router port 9 to forward to IP 255.255.255.255 (Broadcast IP)
* Set the destination IP: The external IP of the router
*Note: This can only be achieved using the UDP example because Ethernet packets lack the IP layer necessary for the packet to be routed through the internet. IE, Ethernet packets are the local-network-only option. The issue with sending WOL packets over UDP is security because you have to set the router to enable IP broadcasting (255.255.255.255). Enabling broadcasting over IP is usually considered a bad idea because of the added risk of internal attack within the network (Ping flooding, cache spoofing, etc...).*
For more info on the protocol including a sample capture see [this site](http://wiki.wireshark.org/WakeOnLAN).
If you want a quick-and-dirty command line tool that generates WOL packets (and you're running on a debian, linux mint, or Ubuntu) you can install a tool that already does this.
Just install using the command line with:
```
sudo apt-get install wakeonlan
```
**Update:**
**Here's a working example that generates a WakeOnLan packet using the current version of SharpPcap.**
```
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using PacketDotNet;
using SharpPcap;
namespace SharpPcap.Test.Example9
{
public class DumpTCP
{
public static void Main(string[] args)
{
// Print SharpPcap version
string ver = SharpPcap.Version.VersionString;
Console.WriteLine("SharpPcap {0}, Example9.SendPacket.cs\n", ver);
// Retrieve the device list
var devices = CaptureDeviceList.Instance;
// If no devices were found print an error
if(devices.Count < 1)
{
Console.WriteLine("No devices were found on this machine");
return;
}
Console.WriteLine("The following devices are available on this machine:");
Console.WriteLine("----------------------------------------------------");
Console.WriteLine();
int i = 0;
// Print out the available devices
foreach(var dev in devices)
{
Console.WriteLine("{0}) {1}",i,dev.Description);
i++;
}
Console.WriteLine();
Console.Write("-- Please choose a device to send a packet on: ");
i = int.Parse( Console.ReadLine() );
var device = devices[i];
Console.Write("What MAC address are you sending the WOL packet to: ");
string response = Console.ReadLine().ToLower().Replace(":", "-");
//Open the device
device.Open();
EthernetPacket ethernet = new EthernetPacket(PhysicalAddress.Parse(
"ff-ff-ff-ff-ff-ff"), PhysicalAddress.Parse("ff-ff-ff-ff-ff-ff"),
EthernetPacketType.WakeOnLan);
ethernet.PayloadPacket = new WakeOnLanPacket(
PhysicalAddress.Parse(response));
byte[] bytes = ethernet.BytesHighPerformance.Bytes;
try
{
//Send the packet out the network device
device.SendPacket(bytes);
Console.WriteLine("-- Packet sent successfuly.");
}
catch(Exception e)
{
Console.WriteLine("-- "+ e.Message );
}
//Close the pcap device
device.Close();
Console.WriteLine("-- Device closed.");
Console.Write("Hit 'Enter' to exit...");
Console.ReadLine();
}
}
}
```
Note: This is a fully functional Wake-On-Lan packet sending console application built on the Example09 that can be found in the SharpPcap source.
The libraries used in this example that can't be found in the .NET framework are:
```
using PacketDotNet;
```
This library (.dll) comes packaged with SharpPcap. It is responsible for all of the packet construction and parsing within SharpPcap. This is where the WakeOnLan class resides.
*Note: The packet construction/parsing code was originally bundled within SharpPcap.dll. It was migrated to its own lib because SharpPcap is meant to be a wrapper for winpcap. Many of its users deal with designing protocols and/or handling raw networking packets.*
```
using SharpPcap;
```
SharpPcap contains all of the winpcap(windows)/libpcap(\*nix) wrapper code. It's needed to select the interface and send the actual packets across the wire. | 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, serialize it, and then send it.
What do you guys suggest? | 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");
author.addAttrib("age", 43);
author.addText("Tolkien");
```
This would result in the following XML:
```
<book title="Lord of the Rings">
<author age="43">Tolkien</author>
</book>
``` | 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;
```
If that is wrapped in a transaction are there any concurrency issues that can occur? Or is there a better way to do this? | 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 VacationHours = VacationHours * 1.25,
ModifiedDate = GETDATE()
OUTPUT inserted.BusinessEntityID,
deleted.VacationHours,
inserted.VacationHours,
inserted.ModifiedDate
INTO @MyTableVar;
--Display the result set of the table variable.
SELECT EmpID, OldVacationHours, NewVacationHours, ModifiedDate
FROM @MyTableVar;
GO
--Display the result set of the table.
SELECT TOP (10) BusinessEntityID, VacationHours, ModifiedDate
FROM HumanResources.Employee;
GO
``` | 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, 2015:
"Can I use a scalar variable instead of a table variable?" one may ask... Sorry, but no you can't. You'll have to `SELECT @SomeID = ID from @UpdatedIDs` if you need a single ID. | 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, denoted either by names for each slide (like in the Coda slider effect) or by symbols (such as dots for each slide), to allow users to review their options before clicking on the slide to visit the particular highlighted section.
I have seen this done in many ways with flash , but the only javascript approach I have seen that meets my needs is the one used by Apple on the new iLife page ([link](http://www.apple.com/ilife/)). Does anyone have any ideas what they are using or if there is a project that is similar to their implementation?
Thanks in advance. | 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 you wanted a carousel-style animation with the images sliding left and right, might try the [jQuery Carousel](http://www.ajaxdaddy.com/demo-jquery-carousel.html) library. I have not used it myself though so cannot comment on its ease-of-use or quality. | 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;
padding: 5px;
line-height: 10px;
font-size: 150%;
border: 10px solid yellow;
foo: bar;
}
```
Is there an easy way to clear out all of the styles and set it back to the "default" settings? Is there even a list of default styles?
Thanks | 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-size: inherit !important;
border: inherit !important;
foo: inherit !important;
}
```
I am not entirely positive this will work, so I will be looking around and trying it out. | 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 Java Adding events in either Java 5 or 6 but I can't remember where I heard this and I may be making it up.
Basically I'm wrapping a device in a java class the device throws events, and I'm looking for the most logical way of exposing this. I come mostly from a .Net Background and I'm looking for something like the events in .Net (C#)
Any help would be appreciated. | 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 lets you do concurrent, asynchronous event handling like the following:
```
public class EventExample {
public static void main(String[] args) {
while ((char c = System.in.read()) >= 0) {
eventHandler.act(c);
}
}
public static Actor<Character> eventHandler =
Actor.actor(Strategy.simpleThreadStrategy(), new Effect<Character>() {
public void e(Character c) {
// Do something with c here.
}
});
}
```
[Get the actors library here.](http://functionaljava.org)
[See the Javadoc here.](http://functionaljava.googlecode.com/svn/artifacts/2.17/javadoc/fj/control/parallel/package-summary.html) | 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 restarted?
Thanks for your suggestions.
EDIT:
Thanks for all the answers.In answering one of your questions - The machine will not be used for multiple users.
what should I save inorder to recreate the settings.
if I save it to a delimited string can the font class parse this?
"Microsoft Sans Serif, 8.25pt, style=Bold" | 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);
TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
// Saving Font object as a string
string fontString = converter.ConvertToString(font1);
// Load an instance of Font from a string
Font font = (Font)converter.ConvertFromString(fontString);
``` | 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 isolated storage (secure).
EDIT:
After your last update, you can save typed values in the app config. For example, If I want to save a color, I can save the value as a type System.Color, and the runtime will parse it for me. Check [this article](http://www.codeproject.com/KB/cs/SystemConfiguration.aspx?display=Print) for more info and examples. | 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.wikipedia.org/wiki/Hexadecimal). | 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 have: 0C in hex, or just C.
```
16^0 x c (or 12) = 12 in decimal.
16^1 x 0 = 0
```
convert 12 decimal into binary now. Im just gonna show you simple addition pattern for small numbers:
```
2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
```
so to make 12 in binary, you need one group of (2^3) and one group of (2^2). Therefore you have
```
1100.
```
If you convert it to decimal just like you did with hex, you'll end up with 12.
```
0 x 2^0 = 0
0 x 2^1 = 0
1 x 2^2 = 4
2 x 2^3 = 8
total = 12.
``` | 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:58:38.
I do not want to edit the string to add in the milliseconds, so how can I do this?
I also do not want to multiply by 1000 since I am using this for formatting of other times that includes milliseconds. | > 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 should be in milliseconds because that is what the API expects. Anything else is a hack | 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 = toCheck.BaseType;
}
return false;
}
``` | (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. Please enhance this answer to further enhance its clarity.
## TIP:
If you make certain that your GenericClass implementation inherits from an abstract non-generic base class such as GenericClassBase, you could ask the same question without any trouble at all like this:
```
typeof(Test).IsSubclassOf(typeof(GenericClassBase))
```
---
## IsSubclassOf()
My testing indicates that IsSubclassOf() does not work on parameterless generic types such as
```
typeof(GenericClass<>)
```
whereas it will work with
```
typeof(GenericClass<SomeType>)
```
Therefore the following code will work for any derivation of GenericClass<>, assuming you are willing to test based on SomeType:
```
typeof(Test).IsSubclassOf(typeof(GenericClass<SomeType>))
```
The only time I can imagine that you would want to test by GenericClass<> is in a plug-in framework scenario.
---
## Thoughts on the "is" operator
At design-time C# does not allow the use of parameterless generics because they are essentially not a complete CLR type at that point. Therefore, you must declare generic variables with parameters, and that is why the "is" operator is so powerful for working with objects. Incidentally, the "is" operator also can not evaluate parameterless generic types.
The "is" operator will test the entire inheritance chain, including interfaces.
So, given an instance of any object, the following method will do the trick:
```
bool IsTypeof<T>(object t)
{
return (t is T);
}
```
This is sort of redundant, but I figured I would go ahead and visualize it for everybody.
Given
```
var t = new Test();
```
The following lines of code would return true:
```
bool test1 = IsTypeof<GenericInterface<SomeType>>(t);
bool test2 = IsTypeof<GenericClass<SomeType>>(t);
bool test3 = IsTypeof<Test>(t);
```
On the other hand, if you want something specific to GenericClass, you could make it more specific, I suppose, like this:
```
bool IsTypeofGenericClass<SomeType>(object t)
{
return (t is GenericClass<SomeType>);
}
```
Then you would test like this:
```
bool test1 = IsTypeofGenericClass<SomeType>(t);
``` | 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 receive the click event, the TabPage does. Some code:
```
public Form1()
{
InitializeComponent();
this.tabControl1.MouseClick += new MouseEventHandler(tabControl1_MouseClick);
}
private void tabControl1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
this.contextMenuStrip1.Show(this.tabControl1, e.Location);
}
}
``` | 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.GetTabRect(i);
if (r.Contains(p))
{
this.tabControl1.SelectedIndex = i; // i is the index of tab under cursor
return;
}
}
e.Cancel = true;
}
``` | 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 know how to get the number of products at a certain price range, but I can't figure out how to do it at several different price ranges without having to write a boatload of nested queries to aggregate all the results, especially since the price ranges can differ greatly among related products.
Is there a "rule of thumb" when doing something like this as to how you figure out the different price ranges? | 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 else 0 end) as 500to1000
from Products
```
This will only require a single scan of the table. | 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 pr.ProductCategory, pr.MinPrice, pr.MaxPrice, COUNT(*)
FROM Products AS p
INNER JOIN PriceRanges AS pr
ON p.ProductCategory = pr.ProductCategory
AND p.UnitPrice BETWEEN pr.MinPrice AND pr.MaxPrice
GROUP BY pr.ProductCategory, pr.MinPrice, pr.MaxPrice
ORDER BY pr.ProductCategory, pr.MinPrice, pr.MaxPrice
```
You will have to add some cleanup and handle the end of the ranges. | 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, T-SQL doesn't like the expression; it chokes on the equals sign.
Is there some way of evaluating an expression in the SQL select list and getting a returnable result? (Or some other way of achieving the unit testing that I want?)
---
EDIT: 3 great, answers, all built around CASE. I'll accept feihtthief's as he's got the least rep and thus needs it the most. :-) Thanks to everyone. | 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 one after the other and the only remaining manual step was to set the login password (which do not script for security reasons)
This does not seem possible in SQL Server 2005's Management Studio, making everything very fiddly and time consuming. (I end up having to script the whole database, delete all logins and users from the new database, run the script, and then trawl through a mixture of error message to see what worked and what didn't.)
Does anyone have any experience and recommendations on this? | 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:

Now execute this script here for each user, for example
```
exec sp_change_users_login 'Update_One', 'UserNameExample', 'UserNameExample'
```
This fixed my problem. | 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 10 1/2/09
2 2 10 1/2/09
3 1 15 1/3/09
4 2 10 1/03/09
5 1 15 1/4/09
6 2 15 1/4/09
7 3 22 1/4/09
```
I want to be able to select all of the entities along with the most recent recorded score for each resulting in some data like this:
```
entities
id name score date_added
1 Apple 15 1/4/09
2 Orange 15 1/4/09
3 Banana 15 1/4/09
```
I can get the data for a single entity using this query:
```
SELECT entities.*,
scores.score,
scores.date_added
FROM entities
INNER JOIN scores
ON entities.id = scores.entity_id
WHERE entities.id = ?
ORDER BY scores.date_added DESC
LIMIT 1
```
But I'm at a loss for how to select the same for all entities. Perhaps it's staring me in the face?
Thank you very kindly for taking the time.
Thanks for the great responses. I'll give it a few days to see if a preferred solution bubbles up then I'll select the answer.
UPDATE: I've tried out several of the proposed solutions, the main issue I'm facing now is that if an entity does not yet have a generated score they don't appear in the list.
What would the SQL look like to ensure that all entities are returned, even if they don't have any score posted yet?
UPDATE: Answer selected. Thanks everyone! | 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 tempDollarAmount = 0;
string tempVal = value.Replace("$", "").Replace(",","");
if (double.TryParse(tempVal, out tempDollarAmount))
{
base.Text = string.Format("C", tempDollarAmount);
}
else
{
base.Text = "$0.00";
}
}
}
```
Results:
* If I pass the value "Text"
(AmountControl.Text = "Text";) , the
text of the control on my test page
is set to "$0.00", as expected.
* If I pass the value 7
(AmountControl.Text = "7";) , I
expect to see "$7.00", but the text
of the control on my test page is set
to "C".
I assume that I am missing something very simple here. Is it something about the property? Or am I using the string format method incorrectly? | 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.
```
-CacheService
-CacheServiceBean
-getMyObject()
-insertMyObject(MyObject)
-size()
-SomeOtherBean
cache = jndiLookup(CacheService)
cache.insertMyObject(x)
cache.size() -> 1
```
After this assignment, if I call cache.size from inside the CacheServiceBean, I get 0.
Is it even possible to share static singletons through beans? Finally I decided to use a database table, but I'm still thinking about this.
Thanks for your responses. | 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#static_fields> says:
> Nonfinal static class fields are
> disallowed in EJBs because such fields
> make an enterprise bean difficult or
> impossible to distribute | 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. An assessment result is the result a student gets on a test (this includes a collection of answers).
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. Could someone tell me what is going on?.
I've read something about enum bugs in serialization/RMI-IIOP but I don't use that here.
The `enum AnswerStatus` can be `ASSESSED` or `NOT_ASSESSED`.
The `getStatus` method in class `Answer` just returns the status, nothing else. | 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. Could someone tell me
> what is going on?.
This sounds like the `getStatus()` method does not always return the same result - how is it implemented?
BTW, what's the point in having an enum with the values ASSESSED, and NOT\_ASSESSED? Why not use a boolean isAssessed()? | 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, since my guess would be the bottleneck is elsewhere. I'm reading character by character, so the only functions I'm using are `get()`, `peek()`, and `tellg()/seekg()`.
**Update:**
I profiled, and got [confusing](https://stackoverflow.com/questions/485649/confusing-gprof-output) output - gprof didn't appear to think that it took so long. I rewrote the program to read the entire file into a buffer first, and it sped up by about 100x. I think the problem may have been the `tellg()/seekg()` that took a long time, but gprof may have been unable to see that for some reason. In any case, `ifstream` does *not* appear to buffer the entire file, even for this size. | 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 memory at once.
The difference between std::ifstream and the C equivalents, is basically a virtual function call or two. It may make a difference if executed a few tens of million times per second, otherwise, not reall. file I/O is generally so slow that the API used to access it doesn't really matter. What matters far more is the read/write pattern. Lots of seeks are bad, sequential reads/writes good. | 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, so accept that getting my head around Object orientation will be a challenge, for example. I'm vaguely aware that some languages (python?) allow you to test small sections alone, and that this is particularly useful for beginners. I worry that I'm trying to run before I can walk by going straight for C#.
I'm sorry this is a bit of a rambling question, but advice would be greatly appreciated. | 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 code, that's just as easy in Visual Studio, you'll be writing many, many Console Applications where you can test very small snippets of code before you even get to any WinForms development. I say good choice. | 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 case of the blind leading the blind, and they'll teach you bad habits.
So . . .
* buy a book
* structure your learning around the
book
* Take all the help and advice your
friends have to offer - *as you work
your way through the book*.
It's along time since I was a beginner, anyone any recomendations on a C# for beginners book?
P.S. Have I mentioned that I think you should buy a book? | 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?
EDIT:
I would also like to know how others handle multiple optional parameters such as this:
We have several functions like this in internal libraries (I think they're pretty ugly).
```
function Foo(par1, par2, par3)
{
if(par2 == null)
par2 = "my default"
if(par3 == null)
par3 = "my default"
// Do something
}
```
And to call it:
```
Foo("Parameter one",null,true)
``` | 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 || "my default"
myArgs.par2 = myArgs.par2 || "my default"
}
``` | 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 default";
```
or
```
par2 = par2 !== undefined ? par2 : "my default";
```
This will allow you to pass on values like false or null.
However, your second approach is convenient, but only in the case you know that you would never pass false or null. | 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 something please comment
Thanks
G. | 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 to worse performance if there are writes as well as reads against it. | 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 have extended the Rules to include them.
Multi-table SELECTs are almost always needed with a normalised data model; as is often the case with this kind of question, the "correct" answer to the "denormalise?" question depends on several factors.
DBMS platform.
The relative performance of multi- vs single-table queries is influenced by the platform on which your application lives: the level of sophistication of the query optimisers can vary. MySQL, for example, in my experience, is screamingly fast on single-table queries but doesn't optimise queries with multiple joins so well. This isn't a real issue with smaller tables (less than 10K rows, say) but really hurts with large (10M+) ones.
Data volume
Unless you're looking at tables in the 100K+ row region, there pretty much shouldn't be a problem. If you're looking at table sizes in the hundreds of rows, I wouldn't even bother thinking about indexing.
(De-)normalisation
The whole point of normalisation is to minimise duplication, to try to ensure that any field value that must be updated need only be changed in one place. Denormalisation breaks that, which isn't much of a problem if updates to the duplicated data are rare (ideally they should never occur). So think very carefully before duplicating anything but the most static data, Note that your database may grow significantly
Requirements/Constraints
What performance requirements are you trying to meet? Do you have fixed hardware or a budget? Sometimes a performance boost can be most easily - and even most cheaply - achieved by a hardware upgrade. What transaction volumes are you expecting? A small-business accounting system has a very different profile to, say, Twitter.
One last thought strikes me: if you denormalise enough, how is your database different from a flat file? SQL is superb for flexible data and multi-dimensional retieval, but it can be an order of magnitude (at least) slower than a straight sequential or fairly simply indexed file. | 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 the start.bat script). But the jvm does not seem to pick up the parameter. | 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.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=8086
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
```
Then you can connect with JConsole or the newer VisualVM. | 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.zip.ZipException: error in opening zip file
[junit] at java.util.zip.ZipFile.open(Native Method)
[junit] at java.util.zip.ZipFile.(ZipFile.java:114)
[junit] at java.util.zip.ZipFile.(ZipFile.java:131)
[junit] at org.apache.tools.ant.AntClassLoader.getResourceURL(AntClassLoader.java:1028)
[junit] at org.apache.tools.ant.AntClassLoader$ResourceEnumeration.findNextResource(AntClassLoader.java:147)
[junit] at org.apache.tools.ant.AntClassLoader$ResourceEnumeration.nextElement(AntClassLoader.java:130)
[junit] at org.apache.tools.ant.util.CollectionUtils$CompoundEnumeration.nextElement(CollectionUtils.java:198)
[junit] at sun.misc.CompoundEnumeration.nextElement(CompoundEnumeration.java:43)
[junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTask.checkForkedPath(JUnitTask.java:1128)
[junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTask.executeAsForked(JUnitTask.java:1013)
[junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTask.execute(JUnitTask.java:834)
[junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTask.executeOrQueue(JUnitTask.java:1785)
[junit] at org.apache.tools.ant.taskdefs.optional.junit.JUnitTask.execute(JUnitTask.java:785)
[junit] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
[junit] at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
[junit] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[junit] at java.lang.reflect.Method.invoke(Method.java:597)
[junit] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
[junit] at org.apache.tools.ant.Task.perform(Task.java:348)
[junit] at org.apache.tools.ant.Target.execute(Target.java:357)
[junit] at org.apache.tools.ant.Target.performTasks(Target.java:385)
[junit] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1337)
[junit] at org.apache.tools.ant.Project.executeTarget(Project.java:1306)
[junit] at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
[junit] at org.apache.tools.ant.Project.executeTargets(Project.java:1189)
[junit] at org.apache.tools.ant.Main.runBuild(Main.java:758)
[junit] at org.apache.tools.ant.Main.startAnt(Main.java:217)
[junit] at org.apache.tools.ant.launch.Launcher.run(Launcher.java:257)
[junit] at org.apache.tools.ant.launch.Launcher.main(Launcher.java:104)
```
my test running task is as follows:
```
<target name="run-junit-tests" depends="compile-tests,clean-results">
<mkdir dir="${test.results.dir}"/>
<junit failureproperty="tests.failed" fork="true" showoutput="yes" includeantruntime="false">
<classpath refid="test.run.path" />
<formatter type="xml" />
<test name="project.AllTests" todir="${basedir}/test-results" />
</junit>
<fail if="tests.failed" message="Unit tests failed"/>
</target>
```
I've verified that the classpath contains the following as well as all of the program code and libraries:
```
ant-junit.jar
ant-launcher.jar
ant.jar
easymock.jar
easymockclassextension.jar
junit-4.4.jar
```
I've tried debugging to find out which ZipFile it is trying to open with no luck, I've tried toggling *includeantruntime* and *fork* and i've tried running ant with *ant -lib test/libs* where test/libs contains the ant and junit libraries.
Any info about what causes this exception or how you've configured ant to successfully run unit tests is gratefully received.
ant 1.7.1 (ubuntu), java 1.6.0\_10, junit 4.4
Thanks.
**Update - Fixed**
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. | 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 format. So the class path should contain only explicit references to JAR [files] and/or the names of the [directories] where other resources like class files are to be found.
So when building up your class path (in ANT) use:
```
<path id="proj.class.path">
<pathelement location="c:/my/project/root" /> :one for each of the [directories] where class files, log4j property files and other resources etc are to be found
<fileset refid="my.file.set"> :to describe all the explicit JAR [files] that need to be on the class path.
</path>
```
where
```
<fileset id="my.file.set" dir="c:/where/i/keep/my/jars">
<filename name="myjar1.jar" />
<filename name="myjar2.jar" />
<filename name="myjar3.jar" />
</fileset>
```
or
NOTE: When using wild cards like `[**/*]` in you need to make sure the wild card is not matching files that are not JAR files
```
<fileset id="my.file.set" dir="c:/where/i/keep/my/jars">
<include name="**/*.jar" />
</fileset>
``` | 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:
def __init__(self):
self.x = []
def add(self):
self.x.append(1)
x = A()
y = A()
x.add()
y.add()
print("A's x:", x.x)
x = B()
y = B()
x.add()
y.add()
print("B's x:", x.x)
```
Output
```
A's x: [1, 1]
B's x: [1]
``` | 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:
```
>>> class A:
... def __init__(s):
... s.bla = 2
...
>>>
>>> a = A()
>>> a.bla
2
``` | 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,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 = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.17999999999999999 # Approximately 20% of the coins are heads
>>> N = 10000
>>> flips = [flip(0.2) for i in xrange(N)]
>>> float(flips.count('H'))/N
0.20549999999999999 # Better approximation
``` | 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, mode)`**:
>
> Return a random floating point number `N` such that `low <= N < high` and
> with the specified mode between those
> bounds. The `low` and `high` bounds
> default to *zero* and *one*. The `mode`
> argument defaults to the midpoint
> between the bounds, giving a symmetric
> distribution.
>
> **`random.betavariate(alpha, beta)`**:
>
> Beta distribution. Conditions on the parameters are `alpha > 0` and
> `beta > 0`. Returned values range between `0` and `1`.
>
> **`random.expovariate(lambd)`**:
>
> Exponential distribution. `lambd` is `1.0`
> divided by the desired mean. It should
> be *nonzero*. (The parameter would be
> called “*`lambda`*”, but that is a
> reserved word in Python.) Returned
> values range from `0` to *positive
> infinity* if `lambd` is positive, and
> from *negative infinity* to `0` if `lambd`
> is negative.
>
> **`random.gammavariate(alpha, beta)`**:
>
> Gamma distribution. (Not the gamma
> function!) Conditions on the
> parameters are `alpha > 0` and `beta > 0`.
>
> **`random.gauss(mu, sigma)`**:
>
> Gaussian distribution. `mu` is the mean, and `sigma` is the standard
> deviation. This is slightly faster
> than the `normalvariate()` function
> defined below.
>
> **`random.lognormvariate(mu, sigma)`**:
>
> Log normal distribution. If you take
> the natural logarithm of this
> distribution, you’ll get a normal
> distribution with mean `mu` and standard
> deviation `sigma`. `mu` can have any
> value, and `sigma` must be greater than
> *zero*.
>
> **`random.normalvariate(mu, sigma)`**:
>
> Normal distribution. `mu` is the mean,
> and `sigma` is the standard deviation.
>
> **`random.vonmisesvariate(mu, kappa)`**:
>
> `mu` is the mean angle, expressed in
> radians between `0` and `2*pi`, and `kappa`
> is the concentration parameter, which
> must be greater than or equal to *zero*.
> If `kappa` is equal to *zero*, this
> distribution reduces to a uniform
> random angle over the range `0` to `2*pi`.
>
> **`random.paretovariate(alpha)`**:
>
> Pareto distribution. `alpha` is the
> shape parameter.
>
> **`random.weibullvariate(alpha, beta)`**
>
> Weibull distribution. `alpha` is the
> scale parameter and `beta` is the shape
> parameter. | 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 as programming language and SQL Server as DBMS.
Thanks :D | 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 - it simply doesn't scale. Timestamp or row-version columns are a good way of doing optimistic concurrency to prevent against accidental over-writing.
To publish / enforce the fact that a row is being edited, I would store the user-id/user-name of the locking user in a column (null if not locked). This makes it clear who owns the row - i.e. when you want to edit the row, first UPDATE it, setting your user-id (and ensuring that it isn't already locked).
To cope with locks that aren't removed correctly (because of a dead terminal etc) there are 3 common options:
* when the lock owner logs in again, allow them to break their own locks
* allow an administrator to break the user's locks
* store a lock-timeout column (datetime), and have a scheduled task automatically unlock rows that are overdue
So to summarise - consider something like:
```
Foo
===
Id | ...data... | Timestamp | LockOwner | LockTimeout
---+------------+-----------+-----------+------------
```
etc | 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 already set, and make sure that its set to False (0) when the terminal is finished.
Why does the row need to be locked anyway, wouldn't it be better to have a row for each terminal? | 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 this make sense?
Need the quickest solution | 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 not? Are you just interested in the existence of a range, or do you need to find all the ranges that a value belongs to?
EDIT: With the edits to the question, Barry's answer is exactly right. Just sort (by lower bound is good enough) at initialization time and then do a binary search to find the range containing the value, or the lack thereof.
EDIT: I've found the code below in [my answer to a similar question](https://stackoverflow.com/questions/454250#454312) recently.
The ranges will need to be sorted beforehand - `List<Range>.Sort` will work fine assuming you have no overlap.
```
public class Range : IComparable<Range>
{
private readonly int bottom; // Add properties for these if you want
private readonly int top;
public Range(int bottom, int top)
{
this.bottom = bottom;
this.top = top;
}
public int CompareTo(Range other)
{
if (bottom < other.bottom && top < other.top)
{
return -1;
}
if (bottom > other.bottom && top > other.top)
{
return 1;
}
if (bottom == other.bottom && top == other.top)
{
return 0;
}
throw new ArgumentException("Incomparable values (overlapping)");
}
/// <summary>
/// Returns 0 if value is in the specified range;
/// less than 0 if value is above the range;
/// greater than 0 if value is below the range.
/// </summary>
public int CompareTo(int value)
{
if (value < bottom)
{
return 1;
}
if (value > top)
{
return -1;
}
return 0;
}
}
// Just an existence search
public static bool BinarySearch(IList<Range> ranges, int value)
{
int min = 0;
int max = ranges.Count-1;
while (min <= max)
{
int mid = (min + max) / 2;
int comparison = ranges[mid].CompareTo(value);
if (comparison == 0)
{
return true;
}
if (comparison < 0)
{
min = mid+1;
}
else if (comparison > 0)
{
max = mid-1;
}
}
return false;
}
``` | 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 form to be opened.
Thanks in advance, | 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 int SelectedTab
{
get { return _tabControl.SelectedIndex; }
set { _tabControl.SelectedIndex = value; }
}
``` | 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 all the tabs by index. | 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 responses. yes they are fixed length records. These text files coming from a local company. (There last month transaction records)
Is it possible to access these files like normal text files (using normal file stream).
and
How about the memory management???? | 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 will have killed your process out of frustration.
The trick is to process the file incrementally. The base System.IO.Stream() class is designed to process a variable (and possibly infinite) stream in distinct quantities. It has several Read methods that will only progress down a stream a specific number of bytes. You will need to use these methods in order to divide up the stream.
I can't give more information because your scenario is not specific enough. Can you give us more details or your record delimeters or some sample lines from the file?
**Update**
If they are fixed length records then System.IO.Stream will work just fine. You can even use File.Open() to get access to the underlying Stream object. Stream.Read has an overload that requests the number of bytes to be read from the file. Since they are fixed length records this should work well for your scenario.
As long as you don't call ReadAllText() and instead use the Stream.Read() methods which take explicit byte arrays, memory won't be an issue. The underlying Stream class will take care not to put the entire file into memory (that is of course, unless you ask it to :) ). | 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 move to the location in the file you need to start from, process the data you need to process in chunks, and then close the file.
More information here would certainly be helpful. | 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 accidentally declare a new function, instead of overriding the old one.
Take this example:
```
class parent {
public:
virtual void handle_event(int something) const {
// boring default code
}
};
class child : public parent {
public:
virtual void handle_event(int something) {
// new exciting code
}
};
int main() {
parent *p = new child();
p->handle_event(1);
}
```
Here `parent::handle_event()` is called instead of `child::handle_event()`, because the child's method misses the `const` declaration and therefore declares a new method. This could also be a typo in the function name or some minor difference in the parameters types. It can also easily happen if the interface of the base class changes and somewhere some derived class wasn't updated to reflect the change.
Is there some way to avoid this problem, can I somehow tell the compiler or some other tool to check this for me? Any helpful compiler flags (preferably for g++)? How do you avoid these problems? | 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 mis-spelling the function name itself. | Safely override C++ virtual functions | [
"",
"c++",
"overriding",
"virtual-functions",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.