input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
|---|---|
Accessing a list of avaliable Wifi APs, on Windows Mobile <p>I need to query for a list of available Wireless Access points. I only need their SSIDs.</p>
<p>The App is currently .Net CF 2.0, but it's not a problem going with 3.5 if we have to.</p>
|
<p>The list of "nearby" APs is retrived eitehr through NDIS or WZC, depending on what your NIC driver supports. Both are somewhat well documented in MSDN, but they aren't fun to wrap. OpenNETCF's SDF contains a wrapper that looks at both, depending on your NIC's support.</p>
<p>It's accessible via the <a href="http://opennetcf.com/library/sdf/html/d79a4a4f-93be-3c85-477b-5298d1141978.htm" rel="nofollow">OpenNETCF.Net.NetworkInformation</a>.<a href="http://opennetcf.com/library/sdf/html/d308a2a7-778b-ff94-b297-54422ea9a271.htm" rel="nofollow">NetworkInterface</a>'s <a href="http://opennetcf.com/library/sdf/html/2dc21eda-47c6-fde5-e569-1781b1b44feb.htm" rel="nofollow">GetAllNetworkInterfaces method</a> in the newest <a href="http://smartdeviceframework.com" rel="nofollow">SDF 2.3</a> (actually it's been there since 2.2).</p>
|
Is there a Perl module that validates an XML against a schema? <p>I need to validate an XML agaist a schema. </p>
<p>I tried XML::SAX::ParserFactory; XML::Validator::Schema and related modules but looks like they are limited.<br />
Limited in the sense that it didn't recognize schema elements such as xsd:unique, xsd:group, xsd:keyref, xsd:union and xsd:key. </p>
<p>Are these xsd:unique, etc. new additions?</p>
<p>Appreciate if you can point me to some Perl modules which are upto date and upto the task.</p>
<p>Thanks in advance.</p>
|
<p>Have a look at <a href="http://search.cpan.org/dist/XML-LibXML/">XML::LibXML</a></p>
<p>This uses the highly regarded libxml2 library which most people cite as a successor to Expat and <a href="http://search.cpan.org/dist/XML-Parser/">XML::Parser</a> based modules.</p>
<p>For schema validation look at <a href="http://search.cpan.org/perldoc/XML%3A%3ALibXML%3A%3ASchema">XML::LibXML::Schema</a></p>
<pre><code>use XML::LibXML;
use XML::LibXML::Schema;
my $schema = XML::LibXML::Schema->new(location => 'file.xsd' );
my $parser = XML::LibXML->new;
my $xml = 'file.xml';
my $doc = $parser->parse_file( $xml );
eval { $schema->validate( $doc ) };
die $@ if $@;
say "$xml is valid\n";
</code></pre>
<p>NB. I still mainly a <a href="http://search.cpan.org/dist/XML-Twig/">XML::Twig</a> user and barely touch XML schema so I don't know if XML::LibXML::Schema will solve the problem you have but it possibly is the best solution on CPAN for your needs.</p>
<p>/I3az/</p>
|
Invoke gdb to automatically pass arguments to the program being debugged <p>I'd like to write a script that (under certain conditions) will execute gdb and automatically run some program X with some set of arguments Y. Once the program has finished executing the user should remain at gdb's prompt until s/he explicitly exits it.</p>
<p>One way to do this would be to have the script output the run command plus arguments Y to some file F and then have the script invoke gdb like this:</p>
<pre><code>gdb X < F
</code></pre>
<p>But is there a way to do this without introducing a temporary file?</p>
<p>Thanks.</p>
|
<p>The easiest way to do this given a program <code>X</code> and list of parameters <code>a b c</code>:</p>
<pre><code>X a b c
</code></pre>
<p>Is to use <code>gdb</code>'s <code>--args</code> option, as follows:</p>
<pre><code>gdb --args X a b c
</code></pre>
<p><hr /></p>
<p><code>gdb --help</code> has this to say about <code>--args</code>:</p>
<blockquote>
<blockquote>
<p><code>--args Arguments after executable-file are passed to inferior</code></p>
</blockquote>
</blockquote>
<p>Which means that the first argument after <code>--args</code> is the executable to debug, and all the arguments after that are passed <em>as is</em> to that executable.</p>
|
ASP.NET 3.5 bind to XML string <p>With ASP.NET 3.5 I can easily bind to an XML file by using an <code>XmlDataSource</code>.</p>
<p>How can I bind to an XML <em>string</em> instead of a <em>file</em>?</p>
|
<p>Use the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.xmldatasource.data.aspx" rel="nofollow">XmlDataSource.Data</a> property.</p>
<pre><code>XmlDataSource dataSource = new XmlDataSource();
dataSource.Data = "<root><element>Item #1</element><element>Item #2</element></root>";
dataSource.XPath = "root/element";
dataSource.DataBind();
</code></pre>
<p>Alternately, you could specify the data declaratively:</p>
<pre><code><asp:xmldatasource
id="XmlDataSource1"
runat="server"
>
<data>
<Books>
<LanguageBooks>
<Book Title="Pure JavaScript" Author="Wyke, Gilliam, and Ting"/>
<Book Title="Effective C++ Second Edition" Author="Scott Meyers"/>
<Book Title="Assembly Language Step-By-Step" Author="Jeff Duntemann"/>
<Book Title="Oracle PL/SQL" Author="Steven Feuerstein"/>
</LanguageBooks>
<SecurityBooks>
<Book Title="Counter Hack" Author="Ed Skoudis"/>
</SecurityBooks>
</Books>
</data>
</asp:xmldatasource>
</code></pre>
|
Which Tomcat 5 context file takes precedence? <p><a href="http://tomcat.apache.org/tomcat-5.5-doc/deployer-howto.html" rel="nofollow">Tomcat documentation</a> says: </p>
<p>The locations for Context Descriptors are;</p>
<p>$CATALINA_HOME/conf/[enginename]/[hostname]/context.xml<br>
$CATALINA_HOME/webapps/[webappname]/META-INF/context.xml</p>
<p>On my server, I have at least 3 files floating around:</p>
<pre><code>1 ...tomcat/conf/context.xml
2 ...tomcat/Catalina/localhost/myapp.xml
3 ...tomcat/webapps/myapp/META-INF/context.xml
</code></pre>
<p>What is the order of precedence? </p>
|
<p>For the files you listed, the simple answer assuming you are using all the defaults, the order is (note the <strong>conf</strong>/Catalina/localhost):</p>
<pre><code>...tomcat/conf/context.xml
...tomcat/conf/Catalina/localhost/myapp.xml
...tomcat/webapps/myapp/META-INF/context.xml
</code></pre>
<p>I'm basing this (and the following discussion) on the <a href="http://tomcat.apache.org/tomcat-5.5-doc/config/context.html">Tomcat 5.5 official documentation for the <strong>Context Container</strong></a>. </p>
<p>So if that's the simple answer, whats the complete answer?</p>
<p>Tomcat 5.5. will look in a couple of other places for <code><Context></code> elements beyond those you've listed (see the official docs).</p>
<p>The <code>META-INF/context.xml</code> will never be opened if Tomcat finds a <code>Catalina/localhost/myapp.xml</code>. So if you actually have all the files above, its more correct to say the the <code>META-INF/context.xml</code> is <strong>irrelevant</strong>, not that it's the lowest precedence.</p>
<p>If you say <code><Context override="true" ...></code> in your <code>Catalina/localhost/myapp.xml</code> that will make it the <strong>highest</strong> precedence, regardless of <code>conf/context.xml</code>. Same thing in your <code>META-INF\context.xml</code>, as long as you don't have a <code>Catalina/localhost/myapp.xml</code> (see previous paragraph).</p>
<p>Also, the <code>/Catalina/localhost/</code> portion of the path in the files above actually comes out of the "default" <code>conf/server.xml</code> and matches the <code><Engine name="Catalina" defaultHost="localhost"></code>. If your <code>server.xml</code> uses different values for <code>name</code> and <code>defaultHost</code> in the <code><Engine></code>, that's the dir structure where Tomcat will look.</p>
<p>Finally, for the <code>...tomcat\</code> portion of the files you listed, Tomcat uses the dir from the <code>$CATALINA_BASE</code> environment variable. If that's not set, then it uses the dir from the <code>$CATALINA_HOME</code> environment variable, which is the directory of the Tomcat installation. I like to set and use <code>$CATALINA_BASE</code> so that I don't "pollute" my Tomcat installation.</p>
|
Getting the Web Capture Web Part to work were the Sharepoint is 64bit <p>Previously our SharePoint server was 32-bit and we used the web capture web part to display a bugzilla search results page. Since we've migrated to a 64-bit server the webpart no longer works. We're running the same versions of everything, the only change was moving from a Windows Server 2003 32-bit box to a Windows Server 2003 64-bit box.</p>
<p>Oddly enough, the logs don't contain anything. The pages where the webparts appear are the only place that error messages appear. Here is what I have:</p>
<p>-Web Part Error: A Web Part or Web Form Control on this Page cannot be displayed or imported. The type could not be found or it is not registered as safe.</p>
<ul>
<li>Error - An unexpected error has been encountered in this Web Part.</li>
</ul>
<p>The reason I suspect the 64bit vs 32bit issue is that I saw numerous posts on the subject in various forums. It would appear that I am not the only one with this issue and all the troubleshooting has lead to this conclusion.</p>
|
<p>In all the times I have come across an error in changing from 64bit to 32bit, the change in the number of bits is usually a red herring and the actual cause of the failure is something else.</p>
<p>Check the sharepoint logs for the WebPart errors. They will help show exactly what is wrong.
Post the relevant errors if you still need help.</p>
|
How do I examine the contents of an std::vector in gdb, using the icc compiler? <p>I want to examine the contents of a std::vector in gdb but I don't have access to _M_impl because I'm using icc, not gcc, how do I do it? Let's say it's a std::vector for the sake of simplicity.</p>
<p>There is a very nice answer <a href="http://stackoverflow.com/questions/253099/how-do-i-print-the-elements-of-a-c-vector-in-gdb">here</a> but this doesn't work if I use icc, the error message is "There is no member or method named _M_impl". There appears to be a nice debug toolset <a href="http://www.yolinux.com/TUTORIALS/GDB-Commands.html#STLDEREF">here</a> but it also relies on _M_impl.</p>
|
<p>Not sure this will work with your vector, but it worked for me.</p>
<pre><code>#include <string>
#include <vector>
int main() {
std::vector<std::string> vec;
vec.push_back("Hello");
vec.push_back("world");
vec.push_back("!");
return 0;
}
</code></pre>
<p>gdb:</p>
<pre><code>(gdb) break source.cpp:8
(gdb) run
(gdb) p vec.begin()
$1 = {
_M_current = 0x300340
}
(gdb) p $1._M_current->c_str()
$2 = 0x3002fc "Hello"
(gdb) p $1._M_current +1
$3 = (string *) 0x300344
(gdb) p $3->c_str()
$4 = 0x30032c "world"
</code></pre>
|
API to determine cell carrier? <p>Is there a free API or some other way to determine what carrier a cell phone number is registered with?</p>
<p>I'd like my application to broadcast text messages without them picking their carrier from a list.</p>
<p><strong>UPDATE:</strong>
Interestingly, a coworker found the answer: <a href="http://developer.whitepages.com/" rel="nofollow">http://developer.whitepages.com/</a></p>
<p><strong>UPDATE2:</strong>
Well the whitepages license agreement is so restrictive that you can't build an app for it. Any other ideas?</p>
<p><strong>UPDATE3:</strong><br>
At some point, someone removed my Update 2. This puts it back. More importantly as of 10/19/2015 the <a href="http://pro.whitepages.com/terms-of-service/?_ga=1.260850253.1904530943.1445280336" rel="nofollow">Terms of Service</a> is still in a state that it should be impossible to legally utilize their services. </p>
|
<p>Data24-7 offers an API for looking up the carrier for wireless phone numbers. It also returns the email addresses to send SMS and MMS messages to the phone. It's not free, it's $12 per month and $0.006 per lookup. </p>
<p>The link is: <a href="http://www.data24-7.com">http://www.data24-7.com</a></p>
|
Can I invoke an instance method on a Ruby module without including it? <h3>Background:</h3>
<p>I have a module which declares a number of instance methods</p>
<pre><code>module UsefulThings
def get_file; ...
def delete_file; ...
def format_text(x); ...
end
</code></pre>
<p>And I want to call some of these methods from within a class. How you normally do this in ruby is like this:</p>
<pre><code>class UsefulWorker
include UsefulThings
def do_work
format_text("abc")
...
end
end
</code></pre>
<h3>Problem</h3>
<p><code>include UsefulThings</code> brings in <em>all</em> of the methods from <code>UsefulThings</code>. In this case I only want <code>format_text</code> and explicitly do not want <code>get_file</code> and <code>delete_file</code>.</p>
<p>I can see several possible solutions to this: </p>
<ol>
<li>Somehow invoke the method directly on the module without including it anywhere
<ul>
<li>I don't know how/if this can be done. (Hence this question)</li>
</ul></li>
<li>Somehow include <code>Usefulthings</code> and only bring in some of it's methods
<ul>
<li>I also don't know how/if this can be done</li>
</ul></li>
<li>Create a proxy class, include <code>UsefulThings</code> in that, then delegate <code>format_text</code> to that proxy instance
<ul>
<li>This would work, but anonymous proxy classes are a hack. Yuck.</li>
</ul></li>
<li>Split up the module into 2 or more smaller modules
<ul>
<li>This would also work, and is probably the best solution I can think of, but I'd prefer to avoid it as I'd end up with a proliferation of dozens and dozens of modules - managing this would be burdensome</li>
</ul></li>
</ol>
<p>Why are there lots of unrelated functions in a single module? It's <code>ApplicationHelper</code> from a rails app, which our team has de-facto decided on as the dumping ground for anything not specific enough to belong anywhere else. Mostly standalone utility methods that get used everywhere. I could break it up into seperate helpers, but there'd be 30 of them, all with 1 method each... this seems unproductive</p>
|
<p>If a method on a module is turned into a module function you can simply call it off of Mods as if it had been declared as</p>
<pre><code>module Mods
def self.foo
puts "Mods.foo(self)"
end
end
</code></pre>
<p>The module_function approach below will avoid breaking any classes which include all of Mods.</p>
<pre><code>module Mods
def foo
puts "Mods.foo"
end
end
class Includer
include Mods
end
Includer.new.foo
Mods.module_eval do
module_function(:foo)
public :foo
end
Includer.new.foo # this would break without public :foo above
class Thing
def bar
Mods.foo
end
end
Thing.new.bar
</code></pre>
<p>However, I'm curious why a set of unrelated functions are all contained within the same module in the first place? </p>
<p><em>Edited</em> to show that includes still work if <code>public :foo</code> is called after <code>module_function :foo</code></p>
|
Moving from NuSOAP to PHP5 SOAP <p>I have been working on a script with PHP4 that relies on NuSOAP. Now, I'm trying to move this to PHP5, and use the buildin support for SOAP there.</p>
<pre><code>$wsdlPath = ""; // I have obviously set these variables to something meaningful, just hidden for the sake of security
$apiPath = "";
$username = "";
$password = "";
// PHP5 style
$client = new soapclient($wsdlPath, array('login'=>username,
'password'=> $password,
'soap_version'=> SOAP_1_2,
'location'=> $apiPath,
'trace'=> 1));
// PHP4/NuSOAP style
$client = new soapclient($wsdlPath, true);
client->setEndpoint($apiPath);
$client->setCredentials($username, $password);
$client ->loadWSD);
</code></pre>
<p>The PHP5-version throws the following exception stacktrace:</p>
<pre><code>EXCEPTION=SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://external-nbb.napi.norwegian.no.stage.osl.basefarm.net/api/napi1300?wsdl' in /home/eisebfog/public_html/database/norwegian.php:31
Stack trace:
#0 /home/eisebfog/public_html/database/norwegian.php(31): SoapClient->SoapClient('http://external...', Array)
#1 /home/eisebfog/public_html/database/index.php(53): require_once('/home/eisebfog/...')
#2 {main}
</code></pre>
<p>Now, as the NuSOAP version does work, and the pure PHP5 doesn't - it doesn't take a brain surgeon to figure out I'm doing something wrong. I have access to the .htaccess file, and through phpinfo() I have made sure that I'm running NuSOAP properly and running PHP5 when I should, and PHP4/Nusoap when I should.</p>
<p>Basically, I'm not very good with web services and soap - but if anyone has any ideas, i'd appreciate any input on what I'm doing wrong and how I can move to the native soap in PHP5. Btw, the reson I want this move in the first place is the assumed resource savings in native soap. I'd appreciate any links to benchmarks between these two solutions too.</p>
|
<p>Make sure NuSoap and PHPv5-SOAP are running on the same server. If I'm not totally wrong, both libraries uses the same class-name. Maybe it will work better if you make sure none NuSopa-files are included? And also verify that the SOAP-library are loaded:</p>
<pre><code>if(!extension_loaded('soap')){
dl('soap.so'); // Actually a deprecated method. See "notes" at http://no.php.net/dl
}
</code></pre>
<p>I guess the version-field you refer to is defined as "SOAP 1.1" or similiar?</p>
<p>Best wishes :)</p>
Btw: what are you working on? Exchange of delays from the pilot to the airport? Or perhaps a webservice which will decrease the waiting-time on luggage delivery at Osl? :p</p>
|
How do I convert a Char into a Keycode in .Net? <p>I want to convert a string into a series of Keycodes, so that I can then send them via PostMessage to a control. I need to simulate actual keyboard input, and I'm wondering if a massive switch statement is the only way to convert a character into the correct keycode, or if there's a simpler method.</p>
<p>====</p>
<p>Got my solution - <a href="http://msdn.microsoft.com/en-us/library/ms646329" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms646329</a>(VS.85).aspx</p>
<p>VkKeyScan will return the correct keycode for any character.</p>
<p>(And yes, I wouldn't do this in general, but when doing automated testing, and making sure that keyboard presses are responded to correctly, it works reliably enough).</p>
|
<p>Raymond says this is a bad idea.</p>
<p><a href="http://blogs.msdn.com/oldnewthing/archive/2005/05/30/423202.aspx" rel="nofollow">http://blogs.msdn.com/oldnewthing/archive/2005/05/30/423202.aspx</a></p>
|
How does Flash work? <p>Right now I'm developing a small canvas oriented 2D graphics engine for a game, and have been looking into several sources for hints to apply to my system's design. But obviously the most battle proven solution out there is flash, so I was wondering how is Flash architectured. I found some sources about Flash's workings, but most are very basic and oriented towards designers and artists, but I'd like to learn more about the guts of the system. My next step is to download Flex's source code and wade through it, but before that I'd like to have a "guide" to make the best of my time in the code base. Any suggestions of good online resources and articles?</p>
<p>Thanks!</p>
<p><strong>Edit:</strong> To make it more clear, I'm looking for the inner workings of Flash because my goal here is to make something similar to Flash, but not as powerful of course, that works in a browser without plugins. Alas pure HTML+Javascript.</p>
<p>Also the reason I'm not using Flash as such is because it doesn't fulfill my requirements (free + no plugin), and because I don't have Flash support on my target platforms, besides I'm reinventing the wheel here for fun and self-education. Oh and I already know how to use Flash :)</p>
|
<p>Well, at the root of your Flash content is a stage object (an instance of the <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/display/Stage.html" rel="nofollow">Stage</a> class). That stage is the root node of a tree of display objects, any of which can contain graphical assets (lines, text fields, etc.) or other display objects. How Flash "works" is that, X times per second, the Flash player draws that entire display tree onto the screen. The player also collects user input (<a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/events/KeyboardEvent.html" rel="nofollow">KeyboardEvents</a>, etc.) from the OS and delivers them to any object that has registered for them.</p>
<p>Your job as a content creator, then, is to populate this Stage with children (of type <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/display/DisplayObject.html" rel="nofollow">DisplayObject</a> or any subclass), which the Flash engine will draw onto the screen for you. You can populate it with low-level children like Sprite and MovieClip and TextField, which are the basic building blocks of Flash content, or you can instantiate things like <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/fl/controls/ScrollBar.html" rel="nofollow">ScrollBar</a> or <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/fl/controls/DataGrid.html" rel="nofollow">DataGrid</a>, which are higher-level components with the usual complex inner workings. </p>
<p>And of course you can extend any of these classes to include your own custom visuals or class logic, or create non-visual classes that aren't part of the display tree. And you can load in other flash content, or make HTTP connections, etc. etc.</p>
<p>That's all assuming you mean AS3. Does that help? If not you're going to have to make your question more specific. ;)</p>
|
TortoiseSVN Repo-Browser urls <p>How do I remove the urls of repositories that no longer exist in the dropdown in the TortoiseSvn repo-browser?</p>
|
<p>Just move the mouse over the item you want to remove and press <kbd>Shift</kbd>+<kbd>Del</kbd>.</p>
|
What is Teredo Tunneling Pseudo-Interface? <p>Running ipconfig /all shows a Teredo Tunneling Pseudo-Interface. What is that? Does this have something to do with IPv4 vs IPv6? Should I get rid of it? If so how?</p>
|
<p>Is to do with IPv6 </p>
<p>All the gory details here: <a href="http://www.microsoft.com/technet/network/ipv6/teredo.mspx">http://www.microsoft.com/technet/network/ipv6/teredo.mspx</a> </p>
<p>Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...</p>
|
In ruby, why does my IRB interactive debugging session always say "No sourcefile available" <p>Just trying to get my irb sessions to actually list the current line of code, and those around it. Similar to what Perl's -d debugging mode lets you ddo.</p>
|
<p>Its because, when you are doing it interactively, your "sourcefile" is std-in. </p>
|
System.BadImageFormatException: Could not load file or assembly (from installutil.exe) <p>I am trying to install a Windows service using InstallUtil.exe and am getting the error message</p>
<blockquote>
<p>System.BadImageFormatException: Could not load file or assembly '<code>{xxx.exe}</code>' or one of its dependencies. An attempt was made to load a program with an incorrect format.</p>
</blockquote>
<p>What gives?</p>
<hr>
<p>EDIT: (Not by OP) Full message extracted from dup getting way more hits [for googleability]:</p>
<blockquote>
<p>C:\Windows\Microsoft.NET\Framework64\v4.0.30319>InstallUtil.exe C:\xxx.exe
Microsoft (R) .NET Framework Installation utility Version 4.0.30319.1
Copyright (c) Microsoft Corporation. All rights reserved.</p>
<p>Exception occurred while initializing the installation:
System.BadImageFormatException: Could not load file or assembly 'file:///C:\xxx.exe' or one of its dependencies. An attempt was made to load a program with an incorrect format..</p>
</blockquote>
|
<p>Some more detail for completeness in case it helps someone...</p>
<p>Note that the most common reason for this exception these days is attempting to load a 32 bit-specific (<code>/platform:x86</code>) DLL into a process that is 64 bit or vice versa (viz. load a 64 bit-specific (<code>/platform:x64</code>) DLL into a process that is 32 bit). If your <code>platform</code> is non-specific (<code>/platform:AnyCpu</code>), this won't arise (assuming no referenced dependencies are of the wrong bitness).</p>
<p>In other words, running:</p>
<blockquote>
<p>%windir%\Microsoft.NET\Framework\v2.0.50727\installutil.exe </p>
</blockquote>
<p>or:</p>
<blockquote>
<p>%windir%\Microsoft.NET\Framework<strong>64</strong>\v2.0.50727\installutil.exe </p>
</blockquote>
<p>will not work (substitute in other framework versions: <code>v1.1.4322</code> (32-bit only, so this issue doesn't arise) and <code>v4.0.30319</code> as desired in the above).</p>
<p>Obviously, as covered in the other answer, one will also need the .NET version number of the <code>installutil</code> you are running to be >= (preferably =) that of the EXE/DLL file you are running the installer of.</p>
<p>Finally, note that <a href="http://blogs.msdn.com/rmbyers/archive/2009/06/8/anycpu-exes-are-usually-more-trouble-then-they-re-worth.aspx">in Visual Studio 2010, the tooling will default to generating x86 binaries</a> (<a href="https://connect.microsoft.com/VisualStudio/feedback/details/455333/platform-target-is-defaulting-to-x86-rather-than-any-cpu">rather than <em>Any CPU</em> as previously</a>).</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.badimageformatexception.aspx">Complete details of System.BadImageFormatException</a> (saying the only cause is mismatched bittedness is really a gross oversimplification!).</p>
<p>Another reason for a <code>BadImageFormatException</code> under an <strong>x64</strong> installer is that <a href="http://msdn.microsoft.com/en-us/library/kz0ke5xt.aspx">in Visual Studio 2010, the default <code>.vdproj</code> Install Project type generates a 32-bit <code>InstallUtilLib</code> shim, <strong>even on an x64 system</strong></a> (Search for "64-bit managed custom actions throw a System.BadImageFormatException exception" on the page).</p>
|
Is an HTTPS query string secure? <p>I am creating a secure web based API that uses HTTPS; however, if I allow the users to configure it (include sending password) using a query string will this also be secure or should I force it to be done via a POST?</p>
|
<p>Yes, it is. <strong>But using GET for sensitive data is a bad idea</strong> for several reasons:</p>
<ul>
<li>Mostly HTTP referrer leakage (an external image in the target page might leak the password[1])</li>
<li>Password will be stored in server logs (which is obviously bad)</li>
<li>History caches in browsers </li>
</ul>
<p>Therefore, even though Querystring is secured it's not recommended to transfer sensitive data over querystring.</p>
<p><em>[1] Although I need to note that RFC states that browser should not send referrers from HTTPS to HTTP. But that doesn't mean a bad 3rd party browser toolbar or an external image/flash from an HTTPS site won't leak it.</em></p>
|
Reading byte stream returned from JavaEE server <p>We have a JavaEE server and servlets providing data to mobile clients (first JavaME, now soon iPhone). The servlet writes out data using the following code:</p>
<pre><code>DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(someInt);
dos.writeUTF(someString);
</code></pre>
<p>... and so on</p>
<p>This data is returned to the client as bytes in the HTTP response body, to reduce the number of bytes transferred.</p>
<p>In the iPhone app, the response payload is loaded into NSData object. Now, after spending hours and hours trying to figure out how to read the data out in the Objective-C application, I'm almost ready to give up, as I haven't found any good way to read the data into NSInteger and NSString (as corresponding to above protocol)</p>
<p>Would anyone have any pointers how to read stuff out from a binary protocol written by a java app? Any help is greatly appreciated!</p>
<p>Thanks!</p>
|
<p>You'll have to do the demarshalling yourself; fortunately, it's fairly straightforward. Java's <code>DataOutputStream</code> class writes integers in big-endian (network) format. So, to demarshall the integer, we grab 4 bytes and unpack them into a 4-byte integer.</p>
<p>For UTF-8 strings, <code>DataOutputStream</code> first writes a 2-byte value indicating the number of bytes that follow. We read that in, and then read the subsequent bytes. Then, to decode the string, we can use the <code>NSString</code> method <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString%5FClass/Reference/NSString.html#//apple%5Fref/occ/instm/NSString/initWithBytes:length:encoding:" rel="nofollow"><code>initWithBytes:length:encoding:</code></a> as so:</p>
<pre><code>NSData *data = ...; // this comes from the HTTP request
int length = [data length];
const uint8_t *bytes = (const uint8_t *)[data bytes];
if(length < 4)
; // oops, handle error
// demarshall the big-endian integer from 4 bytes
uint32_t myInt = (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | (bytes[3]);
// convert from (n)etwork endianness to (h)ost endianness (may be a no-op)
// ntohl is defined in <arpa/inet.h>
myInt = ntohl(myInt);
// advance to next datum
bytes += 4;
length -= 4;
// demarshall the string length
if(length < 2)
; // oops, handle error
uint16_t myStringLen = (bytes[0] << 8) | (bytes[1]);
// convert from network to host endianness
myStringLen = ntohs(myStringLen);
bytes += 2;
length -= 2;
// make sure we actually have as much data as we say we have
if(myStringLen > length)
myStringLen = (uint16_t)length;
// demarshall the string
NSString *myString = [[NSString alloc] initWithBytes:bytes length:myStringLen encoding:NSUTF8StringEncoding];
bytes += myStringLen;
length -= myStringLen;
</code></pre>
<p>You can (and probably should) write functions to demarshall, so that you don't have to repeat this code for every field you want to demarshall. Also, be <strong>extra careful</strong> about <strong>buffer overflows</strong>. You're handling data sent over the network, which you should always distrust. <strong>Always</strong> verify your data, and <strong>always</strong> check your buffer lengths.</p>
|
Processes and threads <p>1a)Are MS Word and MS PowerPoint different processes or threads of a single process?</p>
<p>b)How does a spell checker routine (common to both, word and PowerPoint) used? I mean is the code copied 2 times for each of the processes in the main memory,</p>
<ul>
<li>if they are different processes</li>
<li>if they are threads.</li>
</ul>
<p>The question is not specific to Windows OS.</p>
|
<p>They are different processes that happen to have overlap in [certain] functionality.</p>
|
How can I remove default banner of web server from response - Apache http1.1 coyote <p>Please let me know how can I remove default banner of web server from response - Apache http1.1 coyote</p>
|
<p>If you're talking about the generated line at the bottom of apache generated pages, you have to update your httpd.conf with this command:</p>
<pre><code>ServerSignature Off
</code></pre>
<p>See <a href="http://httpd.apache.org/docs/2.2/mod/core.html#serversignature" rel="nofollow">http://httpd.apache.org/docs/2.2/mod/core.html#serversignature</a></p>
<p>Be careful, theses informations are also sent through HTTP headers. You can alter them via this <a href="http://httpd.apache.org/docs/2.2/mod/core.html#servertokens" rel="nofollow">directive</a></p>
<p>About Coyote, AFAIK there is no key to hide these info.</p>
|
MVC architecture question for Mac application <p>I have a controller class from which I call a method of model class. Now from this model class method I want to update textView object which is a data member of controller class continuously. I have method in the controller class to edit this textView. I tried creating a controller object from the model class method and edited the textView. Although I don't get any errors, but its not displaying the text in the textView. How do I get the model class use controller class method to display text continuously..?? Is it that I am creating a local controller object and referring to its textView instead of the original controller object.</p>
<p>Controller.m file:</p>
<pre><code>- (void) notifyContentHasChanged:(NSInteger) block {
NSString *str;
str = [NSString stringWithFormat:@"Block Written Successfully: %d\n", block];
[data insertText:str];
}
</code></pre>
<p>Model.m file: </p>
<pre><code>Controller * c = [[Controller alloc] init];
while (USB_SUCCESS(status)){
DfuBlockCnt++;
printf("\nBlocks Written Successfully: %d",DfuBlockCnt);
[c notifyContentHasChanged:DfuBlockCnt];
}
</code></pre>
|
<p>You should look into using KVO - Key Value Observing - that way you can have an observer do all of the work for you.</p>
<p>I wonder if your connection to the NSTextView is missing - it won't give you an error if you try to pass a message to a nil object in Objective C.</p>
|
How do I get the current state of a thread (e.g. blocking, suspended, running, etc..) in win32? <p>I couldn't find a documented API that yields this information.</p>
<p>A friend suggested I use NtQuerySystemInformation. After looking it up, the information is there (see <a href="http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/System%20Information/Structures/SYSTEM_THREAD.html" rel="nofollow">SYSTEM_THREAD</a> ) but it is undocumented, and not very elegant - I get the information for all threads in the system.</p>
<p>Do you know of a more elegant, preferably documented API to do this?</p>
|
<p>NtQuerySystemInformation is totally documented and the best method.
The other answer is completely off topic</p>
|
Any have a Visual Studio shortcut/macro for toggling break on handled/unhandled exceptions? <p>I've been trying to write a macro do do the equivalent of </p>
<ol>
<li>Hitting Ctrl+Alt+E to bring up the Exceptions window</li>
<li>Toggling the textbox in the 'thrown' column for 'Common Language Runtime Exceptions'</li>
<li>Hitting OK</li>
</ol>
<p>If I record this, it records only a single line of macro code which doesn't do anything. Anyone know how to do this?</p>
|
<p>A similar question was posted and answered <a href="http://stackoverflow.com/questions/958011/toggle-break-when-an-exception-is-thrown-using-macro-or-keyboard-shortcut">here</a>. It works for all CLR exceptions and takes ~1.5s to execute.</p>
|
Lucene.Net and Geosearch - is it outthere somewhere? <p>I've found an interesting article about Lucene and geosearching:</p>
<p><a href="http://sujitpal.blogspot.com/2008/02/spatial-search-with-lucene.html" rel="nofollow">http://sujitpal.blogspot.com/2008/02/spatial-search-with-lucene.html</a></p>
<p>Is there an equivilant .NET implementation out there that I have been unable to find or do I have to rework the Java-code in his example to fit in the .NET Framework?</p>
|
<p>I came across this article, as well. I do not see a .NET-specific in my Googling, so I am planning on probably porting this code when the need arises, as well. Right now, I am just getting my feet wet with Lucene.NET and have not gotten to the point that I am comfortable enough with it to start extending it, yet.</p>
<p>The code in the article appears to be a derived example of the conceptual geo-distance functionality outlined in Lucene In Action. Although the book is based on the Java product, it is a great read. The samples port easily and it is full of information.</p>
|
Why does every build change the exe-file? <p>Building the same project (without any changes) produces <strong>binary different</strong> exe-files: some small regions of them are different. Empty project, version information (and auto-increment on every build) is turned off.</p>
<p>Why it happens? And is it possible to make delphi produce binary equal files for the same projects?</p>
|
<p>The various structures in the PE executable file format used by Windows include timestamps that are set by the compiler and linker.</p>
<p>It is possible to post-process the file to reset these values to a defined constant (I wrote a tool to do exactly this for a secure product that needed exact hash values), but this should only be done on ready-to-ship executables, as some debuggers rely on the timestamps for source lookup, etc.</p>
|
IIS7 shows welcome screen in Firefox, Internet Explorer works correctly <p>Has anyone encountered the following problem: I have IIS7 running on my computer. On that same computer, I open IE7 and the website works (<a href="http://localhost/web.site/Default.aspx" rel="nofollow">http://localhost/web.site/Default.aspx</a>). Put that same url in Firefox 3 and I get the welcome screen of IIS7, a big image with IIS7 in the middle and 'Welcome' in several different languages. Clicking on the image leads you to <a href="http://www.iis.net/" rel="nofollow">http://www.iis.net/</a>.</p>
|
<p>One browser accesses your server via 127.0.0.1, and another via your external IP.</p>
<p>Make sure virtualhost works with all network interfaces.</p>
|
Signaling validation errors in assigning a virtual attribute? <p>This is a Rails/ActiveRecord question.</p>
<p>I have a model which basically has to represent <em>events</em> or performances. Each event has many <em>attributions</em>: an attribution is basically something like "In this event, Person X had Role Y".</p>
<p>I concluded that the best way to allow a user to edit this data is by providing a free text field which expects a structured format, which I'll call a <em>role string</em>:</p>
<p><code>singer: Elvis Costello, songwriter: Paul McCartney, ...</code></p>
<p>where I use autocompletion to complete on both the names of roles (singer, songwriter...) and the names of people. Both roles and people are stored in the database.</p>
<p>To implement this, I created a virtual attribute in the Event model:</p>
<pre><code>def role_string
# assemble a role string from the associations in the model
end
def role_string=(s)
# parse a string in the above role string format,
# look up the People and Events mentioned, and update
# what's in the database
end
</code></pre>
<p>This is all fine. The whole thing works quite well, when the role string is well-formed and the associations given by the role string all check out.</p>
<p>But what if the role string is malformed? Okay, I figure, I can just use a regex together with standard validation to check the format:</p>
<pre><code>validates_format_of :role_string, :with => /(\w+:\s*\w+)(,\s*\w+:\s*\w+)*/
</code></pre>
<p>But what if the associations implied by the role string are invalid? For example, what happens if I give the above role string, and <code>Elvis Costello</code> doesn't reference a valid person?</p>
<p>I thought, well, I could use <code>validates_each</code> on the attribute <code>:role_string</code> to look up the associations and throw an error if one of the names given doesn't match anything, for example.</p>
<p>My questions are two: first, I don't like this approach, since to validate the associations I would have to parse the string and look them up, which duplicates what I'd be doing in <code>role_string=</code> itself, except for actually saving the associations to the database.</p>
<p>Second, ... how would I indicate that an error's occurred in assigning to this virtual attribute?</p>
|
<p>First of all, you're attributing the Person to the Event incorrectly. You should instead pass a Person's ID to the event, rather than a string of the person's name. For instance, what if a Person with an ID of 230404 and a name of "Elvis Costello" changes his name to "Britney Spears?" Well, if that were to happen, the ID would remain the same, but the name would change. However, you would not be able to reference that person any longer.</p>
<p>You should set up your associations so that the foreign key references people in multiple cases:</p>
<pre><code>has_one :singer, :class_name => "Person", :foreign_key => "singer_id"
has_one :songwriter, :class_name => "Person", :foreign_key => "songwriter_id"
</code></pre>
<p>This way, you can have multiple people associated with an Event, under different roles, and you can reference multiple attributes that Person may have. For example:</p>
<pre><code>Event.first.singer.name # => "Elvis Costello"
Event.first.songwriter.name # => "Britney Spears"
</code></pre>
<p>You can research the available validations for associations (<code>validates_associated</code>), as well as whether or not an ID is present in a form (<code>validates_presence_of</code>). I would recommend creating your own custom validation to ensure that a Person is valid before_save. Something like (untested):</p>
<pre><code>def before_save
unless Person.exists?(self.songwriter_id)
self.errors.add_to_base("Invalid songwriter. Please try again!")
return false
end
end
</code></pre>
<p>Also, I noticed that you're looking for a way for users to select a user which should be used for the roles in your Event. Here is what you can do in your form partial: </p>
<pre><code>select(:event, :singer_id, Person.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => 'None' })
</code></pre>
<p>Hope this helps!</p>
|
Can I convert a C# string value to an escaped string literal <p>In C#, can I convert a string value to a string literal, the way I would see it in code? I would like to replace tabs, newlines, etc. with their escape sequences.</p>
<p>If this code:</p>
<pre><code>Console.WriteLine(someString);
</code></pre>
<p>produces:</p>
<pre><code>Hello
World!
</code></pre>
<p>I want this code:</p>
<pre><code>Console.WriteLine(ToLiteral(someString));
</code></pre>
<p>to produce:</p>
<pre><code>\tHello\r\n\tWorld!\r\n
</code></pre>
|
<p>I found this:</p>
<pre><code>private static string ToLiteral(string input)
{
using (var writer = new StringWriter())
{
using (var provider = CodeDomProvider.CreateProvider("CSharp"))
{
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
return writer.ToString();
}
}
}
</code></pre>
<p>This code:</p>
<pre><code>var input = "\tHello\r\n\tWorld!";
Console.WriteLine(input);
Console.WriteLine(ToLiteral(input));
</code></pre>
<p>Produces:</p>
<pre><code> Hello
World!
"\tHello\r\n\tWorld!"
</code></pre>
|
variable not being passed? <p>I have this code</p>
<pre><code>while($row = mysql_fetch_row($result))
{
echo '<tr>';
$pk = $row[0]['ARTICLE_NO'];
foreach($row as $key => $value)
{
echo '<td><a href="#" onclick="GetAuctionData(\''.$pk.'\')">' . $value . '</a></td>';
}
</code></pre>
<p>which gets pk. pk is then passed on to the axjax part with this:</p>
<pre><code>function GetAuctionData(pk)
{
.....
var url="get_auction.php?"
url=url+"cmd=GetAuctionData&pk="+pk;
</code></pre>
<p>And finally used in a separate php file with:</p>
<pre><code>$pk = $_GET["pk"];
$sql="SELECT * FROM Auctions WHERE ARTICLE_NO ='$pk'";
</code></pre>
<p>the second php file works fine when using it by itself and passing parameters. Likewise there are no errors anywhere. The problem seems to be with passing or generating $pk, as the links in the output file result in $pk being incremednted by 2, eg 4, 6, 8 etc</p>
<p>I can not understand why this is happening.</p>
|
<p>mysql_fetch_row <a href="http://no.php.net/manual/en/function.mysql-fetch-row.php" rel="nofollow">link</a> does not have subarrays. It will return the first field as 0, next as 1, etc. </p>
<p>Try with </p>
<pre><code>$pk = $row[0];
</code></pre>
<p>This can easily be used with your foreach</p>
<pre><code>while($row = mysql_fetch_assoc($result))
$pk = $row['ARTICLE_NO'];
</code></pre>
<p>or this gives you both associative and numbered array.</p>
<pre><code>while($row = mysql_fetch_array($result, MYSQL_BOTH))
$pk = $row['ARTICLE_NO'];
</code></pre>
<p>EDIT:
Based on </p>
<pre><code>$result = mysql_query("SELECT SELLER_ID, ACCESSSTARTS, ARTICLE_NAME FROM {$table}");
</code></pre>
<p>You have to include the row you want a value from. ;)</p>
<pre><code>$result = mysql_query("ARTICLE_NO, SELECT SELLER_ID, ACCESSSTARTS, ARTICLE_NAME FROM {$table}");
</code></pre>
<p>BTW: Im pretty sure this nested loop will not produce what you want. You'll get 3 links to each article_no. The first with seller_id as text, the second text is accessstarts, and the last link with the same href will have the text article_name. </p>
<p>Maybe something like this?</p>
<pre><code>while($row = mysql_fetch_assoc($result))
{
$pk = $row['ARTICLE_NO'];
echo '<td><a href="#" onclick="GetAuctionData(\''.$pk.'\')">' . $row['ARTICLE_NAME'] . '</a></td>';
}
</code></pre>
|
Hibernate and Oracle native functions <p>I have an entity that maps to an external oracle table which is one of the primary data sources of my application. This entity is modelled using hibernate.</p>
<p>The oracle table now has a complex function defined the calculates some special values. I need to call this function somehow - almost as another accessor on the entity.</p>
<p>What would you suggest is the best way to incorporate this function call so that I can maintain relatively normal hibernate access to the entities?</p>
|
<p>I have a solution using the @Formula annotation</p>
|
ASP.Net: Users are logged out when deploying a new file to the server <p>Everytime I upload a file to my ASP.NET site, all users are logged out (aka, I guess their session become invalidated). </p>
<p>Is there any way to "hotswap" the code in ASP.NET so that this doesn't happen? Compile before deploying etc. </p>
<p>My deployment method is pretty simple through a SVN update. </p>
<p>Thanks!
/Niels</p>
|
<p>You could store your session in a <a href="http://msdn.microsoft.com/en-us/library/ms229862(VS.80).aspx" rel="nofollow">SQL database</a>, thus the application restart would not lose your sessions.</p>
<p>Having precompiled non updatable code to deploy would make your xcopy faster alright but app pool would still be restarted.</p>
<p>UPDATE: @configurator, making your comment visible to any casual observers
<a href="http://support.microsoft.com/kb/317604" rel="nofollow">http://support.microsoft.com/kb/317604</a> </p>
<p>(there is plenty of coverage of the different options and how-tos out there, e.g. more than one session db, different frameworks dbs in same db, etc)</p>
|
How to access previous/next element while for looping? <p>Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop?</p>
<pre><code>l=[1,2,3]
for item in l:
if item==2:
get_previous(l,item)
</code></pre>
|
<p>Expressed as a generator function:</p>
<pre><code>def neighborhood(iterable):
iterator = iter(iterable)
prev = None
item = iterator.next() # throws StopIteration if empty.
for next in iterator:
yield (prev,item,next)
prev = item
item = next
yield (prev,item,None)
</code></pre>
<p>Usage:</p>
<pre><code>for prev,item,next in neighborhood(l):
print prev, item, next
</code></pre>
<p><strong>Edit:</strong> I thought it would reduce the readability, but this way seem to look better.</p>
|
Autotools : how to set global compilation flag <p>I have a project with several sources directories : </p>
<pre><code>src/A
/B
/C
</code></pre>
<p>In each, the Makefile.am contains </p>
<pre><code>AM_CXXFLAGS = -fPIC -Wall -Wextra
</code></pre>
<p>How can avoid repeating this in each source folder ? </p>
<p>I tried to modifiy src/Makefile.am and the configure.in, but without success. I thought I could use AC_PROG_CXX to set the compilation flags globally but can't find much documentation on how to use those macro (do you have any pointer to such a documentation ?).</p>
<p>Thanks in advance</p>
|
<p>You can do several things:</p>
<p>(1) One solution is to include a common makefile fragment on all your <code>Makefile.am</code>s:</p>
<pre><code>include $(top_srcdir)/common.mk
...
bin_PROGRAMS = foo
foo_SOURCES = ...
</code></pre>
<p>in that case you would write</p>
<pre><code>AM_CXXFLAGS = -fpic -Wall -Wextra
</code></pre>
<p>to <code>common.mk</code> and in the future it will be easier to add more macros or rules to all <code>Makefile.am</code>s by just editing this file.</p>
<p>(2) Another solution would be to set these variables globally in your <code>configure.ac</code> (the name <code>configure.in</code> has been deprecated long ago), as in :</p>
<pre><code>...
AC_SUBST([AM_CXXFLAGS], [-fpic -Wall -Wextra])
...
</code></pre>
<p>Then you don't even have to say anything in your <code>Makefile.am</code>s, they automatically inherit this global definition. The drawback is that you can't opt-out easily (with the first solution it's easy to decide not to include <code>common.mk</code>) and the dependency is not really explicit to third-party people (when they read the <code>Makefile.am</code> they have no hint about where the flags may come from).</p>
<p>(3) A third solution would be to do as <a href="http://stackoverflow.com/users/15622/orsogufo">orsogufo</a> suggested: overwriting the user variable CXXFLAGS in <code>configure.ac</code>. I would advise against it, because it defeats one of the features of the GNU Build System: users are allowed to override this variable at <code>make</code>-time. For instance you may want to type</p>
<pre><code>make CXXFLAGS='-O0 -ggdb'
</code></pre>
<p>when debugging a piece of code, and this will overwrite any definition of <code>CXXFLAGS</code> (but
not those in <code>AM_CXXFLAGS</code>). To be honest, most projects fails to support this correctly because they play tricks with <code>CXXFLAGS</code>.</p>
<p>Finally, I should mention that <code>-fpic</code>, <code>-Wall</code>, and <code>-Werror</code> are not portable options.
Depending on the scope of your project you may want to add configure check for these (<a href="http://www.gnu.org/software/gnulib/">gnulib</a> recently acquired new macros to tests for warnings flags, and <a href="http://www.gnu.org/software/libtool/">libtool</a> can be used to build shared libraries).</p>
|
how to block a superclass method to be called to a subclass <p>I'm extending the functionality of a class with a subclass, and I'm doing some dirty stuff that make superclass methods dangerous (app will hang in a loop) in the context of the subclass. I know it's not a genius idea, but I'm going for the low-hanging fruit, right now it's gonna save me some time. Oh it's a dirty job, but someone's gotta do it. </p>
<p>Bottom line, I need to either block that method from outside, or throw an exception when it's called directly to the superclass. (But I still use it from the subclass, except with care).</p>
<p>What would be the best way to do this?</p>
<p>UPDATE ---</p>
<p>So this is what I went for. I'm not self-answering, as Boaz' answer mentions multiple valid ways to do this, this is just the way that suited me. In the subclass, I overrode the method like this:</p>
<pre><code>- (int)dangerousMethod
{
[NSException raise:@"Danger!" format:@"Do not call send this method directly to this subclass"];
return nil;
}
</code></pre>
<p>I'm marking this as answered, but evidently that doesn't mean it's closed, further suggestions are welcome.</p>
|
<p>You can override whichever methods you want to block in your subclass's <code>.h</code> file. You can make <code>dangerousMethod</code> unavailable by placing the following in your <code>.h</code> file.</p>
<pre><code>- (int)dangerousMethod __attribute__((unavailable("message")));
</code></pre>
<p>This will make the <code>dangerousMethod</code> method unavailable to anyone using your subclass.</p>
<p>To keep other code from using the superclass's version this method, you can further restrict by putting this in your <code>.m</code> file.</p>
<pre><code>- (int)dangerousMethod
{
return nil;
}
</code></pre>
|
How to pass server-side error messages to ASP.NET Ajax client? <p>An example scenario:</p>
<ol>
<li>User performs an update, for example a drag & drop. This is an ajax request.</li>
<li>Server-side code cannot validate the update or the operation just fails. An exception is thrown.</li>
<li>A reasonable error message should be shown to the user.</li>
</ol>
<p>How should I communicate the exception to the client side and show the error message in a div message box?</p>
<p>The message should be shown <strong>after the fact</strong>. Sometimes it is possible to prevent errors in client-side code but I'm not concerned about this.</p>
<p>With traditional data binding in the code behind file I can show a label after an error condition. But if the Ajax control is connected to a provider class specified in the aspx, I don't see how this would be possible. Only option I can think of is to catch server-side exceptions in client-side code. Is this possible? </p>
<p>I'm using Telerik RadControls for ASP.NET Ajax.</p>
|
<p>You can try adding the error,handler directly in Ajax framework like this:</p>
<p><a href="http://encosia.com/how-to-improve-aspnet-ajax-error-handling/" rel="nofollow">http://encosia.com/how-to-improve-aspnet-ajax-error-handling/</a></p>
|
Is UML a good notation for messaging systems? <p>Ever since the publication of <a href="http://rads.stackoverflow.com/amzn/click/0321200683" rel="nofollow">Enterprise Integration Patterns</a> people have been using the notation introduced in that book for documenting asynchronous heterogenous messaging systems.</p>
<p>But our shop is more or less standardized around a proprietary documentation tool that does exclusively UML. Is one of the standard UML diagrams appropriate for documenting asynchronous messaging systems, including transformers, routers et al.? If yes, which one? If not, what would be a killer argument against the tweaking of UML for this purpose?</p>
|
<p>UML provides a mechanism for extension through <a href="http://en.wikipedia.org/wiki/Profile_%28UML%29" rel="nofollow">profiles</a></p>
<p>A profile allows you to specify stereotypes, tagged values, and constraints.</p>
<p>Every stereotype can have an optional stereotype icon.</p>
<p>Perhaps there is an EIP profile for UML you could download?</p>
<p>If not, you can build your own profile if your UML tool supports this, and use the icons available as Visio shapes from <a href="http://www.eaipatterns.com/downloads.html" rel="nofollow">Gregor Hohpe's website</a></p>
<p>Hope this helps.</p>
|
What advice can you give me for writing a meaningful benchmark? <p>I have developed a framework that is used by several teams in our organisation. Those "modules", developed on top of this framework, can behave quite differently but they are all pretty resources consuming even though some are more than others. They all receive data in input, analyse and/or transform it, and send it further. </p>
<p>We planned to buy new hardware and my boss asked me to define and implement a benchmark based on the modules in order to compare the different offers we have got. </p>
<p>My idea is to simply start sequentially each module with a well chosen bunch of data as input. </p>
<p>Do you have any advice? Any remarks on this simple procedure? </p>
|
<p>Your question is pretty broad, so unfortunately my answer will not be very specific either.</p>
<p>First, benchmarking is hard. Do not underestimate the effort necessary to produce meaningful, repeatable, high-confidence results.</p>
<p>Second, what is your performance goal? Is it throughput (transaction or operations per second)? Is it latency (time it takes to execute a transaction)? Do you care about average performance? Do I care about worst case performance? Do you care about the absolute worst case or I care that 90%, 95% or some other percentile get adequate performance?</p>
<p>Depending on which goal you have, then you should design your benchmark to measure against that goal. So, if you are interested in throughput, you probably want to send messages / transactions / input into your system at a prescribed rate and see if the system is keeping up.</p>
<p>If you are interested in latency, you would send messages / transactions / input and measure how long it takes to process each one.</p>
<p>If you are interested in worst case performance you will add load to the system until up to whatever you consider "realistic" (or whatever the system design says it should support.)</p>
<p>Second, you do not say if these modules are going to be CPU bound, I/O bound, if they can take advantage of multiple CPUs/cores, etc. As you are trying to evaluate different hardware solutions you may find that your application benefits more from a great I/O subsystem vs. a huge number of CPUs.</p>
<p>Third, the best benchmark (and the hardest) is to put realistic load into the system. Meaning, you record data from a production environment, and put the new hardware solution through this data. Getting this done is harder than it sounds, often, this means adding all kinds of measure points in the system to see how it behaves (if you do not have them already,) modifying the existing system to add record/playback capabilities, modifying the playback to run at different rates, and getting a realistic (i.e., similar to production) environment for testing.</p>
|
How to run my program on before logout on windows XP? <p>I am looking for an inverse version of "RunOnceEx".</p>
<p>RunOnceEx does run some program, before the user's shell(desktop&taskbar) start. The login progress will not continue before the runonceex complete.</p>
<p>I want to do exact the same but on user logout.
When she/he logout, all running program shutdown, leaving shell(desktop&taskbar), then ""I wish my program will be execute this moment"", finally logout.</p>
<p>I think it is possible because the "mobsync.exe" is doing that. But I cannot find where and how to do it.</p>
|
<p>Warning, as said <a href="http://www.eggheadcafe.com/software/aspnet/30020406/trouble-getting-logoff-sc.aspx" rel="nofollow"><strong>here</strong></a>, <code>gpedit.msc</code> will allow you to configure a logoff script <strong>for <em>all</em> users</strong>.</p>
<p>If you need that script only for one user, you need to declare it directly in the registry, both in <code>HKCU</code> and <code>HKLM</code>.</p>
|
WebPartManager & Mobile Controls <p>Can WebPartManager be used with web parts constructed from mobile web controls? If possible, should it be done?</p>
|
<p>I looks promising and you just have to tried it out. In mobile development you always need to have full control of the generated output, and this looks like a tool to do a part of the job. </p>
<p>But remember many devices have issues of their own, so you need to be able to control every part of your output. So far I have not come accros any framework that was suitable for the job. </p>
|
How do I redirect URLS that begin with /test/ to a separate script? <p>I have an existing htaccess that works fine:</p>
<pre><code>RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule (.*) /default.php
DirectoryIndex index.php /default.php
</code></pre>
<p>I wish to modify this so that all urls that start with /test/ go to /test/default.php.</p>
<p>Example: <a href="http://www.x.com/hello.php" rel="nofollow">http://www.x.com/hello.php</a> -- > <a href="http://www.x.com/default.php" rel="nofollow">http://www.x.com/default.php</a>
Example: <a href="http://www.x.com/test/hello.php" rel="nofollow">http://www.x.com/test/hello.php</a> -- > <a href="http://www.x.com/test/default.php" rel="nofollow">http://www.x.com/test/default.php</a></p>
|
<p>Basically, just put <code>/test/</code> in front of your expression. Also, the parentheses are unnecessary here:</p>
<pre><code>RewriteRule ^/test/ /test/default.php
</code></pre>
|
HTTP headers encoding/decoding in Java <p>A custom HTTP header is being passed to a Servlet application for authentication purposes. The header value must be able to contain accents and other non-ASCII characters, so must be in a certain encoding (ideally UTF-8).</p>
<p>I am provided with this piece of Java code by the developers who control the authentication environment:</p>
<pre><code>String firstName = request.getHeader("my-custom-header");
String decodedFirstName = new String(firstName.getBytes(),"UTF-8");
</code></pre>
<p>But this code doesn't look right to me: it presupposes the encoding of the header value, when it seemed to me that there was a proper way of specifying an encoding for header values (from MIME I believe).</p>
<p>Here is my question: what is the right way (tm) of dealing with custom header values that need to support a UTF-8 encoding:</p>
<ul>
<li>on the wire (how the header looks like over the wire)</li>
<li>from the decoding point of view (how to decode it using the Java Servlet API, and can we assume that request.getHeader() already properly does the decoding)</li>
</ul>
<p>Here is an environment independent code sample to treat headers as UTF-8 in case you can't change your service:</p>
<pre><code>String valueAsISO = request.getHeader("my-custom-header");
String valueAsUTF8 = new String(firstName.getBytes("ISO8859-1"),"UTF-8");
</code></pre>
|
<p>Again: RFC 2047 is not implemented in practice. The next revision of HTTP/1.1 is going to remove any mention of it.</p>
<p>So, if you need to transport non-ASCII characters, the safest way is to encode them into a sequence of ASCII, such as the "Slug" header in the Atom Publishing Protocol.</p>
|
Safe stream update of file <p>We perform updates of large text files by writing new records to a temp file, then replacing the old file with the temp file. A heavily abbreviated version:</p>
<pre><code>var tpath = Path.GetTempFileName();
try
{
using (var sf = new StreamReader(sourcepath))
using (var tf = new StreamWriter(tpath))
{
string line;
while ((line = sf.ReadLine()) != null)
tf.WriteLine(UpdateLine(line));
}
File.Delete(sourcepath);
File.Move(tpath, sourcepath);
}
catch
{
File.Delete(tpath);
throw;
}
</code></pre>
<p>If anything throws an exception (file not found, no permission), the original file is left untouched, which is what we want.</p>
<p>However, the code has the following problems:</p>
<ol>
<li><p>Is there a real-world situation where the <code>Delete</code> works but the <code>Move</code> fails? This would delete the original and updated data. This would be bad.</p></li>
<li><p>The most common failure is the source file being open from another application, and the <code>Delete</code> fails. This means all the Update work is discarded. Is there a way to see if the source file is deletable at the start, and abandon the update if not?</p></li>
<li><p>We have users putting Windows Explorer Summary properties, like Title or Comments, on files. These are discarded when we delete the file. Is there a way to copy the old file's Summary properties to a new file? Should we do this?</p></li>
</ol>
|
<p>The normal way of avoiding the "delete then move fails problem" is:</p>
<ul>
<li>Write to file.new</li>
<li>Move file.current to file.old</li>
<li>Move file.new to file.current</li>
<li>Delete file.new</li>
</ul>
<p>Then when you come to read, use file.new if file.current is missing, deleting file.old if you see it.</p>
<p>Checking for whether or not the file is available: try opening it for write, but appending to the end. Of course, you'll need to close the handle before you then move it, and in-between someone else could open it - but it would at least be a <em>reasonable</em> optimisation.</p>
<p>Not sure about copying summaries etc, I'm afraid.</p>
|
How can I customize the text color of the back button in a UINavigationController header view? <p>I'm using a custom tintColor on my UINavigationController's navigation bar, and because the color is so light I need to use dark colored text. It's relatively easy to swap out the title view, and the custom buttons I've added on the right hand side, but I can't seem to get a custom view to stick on the back button. This is what I'm trying right now:</p>
<pre><code> UILabel *backLabel = [[UILabel alloc] initWithFrame:CGRectZero];
[backLabel setFont:[UIFont fontWithName:[[UIFont fontNamesForFamilyName:@"Arial Rounded MT Bold"] objectAtIndex:0] size:24.0]];
[backLabel setTextColor:[UIColor blackColor]];
[backLabel setShadowColor:[UIColor clearColor]];
[backLabel setText:[aCategory displayName]];
[backLabel sizeToFit];
[backLabel setBackgroundColor:[UIColor clearColor]];
UIBarButtonItem *temporaryBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:backLabel];
temporaryBarButtonItem.customView = backLabel;
[backLabel release];
self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
[temporaryBarButtonItem release];]
</code></pre>
<p>The custom view doesn't stick though, and I don't see any obviously easy way to get at the actual text inside the default button and start changing its style. </p>
|
<p>This works, solves the original question (change the Navbar BACK button - and no buttons on other toolbars, no buttons on tab bars, etc):</p>
<pre><code>[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], UITextAttributeTextColor,nil]
forState:UIControlStateNormal];
</code></pre>
|
How do I determine if an email is Base64 encoded? <p>I am having difficulty determining if the body of a text email message is base64 encoded.
if it is then use this line of code;
making use of jython 2.2.1</p>
<pre><code>dirty=base64.decodestring(dirty)
</code></pre>
<p>else continue as normal.</p>
<p>This is the code I have atm. What line of code will allow me to extract this from the email: </p>
<p>"Content-Transfer-Encoding: base64" </p>
<pre><code>import email, email.Message
import base64
def _get_email_body(self):
try:
parts=self._email.get_payload()
check=parts[0].get_content_type()
if check=="text/plain":
part=parts[0].get_payload()
enc = part[0]['Content-Transfer-Encoding']
if enc == "base64":
dirty=base64.decodestring(dirty)
elif check=="multipart/alternative":
part=parts[0].get_payload()
enc = part[0]['Content-Transfer-Encoding']
if part[0].get_content_type()=="text/plain":
dirty=part[0].get_payload()
if enc == "base64":
dirty=base64.decodestring(dirty)
else:
return "cannot obtain the body of the email"
else:
return "cannot obtain the body of the email"
return dirty
except:
raise
</code></pre>
<p>OKAY this code works now! thanks all</p>
|
<p>Try:</p>
<pre><code>enc = msg['Content-Transfer-Encoding']
</code></pre>
<p>It's a header so you won't be able to get it looking at the body. You should be able to get at the same place you find out the Subject.</p>
|
How to fill DataTable from an in-memory Excel Worksheet <p>Our client gets Excel files in Excel's HTML format.(That's the way it arrives; nobody has any control over that.) We then need to run a report based on the data in the file. Using ADO.NET (OleDbReader) results in a "External file not in expected format" exception.</p>
<p>If the data is converted to regular Excel format it gets read in OK. However this is not really a solution as it imposes an extra step they must take and they are not too computer-literate at the best of times.</p>
<p>The only solution I could come up with was to use Excel Automation to create a new spreadsheet, fill it with the same data, and read that one instead. But ADO.NET seem to only be able read from a file on disk. I could of course save the file and delete it when I'm done with it (which I've verified will work). But I'm uncomfortable with the idea of messing around with their filesystem. So my first question is - is there a way to fill a DataTable from an in-memory Excel Worksheet?</p>
<p>Additionally, I don't like the whole business with using Automation; it's incredibly slow. The operation takes over 30 seconds even without filling the DataTable. So a solution that makes it any slower is not going to be any good. That brings me to my second question - Is there a better way to accomplish what I'm trying here?</p>
|
<p>Try the HTML Agility Pack: <a href="http://www.codeplex.com/htmlagilitypack" rel="nofollow">http://www.codeplex.com/htmlagilitypack</a></p>
<p>I use it in a similar scenario. In my case:...</p>
<ul>
<li>someone pasted a table from excel into the clipboard</li>
<li>retrieve the HTML text</li>
<li>use HTML Agility back to find the TABLE, TR, TH, TD tags</li>
<li>and then construct the DataTable from it</li>
</ul>
<p>At no time in my case is the HTML persisted to disk</p>
|
JavaScriptSerializer C# and Generics (newbie mistakes I think!) <p>WinForms C#.. am getting some JSON in the format below (bottom of message) and trying to deserialise using:</p>
<p>using System.Web.Script.Serialization;</p>
<p>When I had simply this json returned:</p>
<pre><code>{
"objects": [
{
"categoryid": "1",
"name": "funny",
"serverimageid": "1",
"dateuploaded": "2008-11-17 16:16:41",
"enabled": "1"
},
{
"categoryid": "2",
"name": "happy",
"serverimageid": "2",
"dateuploaded": "2008-11-17 16:17:00",
"enabled": "1"
},
{
"categoryid": "3",
"name": "sad",
"serverimageid": "3",
"dateuploaded": "2008-11-16 16:17:13",
"enabled": "1"
}
]
}
</code></pre>
<p>Then is was easy to deserialize: (yikes.. a bit hacky)</p>
<pre><code>// s is the string
s = s.Remove(0, 11);
// last }
int stringLength = s.Length;
s = s.Remove(stringLength - 1, 1);
listOfCategories = serializer1.Deserialize<List<Category>>(s);
</code></pre>
<p>Where</p>
<pre><code>public class Category
{
public int categoryID;
public string name;
public int imageID;
public DateTime dateUpdated;
public int isActive;
public int displayOrder;
}
</code></pre>
<p>However now, I'm stuck! Have tried a list of lists... but can't get anywhere..</p>
<p>Much appreciated any help.</p>
<pre><code>{
"objects": {
"categories": [
{
"name": "Congratulations",
"imageID": "1",
"isActive": "1",
"displayOrder": "0",
"dateUpdated": "2008-11-27 00:00:00"
},
{
"name": "Animals",
"imageID": "2",
"isActive": "1",
"displayOrder": "0",
"dateUpdated": "2008-11-26 00:00:00"
},
{
"name": "Romance",
"imageID": "3",
"isActive": "1",
"displayOrder": "0",
"dateUpdated": "2008-11-24 00:00:00"
}
],
"present": [
{
"presentID": "1",
"name": "Tiger",
"categoryID": "2",
"imageID": "1",
"dateUpdated": "2008-11-27",
"isActive": "1",
"isAnimated": null,
"isInteractive": null,
"isAdaptive": null,
"webLinkURL": null
},
{
"giphtID": "2",
"name": "Donkey",
"categoryID": "2",
"imageID": "2",
"dateUpdated": "2008-11-27",
"isActive": "1",
"isAnimated": null,
"isInteractive": null,
"isAdaptive": null,
"webLinkURL": null
},
{
"giphtID": "3",
"name": "Elephant",
"categoryID": "2",
"imageID": "3",
"dateUpdated": "2008-11-27",
"isActive": "1",
"isAnimated": null,
"isInteractive": null,
"isAdaptive": null,
"webLinkURL": null
}
]
}
}
</code></pre>
|
<p>This seems to work fine (And no wacky string trimming!):</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
class Program
{
static void Main( string[] args )
{
string json = System.IO.File.ReadAllText( "../../input.json" );
var serializer = new JavaScriptSerializer();
Structure jsonStructure = serializer.Deserialize<Structure>( json );
System.Diagnostics.Debugger.Break();
}
}
class Structure
{
public StructureObjects objects;
}
class StructureObjects
{
public List<StructureCategory> categories;
public List<StructurePresent> present;
}
class StructureCategory
{
public string name;
public int imageID;
public DateTime dateUpdated;
public int isActive;
public int displayOrder;
}
class StructurePresent
{
public int presentID;
public string name;
public int categoryID;
public int imageID;
public DateTime dateUpdated;
public int isActive;
public int? isAnimated;
public int? isInteractive;
public int? isAdaptive;
public Uri webLinkURL;
}
</code></pre>
<p>Thanks for the System.Web.Script.Serialization pointer, I would never have found that!</p>
|
How can you write info to a Windows "global (in-memory) variable" than can be shared by various applications, using Windows APIs? <p>Maybe this cannot be done, but please help or suggest how this can be achieved without writing something to disk.</p>
<p>Lets suppose there are two string values that I want to share between two independent applications.</p>
<p>You are welcome to provide code sample in any programming language.</p>
|
<p>What you probably want to do is create a memory-mapped file. You can create a memory-mapped file that doesn't have any backing store on disk, but is instead backed by the system page file. Have a look at the documentation for <a href="http://msdn.microsoft.com/en-us/library/aa366537(VS.85).aspx" rel="nofollow"><code>CreateFileMapping</code></a>, in particular when the first parameter is <code>INVALID_HANDLE_VALUE</code>.</p>
<p>You can give such a file mapping a unique system-wide name, and then other applications can open it using <code>OpenFileMapping</code> and providing the same name.</p>
<p>Once you have such a block of shared memory, you can put any information you like into it. Note that since the memory is shared across processes, you don't want to store any pointers into the block of memory (which precludes doing things like storing a <code>std::string</code> there).</p>
|
How to bind a click event on a recently added <a> tag in jquery <p>I have 6 links on a page to an mp3.</p>
<p>The plugin I installed replaces those links with a swf and plays that mp3 inline.</p>
<p>The problem I <em>had</em> was that it was possible to activate all 6 links and have all audio playing at once. I <em>solved</em> that problem (I feel in a clumsy novice way though) by catching the < a > tag before it was replaced with the embed tag and then putting it back when another one was clicked.</p>
<p><strong>However, this is my problem now</strong>: the < a > tag I put back looses it's onClick event (i think that's what is happening) and so, if clicked a second time, fails to switch like the first time.</p>
<pre><code>$(".storyplayer a").bind("click", function() {
// replace the <a> tag from the previous media player installation
if (previousplayerlocation != null) {$("#" + previousplayerlocation + " .storyplayer").html(graboldcode);}
// now remember this installation's <a> tag before it's replaced
graboldcode = $(this).parent().html();
// remember where I grabbed this <a> tag from
previousplayerlocation = $(this).parents("div.storylisting").attr("id");
// replaces the <a> tag with the media player.
$(this).media({width: 190,height: 30});
return false;
});
</code></pre>
<p>I am asking if there is a way to re-assign the click event to the "if" statement?
Thanks!</p>
|
<p>Use event delegation - this means binding the click to some container and let that handle the event. You can then query the event.target to see if it was an anchor that was clicked then do you required behaviour. This is better for a number of reasons.</p>
<ol>
<li>Less events bound to elements (performance)</li>
<li>No need to rebind events after adding/removing content as the container remains a constant and will always be there to handle the bubbled click event.</li>
</ol>
<p>The code would be something like</p>
<pre><code>$('#someContainer').click( function(ev){
var $el=$(ev.target);
if ( $el.is('a') ){
//do your stuff
}
});
</code></pre>
<p>See this <a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery" rel="nofollow">post</a> for more reading</p>
|
Visual Studio C#-settings and StyleCop (MS Source Analysis) <p>Does anyone have settings for Visual Studio, in XML or a .vssettings-file, that is compatible with <a href="http://code.msdn.microsoft.com/sourceanalysis" rel="nofollow">StyleCop</a>?</p>
<p>I've used the book <a href="http://rads.stackoverflow.com/amzn/click/0321545613" rel="nofollow">Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries</a> for guidance on what Microsoft finds to be the correct way to format C# and set my Visual Studio-settings accordingly.</p>
<p>But when I use "Format Document" in Visual Studio, StyleCop will fire on all cylinders and complains on all sorts of things.</p>
<p>Some errors even seems impossible to set in the settings. Like curly braces should be on a new line, if something spans for more than one row.</p>
|
<p><a href="http://www.codeplex.com/StyleCopForReSharper" rel="nofollow">StyleCop for ReSharper</a> would certainly help:</p>
<p>StyleCop for ReSharper is now feature complete in that is has reached feature parity with StyleCop 4.3.</p>
<p>There are 148 StyleCop rules.</p>
<ul>
<li>38 of these must be fixed manually (normally because you have to type descriptive text or rename variables).</li>
<li>Of the remaining 110 rules 58 are fixed by R# Code Cleanup (silent mode).</li>
<li>Of the 52 now remaining we have Code Cleanup rules that fix all of them automatically. </li>
</ul>
<p>We also provide 106 Quick Fixes that provide in place context menu fixes for violations for the 110 rules that can be fixed automatically</p>
<p>We also ship a "StyleCop friendly ReSharper Code Style Sharing Settings file" which configures ReSharper to automatically format code in a StyleCop friendly manner.</p>
|
How can I filter out the rows which contain a particular column with null or empty data in SQL? <p>In SQL, How we make a check to filter all row which contain a column data is null or empty ?<br />
For examile </p>
<pre><code>Select Name,Age from MEMBERS
</code></pre>
<p>We need a check Name should not equal to null or empty.</p>
|
<p>This will work in all sane databases (<em>wink, wink</em>) and will return the rows for which name is not null nor empty</p>
<pre><code>select name,age from members where name is not null and name <> ''
</code></pre>
|
I need help: .NET Sample code to read file file properties like title and summary <p>I need help: .NET Sample code to read file file properties like title and summary in .NET</p>
|
<p>If I understand your question correctly, you need <a href="http://stackoverflow.com/questions/220097/readwrite-extended-file-properties-c">this post</a>. </p>
|
I need some help in Undo function in Java <p>I write a Text Editor with Java , and I want to add Undo function to it </p>
<p>but without UndoManager Class , I need to use a Data Structure like Stack or LinkedList but the Stack class in Java use Object parameters e.g : push(Object o) , Not Push(String s)
I need some hints or links .
Thanks</p>
|
<p>Assuming you are using Java 5, Stack is a generic class. You can instantiate it according to the objects it should hold.</p>
<p>You can then use:</p>
<pre><code>Stack<String> stack = new Stack<String>();
String string = "someString";
stack.push(string);
</code></pre>
<p>Also note that in the case you are using Java 1.4 or below, you can still push String objects into the stack. Only that you will need to explicitly downcast them when you pop() them out, like so:</p>
<pre><code>Stack stack = new Stack();
String string = "someString";
stack.push(string);
String popString = (String) stack.pop(); // pop() returns an Object which needs to be downcasted
</code></pre>
|
Aspect-oriented programming in Java <p>What is the best tool for Java for aspect-oriented programming? </p>
<p>The requirements for a tool are of course IDE support, expressiveness and proper documentation.</p>
|
<p>JBossAOP and AspectJ are two commonly used, mature frameworks for AOP. Another popular choice is Spring AOP, but it lacks some of the features of the other two.</p>
<p>Both JBossAOP and AspectJ have similar features, one big difference being that AspectJ relies on extensions to the Java language, whereas JBoss AOP does not. </p>
<p>If your AOP requirements are fairly simple, it's also worth considering a byte-code manipulation library, such as <a href="http://asm.objectweb.org/" rel="nofollow">ASM</a>. I've used ASM to implement simple 'around-advice' (ie, code that is injected before and after method invocations), and it proved to be a more lightweight alternative to JBossAOP. ASM is cleanly-designed and well-documented. </p>
|
binary .dat file <p>how can access the binary data file(.DAT). i am using geonames API. can anyone help me? </p>
|
<p>If you are referring to the binary flat file format used by MaxMinds GeoLocation database, they offer some handy utility classes in C# and Java to access it.</p>
<p><a href="http://www.maxmind.com/app/api" rel="nofollow">http://www.maxmind.com/app/api</a></p>
|
Wanted : review of collection libraries features / issues / performance <p>I know there are couple 3rd party collection libraries out there (C5, PowerCollections and I guess loads more of other not so complete libraries) as well as the System.Collections.Generics classes. I am however quite unsure which library use to when. I have tried the C5 collections, but some sources claim that they are slower then the default collections.</p>
<p>Which libraries do you use and why ? Do you ever wander away from the defaults (there are some collections types that are not supported - so sometimes it may be neccessary).</p>
<p>Do you know of any links for such 3rd party libraries reviews ?</p>
<p>Basically I am looking for anything that could shed some light figuring out what collections libraries to use when.</p>
<p>PS: I am not looking for explanations of when to use linked list and when to use a dictionary. I am looking for choices in the world of collection Libraries.</p>
|
<p>I think the choice of library depends on your need for a particular type of collection. Just because one library has a great linked list, doesn't mean it has an awesome dictionary. </p>
<p>But, having that said, I have generally found PowerCollections to work as my starting collection library of choice because they work similar to how the built in collections work. I love looking through C5's source code though, they offer more abstraction and interesting algorithms. </p>
|
What is the Constant Value of the Underline font in Java? <p>What is the Constant Value of the Underline font in Java ?</p>
<p>Font.BOLD <strong>bold</strong> font</p>
<p>Font.ITALIC <em>italic</em> font</p>
<p>What is the UNDERLINE font Constant ?
I try all the available constants but it didn't work .</p>
|
<p>Looking at the <a href="http://java.sun.com/javase/6/docs/api/">Java API Specification</a>, it appears that the <a href="http://java.sun.com/javase/6/docs/api/java/awt/Font.html"><code>Font</code> class</a> does not have a constant for underlining.</p>
<p>However, using the <a href="http://java.sun.com/javase/6/docs/api/java/awt/Font.html#Font(java.util.Map)"><code>Font(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)</code></a> constructor, one can give it a <code>Map</code> containing the <a href="http://java.sun.com/javase/6/docs/api/java/awt/font/TextAttribute.html"><code>TextAttribute</code></a> and the value to use, in order to specify the font attributes. (Note that the <code>TextAttribute</code> class is a subclass of <code>AttributedCharacterIterator.Attribute</code>)</p>
<p><a href="http://java.sun.com/javase/6/docs/api/java/awt/font/TextAttribute.html#UNDERLINE"><code>TextAttribute.UNDERLINE</code></a> seems like the <code>TextAttribute</code> of interest.</p>
<p><strong>Edit:</strong> There's an example of using <code>TextAttribute</code> in the <a href="http://java.sun.com/docs/books/tutorial/2d/text/textattributes.html">Using Text Attributes to Style Text</a> section from <a href="http://java.sun.com/docs/books/tutorial/index.html">The Java Tutorials</a>.</p>
|
What are areas where you can program artificial intelligence? <p>Welcome!
I very enjoyed programming artificial intelligence in my studies - neural networks, expert machines and other. But in work I develop mainly web applications. </p>
<p>And now I think about returning to such programming, maybe in hobby, or maybe in work. Are there areas where AI is commonly used in applications development and programmer with such skills can search work?</p>
<p>Or maybe I can sold some ideas to my boss and use AI to extend some of our applications. </p>
<p>What are you experience and ideas with using AI in applications?</p>
|
<p>I recently started reading the book <a href="http://rads.stackoverflow.com/amzn/click/0596529325" rel="nofollow">Programming Collective Intelligence</a>. It's an excellent book which discusses exactly what you are looking for - using AI techniques in web applications.</p>
<p>The book is written clearly, is easy to understand, explains everything in terms of real applications (it covers how some commonly used technology works: Google Pagerank, Amazons recommendation system, matchmaking websites, link recommendation systems, bayesian spam filters and more) and it uses actually useful examples using real data (ebay API, facebook API etc are used to collect data). In one chapter, it even explains how you can draw graphs (I mean the data structure, not bar/line/etc graphs) optimally (so that no nodes are too close together, minimum overlapping lines etc), which could be useful for, for example, mapping social networks.</p>
<p>I would recommend having a look at it and see the different ways AI can be applied to web applications.</p>
|
How do I Insert or Update (or overwrite) a record using NHibernate? <p>I need to write a row to the database regardless of whether it already exists or not. Before using NHibernate this was done with a stored procedure. The procedure would attempt an update and if no rows were modified it would fallback to an insert. This worked well because the application doesn't care if the record exists.</p>
<p>With NHibernate, the solutions I have found require loading the entity and modifying it, or deleting the entity so the new one can be inserted. The application does have to care if the record already exists. Is there a way around that?</p>
<h2>Does the Id Matter?</h2>
<h3>Assigned Id</h3>
<p>The object has a keyword as an assigned id and is the primary key in the table.</p>
<p>I understand that SaveOrUpdate() will call the Save() or Update() method as appropriate based on the Id. Using an assigned id, this won't work because the id isn't an unsaved-value. However a Version or Timestamp field could be used as an indicator instead. In reality, this isn't relevant because this only reflects on whether the object in memory has been associated with a record in the database; it does not indicate if the record exists or not in the database.</p>
<h3>Generated Id</h3>
<p>If the assigned id were truly the cause of the problem, I could use a generated id instead of the keyword as the primary key. This would avoid the NHibernate Insert/Update issue as it would effectively always insert. However, I still need to prevent duplicate keywords. With a unique index on the keyword column it will still throw an exception for a duplicate keyword even if the primary key is different.</p>
<h2>Another Approach?</h2>
<p>Perhaps the problem isn't really with NHibernate, but the way this is modeled. Unlike other areas of the application, this is more data-centric rather object-centric. It is nice that NHibernate makes it easy to read/write and eliminates the stored procedures. But the desire to simply write without regard to existing values doesn't fit well with the model of an object's identity model. Is there a better way to approach this?</p>
|
<p>I`m using </p>
<pre><code> public IList<T> GetByExample<T>(T exampleInstance)
{
return _session.CreateCriteria(typeof(T))
.Add(Example.Create(exampleInstance))
.List<T>();
}
public void InsertOrUpdate<T>(T target)
{
ITransaction transaction = _session.BeginTransaction();
try
{
var res=GetByExample<T>(target);
if( res!=null && res.Count>0 )
_session.SaveOrUpdate(target);
else
_session.Save(target);
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
finally
{
transaction.Dispose();
}
}
</code></pre>
<p>but FindByExample method returns all objects alike not objects with the exact ID what do you suggest ? since I have only object as parameter I don't have access to its specific ID field so I cannot use <code>session.get(Object.class(), id);
</code></p>
|
How to use library org.hibernate in java? <p>I create new project in Netbeans, but when I look the library it still using JDK 1.6 (default) I want to change into JDK 6 Update 10 but how? I already instal JDK 6 Update 10 but when I import org.hibernate the neatbeans didn't know which library that org.hibernate.</p>
<p>someone can help me? THX</p>
|
<p>In Netbeans you can define a new Java Platform from Tools > Java Platforms. This brings up the platform manager. At this point you can click the "Add Platform" button and browse to the location of the new platform. You will then have multiple platforms set up and you can configure each project to use the appropriate platform.</p>
<p>To add the hibernate library you can go to Tools > libraries and click "New Library". Then browse to the location of the Hibernate jar files.</p>
<p>Each project can then have th enew library added by right-clicking on the libraries link in the project browser and clicking "Add Library".</p>
|
variable.ToString() vs. Convert.ToString(variable) <p>Let's say I have an integer that I need to convert to a string (I might be displaying the value to the user by means of a TextBox, for example.</p>
<p>Should I prefer <code>.ToString()</code> or <code>Convert.ToString()</code>. They both do the same thing (don't they?).</p>
<pre><code>int someValue = 4;
// You can do this
txtSomeValue.Text = someValue.ToString();
// Or this...
txtSomeValue.Text = Convert.ToString(someValue);
</code></pre>
<p>Assuming that there is no runtime difference between the two, then my reasons come down to aesthetics and consistency. Recently I have been favouring <code>Convert.ToString()</code> as to me it says "hey, I want the <em>value</em> of this thing as a string". However I know that this is not strictly true...</p>
|
<p>One test is </p>
<pre><code>//This will set the variable test to null:
string test = Convert.ToString(ConfigurationSettings.AppSettings["Missing.Value"]);
//This will throw an exception:
string test = ConfigurationSettings.AppSettings["Missing.Value"].ToString();
</code></pre>
<p>Got the above ready example from <a href="http://weblogs.asp.net/jgalloway/archive/2003/11/06/36308.aspx" rel="nofollow">http://weblogs.asp.net/jgalloway/archive/2003/11/06/36308.aspx</a></p>
<p>You can find some benchmarks between the two at
<a href="http://blogs.msdn.com/brada/archive/2005/03/10/392332.aspx" rel="nofollow">http://blogs.msdn.com/brada/archive/2005/03/10/392332.aspx</a></p>
<p>So, it depends what you prefer and what your style is.</p>
|
Flex intellisense forgets flash.* <p>I am using Eclipse 3.3.2 with the Flex Builder Plugin (3.0.194161) and the Flex SDK 3.2. Recently the intellisense has started forgetting about everything in the flash.* package EXCEPT flash.errors.*</p>
<p>The code still compiles, but attempting to automatically resolve something (CTRL+SPACE) removes any of the flash.* import statements and thus causes a compile error. As it stands I have to either not use CTRL+SPACE, or re-add my flash.* before compiling.</p>
<p>I have tried recreating the workspace/project and have re-installed the Flex SDK, but I still get the same problem.</p>
<p>Any thoughts?</p>
|
<p>I was able to work around the problem by adding the following SWC to my library path: FLEX_SDK\libs\player\10\playerglobal.swc</p>
<p>It looks like the problem is caused by {targetPlayerMajorVersion} no longer resolving, though I have no idea how that happened.</p>
<p><strong>Edit:</strong> Known bug, as described in <a href="http://bugs.adobe.com/jira/browse/FB-16703" rel="nofollow">FB-16703</a> and <a href="http://opensource.adobe.com/wiki/display/flexsdk/Targeting+Flash+Player+10" rel="nofollow">"Targeting Flash Player 10"</a></p>
|
BlogEngine.Net Code Formatting Extension that works? <p>For months now I've been trying to find a code syntax formatting extension that works for BlogEngine.Net. I'm not fond of the behavior of the default formatting extension, and have tried a couple of others (manoli is among them), but they always seem to interact badly with the TinyMCE editor. Does anyone know of an extension that works, or a different approach that will allow me to make code samples pretty on my blog without hacking the crap out of the HTML myself?</p>
<p>Thanks.</p>
|
<p>I would try using Windows Live Writer along w/ the Paste From Visual Studio plugin. One you go WLW, you'll never go back to that damn TinyMCE interface.</p>
<p>WLW here:
<a href="http://get.live.com/writer/overview" rel="nofollow">http://get.live.com/writer/overview</a></p>
<p>Plugin here:
<a href="http://gallery.live.com/liveItemDetail.aspx?li=d8835a5e-28da-4242-82eb-e1a006b083b9&l=8" rel="nofollow">http://gallery.live.com/liveItemDetail.aspx?li=d8835a5e-28da-4242-82eb-e1a006b083b9&l=8</a></p>
|
Simple role authentication in asp.net <p>I want to do a simple role authentication in .NET - but am lost in the profusion of apis...</p>
<p>I would like to have a web.config per directory with role access like:</p>
<pre><code><authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>
</code></pre>
<p>And in my login page, where I do FormsAuthentication.RedirectFromLoginPage I want to specify the role of the logged in user (admin, user, etc...)
I have no need for the RoleManagementProviders and the overkilled feature (in my case) of RoleManagement. </p>
<p>What API do I need to user to just specify the role of a user?</p>
<p>Thanks</p>
|
<p>Here is a link on a very simple Forms Authentication implementation with roles. I believe this is the most basic Forms Authentication implementation:
<a href="http://www.codeproject.com/KB/web-security/formsroleauth.aspx">http://www.codeproject.com/KB/web-security/formsroleauth.aspx</a></p>
<p>Here is one on the membership provider:
<a href="http://www.asp.net/learn/moving-to-asp.net-2.0/module-08.aspx">http://www.asp.net/learn/moving-to-asp.net-2.0/module-08.aspx</a>
You might have to search for additional tutorials to get a clear idea on how to customize it.</p>
<p>I prefer the membership provider because it allows you to override the defaults and supply your own datastore and methods used for the different authentication actions. I find it to be easier than using the basic implementation.</p>
|
How do I create a Java string from the contents of a file? <p>I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited.</p>
<p>Is there a better/different way to read a file into a string in Java?</p>
<pre><code>private String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try {
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
} finally {
reader.close();
}
}
</code></pre>
|
<h2>Read all text from a file</h2>
<p>Here's a compact, robust idiom for Java 7, wrapped up in a utility method:</p>
<pre><code>static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
</code></pre>
<h2>Read lines of text from a file</h2>
<p>Java 7 added a <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29">convenience method to read a file as lines of text,</a> represented as a <code>List<String></code>. This approach is "lossy" because the line separators are stripped from the end of each line.</p>
<pre><code>List<String> lines = Files.readAllLines(Paths.get(path), encoding);
</code></pre>
<h2>Memory utilization</h2>
<p>The first method, that preserves line breaks, can temporarily require memory several times the size of the file, because for a short time the raw file contents (a byte array), and the decoded characters (each of which is 16 bits even if encoded as 8 bits in the file) reside in memory at once. It is safest to apply to files that you know to be small relative to the available memory.</p>
<p>The second method, reading lines, is usually more memory efficient, because the input byte buffer for decoding doesn't need to contain the entire file. However, it's still not suitable for files that are very large relative to available memory.</p>
<p>For reading large files, you need a different design for your program, one that reads a chunk of text from a stream, processes it, and then moves on to the next, reusing the same fixed-sized memory block. Here, "large" depends on the computer specs. Nowadays, this threshold might be many gigabytes of RAM.</p>
<h2>Character encoding</h2>
<p>One thing that is missing from the sample in the original post is the character encoding. There are some special cases where the platform default is what you want, but they are rare, and you should be able justify your choice.</p>
<p>The <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html"><code>StandardCharsets</code></a> class define some constants for the encodings required of all Java runtimes:</p>
<pre><code>String content = readFile("test.txt", StandardCharsets.UTF_8);
</code></pre>
<p>The platform default is available from <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html#defaultCharset%28%29">the <code>Charset</code> class</a> itself:</p>
<pre><code>String content = readFile("test.txt", Charset.defaultCharset());
</code></pre>
<hr>
<p>Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.</p>
|
Unit testing with Entity Framework <p>I want to test my Entities that are built using Entity Framework.
My concern is that using Entity Framework means directly working with data source.
So any ideas how to unit testing Entity Framework based components?</p>
|
<p>For Enity Framework 4, this looks promising: <a href="http://msdn.microsoft.com/en-us/ff714955.aspx">Testability and Entity Framework 4.0</a></p>
|
Register Startup Script Control <p>I am looking to make a web control where I can register client startup scripts inline with my aspx because I hate registering in the codebehind!</p>
<p>An example of what I have so far:</p>
<p><Ben:StartupScript runat="server"></p>
<p>var form = document.getElementById("<% =form1.ClientID %>");</p>
<p></Ben:StartupScript></p>
<p>Currently, I am overriding the OnPreRender method of the control, rendering the contents of the control to a string and then manually registering that string as a startup script using ClientScript.RegisterStartupScript on the Page. I also override the Render method in order not to render the control. I should also note that I have the ParseChildren attribute set to false and the PersistChildren attribute set to true.</p>
<p>All seems to be working well, but my control allows other web controls inside it (such as Button). Apart from being unintuitive, this can result in runtime errors. I would love to be able to clear the controls but this is impossible given the <% ... %> code block.</p>
<p>So, is it possible to prevent developers from embedding child controls whilst still allowing codeblocks?</p>
<p>Also, is this idea any good or is it fundamentally flawed? lol.</p>
<p>Thanks a bunch,</p>
<p>Ben</p>
|
<p>it sounds like a good idea, but if you spend too much time fighting the inherited/default behaviors then it may be more trouble than it's worth</p>
<p>if this is a one-shot issue, a cheap-hack solution is to just directly embed your scripts in the header of a master page ;-)</p>
<p>on the other hand, allowing developers to embed their own scripts as children of your web control might be useful</p>
|
Navigation, background swap not having every <li> on mouseover <p>I am using the following jquery code:</p>
<pre><code>$("#top ul li.corner").mouseover(function(){
$("span.left-corner").addClass("left-corner-hover");
$("span.right-corner").addClass("right-corner-hover");
$("span.content").addClass("content-hover");
}).mouseout(function(){
$("span.left-corner").removeClass("left-corner-hover");
$("span.right-corner").removeClass("right-corner-hover");
$("span.content").removeClass("content-hover");
});
</code></pre>
<p>But as you see in the selector that is going to do every li.corner that the mouse is over. i am trying to get it to do only the one the mouse is over, how would I achieve that?</p>
|
<p>are your <code><span></code> elements within your <code><li></code>? if so you could do something like:</p>
<pre><code>$('#top ul li.corner').mouseover(function() {
$('span.left-corner', this).addClass('left-corner-hover');
// etc...
}).mouseout(function() {
$('span.left-corner', this).removeClass('left-corner-hover');
// etc...
});
</code></pre>
<p>basically, this would assign/remove the classes to the specific <code><span></code> elements within the <code><li></code> called.</p>
<p>depending on how much stuff is in there, you may get better results using <code>mouseenter</code> and <code>mouseleave</code>, to avoid triggering mouseover when you cross element boundaries:</p>
<pre><code>$('#top ul li.corner').bind('mouseenter', function() {
// etc...
}).bind('mouseleave', function() {
// etc...
});
</code></pre>
|
How can I control/override the auto-complete in my iPhone app? <p>I want to control/override the auto-complete feature when a user enters text in my iPhone app.</p>
<p>Specifically I'd like to auto-complete a collection of words I supply. For example say my name is BillBobJohn. When I type "billb" auto-complete will suggest BillBobJohn.</p>
<p>How can I do this?</p>
|
<p>This is discussed here: <a href="http://forums.macrumors.com/showthread.php?t=573894" rel="nofollow">http://forums.macrumors.com/showthread.php?t=573894</a></p>
|
Vertically align text within input field of fixed-height without display: table or padding? <p>The line-height property usually takes care of vertical alignment, but not with inputs. Is there a way to automatically center text without playing around with padding?</p>
|
<p>I ran into this problem myself. I found that not specifying an input height, but using the font-height and padding combined, results in vertically aligned text.</p>
<p>For instance, lets say you want to have a 42px tall input box, with a font-size of 20px. You could simply find the difference between the input height and the font-size, divide it by two, and set your padding to that amount. In this case, you would have 22px total worth of padding, which is 11px on each side.</p>
<pre><code><input type="text" style="padding: 11px 0px 11px 0px; font-size: 20px;" />
</code></pre>
<p>That would give you a 42px tall input box with perfect vertical alignment.</p>
<p>Hope that helps.</p>
|
Is There An OSS Implementation Of Google AdWords <p>Is there an open source implementation of Google AdWords, or is the technology protected in some way (such as being patented)?</p>
<p>Edit: To clarify, I'm looking for a 3rd party implementation of an AdWords-like system (that has nothing to to with Google AdWords beyond the concept and superficial similarity).</p>
|
<p>Depending on what part of the system you are looking to replicate you should give <a href="http://www.openx.org/" rel="nofollow">OpenX ad server</a> a try. You can install it on your own servers or use their hosted version. There are other open source ad servers but this one seems to work pretty well.</p>
|
Blogs to freshen up my math (in practice) <p>My question, <a href="http://stackoverflow.com/questions/11743/useful-math-for-programmers">his question</a>, but blogs as resources to be specific.</p>
<p>I find blogs great to keep up to date... refresh material...</p>
<p>So do you know any blogs who tackle math-related programming problems...</p>
|
<p>Not exactly what you're asking for, but <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> freshens up <em>my</em> math skills.</p>
|
How can I dynamically get the set of classes from the current python module? <p>I have a python module that defines a number of classes:</p>
<pre><code>class A(object):
def __call__(self):
print "ran a"
class B(object):
def __call__(self):
print "ran b"
class C(object):
def __call__(self):
print "ran c"
</code></pre>
<p>From within the module, how might I add an attribute that gives me all of the classes?</p>
<p>dir() gives me the names of everything from within my module, but I can't seem to figure out how to go from the name of a class to the class itself from <em>within</em> the module.</p>
<p>From outside of the module, I can simply use <code>getattr(mod, 'A')</code>, but I don't have a <code>self</code> kind of module from within the module itself.</p>
<p>This seems pretty obvious. Can someone tell me what I'm missing?</p>
|
<pre><code>import sys
getattr(sys.modules[__name__], 'A')
</code></pre>
|
Methods and Anonymous Types <p>I know that you cannot return anonymous types from methods but I am wondering how the Select extension method returns an anonymous type. Is it just a compiler trick?</p>
<p>Edit</p>
<p>Suppose L is a List. How does this work?</p>
<pre><code>L.Select(s => new { Name = s })
</code></pre>
<p>The return type is IEnumerable<'a> where 'a = new {String Name}</p>
|
<p>Well, it's normal type inference for generic method type arguments. For instance:</p>
<pre><code>List<string> x = new List<string>();
// The compiler converts this:
x.Select(y => y.Length);
// Into this, using type inference:
Enumerable.Select<string, int>(x, y => y.Length);
</code></pre>
<p>The same would be true if <code>x</code> were a list of some anonymous type, or if the inferred return type of the lambda expression were an anonymous type. Don't forget that even though you can't explicitly state the type of a variable which uses an anonymous type, it still does <em>have</em> a definite type, known to the compiler.</p>
|
What are the best practices for Hardware Description Languages (Verilog, VHDL etc.) <p>What best practices should be observed when implementing HDL code?</p>
<p>What are the commonalities and differences when compared to more common software development fields?</p>
|
<p>Sort of an old thread, but wanted to put in my $0.02. This isn't really specific to Verilog/VHDL.. more on hardware design in general... specifically synthesizable design for custom ASICs. </p>
<p>This is my <em>opinion</em> based on years of industry (as opposed to academic) experience on design. They are in no particular order </p>
<p>My umbrella statement is to Design for validation execution. In hardware design, validation is paramount. Bugs are a lot more expensive when found in actual silicon. You can't just re-compile. Therefore, pre-silicon is given much more focus. </p>
<ul>
<li><p>Know the difference between control paths and data paths. This enables you to create much more elegant and maintainable code. Also allows you to save gates and minimize X propagation. For instance, data paths should never need resettable flops, control paths should always need it.</p></li>
<li><p>Prove functionality before validation. Either through a formal approach or through waveforms. This has many advantages, I will explain 2. First, it will save you wasted time onion peeling through issues. Unlike lots of application level design (esp while learning) and most course work, the turn-around time for code changes is very large (anywhere from 10 minutes to days, depending on complexity). Every time you change code, you need to go through elaboration, lint checking, compiling, waveform bring-up, and finally actual simulation.. which can itself take hours. Second, you are much less likely to have difficult to hit corner cases. Note this is with respect to pre-silicon validation. These will surely hit at post-silicon costing you lots of $$$. Trust me, the up front cost of proving functionality greatly minimizes risk and is well worth the effort. This is sometimes difficult to convince recent college grads.</p></li>
<li><p>Have "chicken bits". Chicken bits are bits in MMIO set via the driver to disable a feature in silicon. It's intended to revert changes made in which confidence is not high (confidence is directly proportional to validation efforts). It is next to impossible to hit every possible state in pre-silicon. Confidence on your design cannot truly be met until it's proven in post-silicon. Even if there is only 1 state that is hit 0.000005% of the time that exposes the bug, it WILL HIT in post-silicon, but not necessarily in pre-silicon.</p></li>
<li><p>Avoid exceptions in the control path at all costs. Every new exception you have doubles your validation efforts. This one is hard to explain. Lets say there is a DMA block that will save out data to memory that another block will use. Lets say the data structure saved out is dependent on some function being done. If you decided to design such that the data structure saved was different between different functions, you just multiplied your validation efforts by the number of DMA functions. If this rule is followed, the data structure saved out would be a super-set of all data available for every function where the content locations are hardcoded. Once the DMA save logic is validated for 1 function its validated for all functions.</p></li>
<li><p>Minimize interfaces (read minimize control paths). This is related to minimizing exceptions. First, every new interface requires validation. This includes new checkers/trackers, assertions, coverage points, and bus functional models in your testbench. Secondly, it can increase your validation efforts exponentially! Lets say you have 1 interface for reading data in caches. Now lets say (for some odd reason) you decide you want another interface for reading main memory. You just quadrupled your validation efforts. You now need to validate these combinations at any given time <em>n</em>:</p>
<ul>
<li>no cache read, no memory read</li>
<li>no cache read, memory read</li>
<li>cache read, no memory read</li>
<li>cache read, memory read</li>
</ul></li>
<li><p>Understand and communicate assumptions. Lacking this is the main reason for block to block communication issues. You could have a perfect block fully validated.. however, without understanding all assumptions, your block will fail when its connected.</p></li>
<li><p>Minimize potential states. The less states (intended or unintended) a design has, the less effort required to validate. It's good practice to group like functions into 1 top level function (like sequencers and arbiters). It is very difficult to identify and define this high level function such that it encompasses as many smaller functions as possible, but in doing so you vastly eliminate state and in turn potential for bugs.</p></li>
<li><p>Always provide a strong signal leaving your block. Most of the time flopping it is the solution. You have no idea what the endpoint block(s) will do with it. You could run into timing issues which can have a direct impact on your perfect implementation.</p></li>
<li><p>Avoid mealy type FSMs unless performance is negatively impacted. Mealy FSMs are more likely to produce timing issues over Moore</p></li>
<li><p>.. and finally the one I dislike the most: "if it ain't broke, don't fix it" Because of the risk involved and the high cost of bugs, many times hacking is a more practical solution to solving problems. Others have eluded to this by mentioning utilization of existing components.</p></li>
</ul>
<p>As for comparing against more <em>traditional</em> software design:</p>
<ul>
<li><p>discrete event driven programming is a completely different paradigm. People see verilog syntax and think "oh, its just like C"... however, this cannot be further from the truth. Although the syntax is similar, one must think differently. For example, a traditional debugger is virtually meaningless on synthesizable RTL (Testbench design is different). Waveforms on paper are the best tool available. However, that being said, FSM design can at times mimic procedural programming. People with a software background tend to go crazy with FSMs (I know I did at first).</p></li>
<li><p>System Verilog has lots and lots (and lots) of testbench specific features. It is completely object oriented. As far as testbench design goes, its very similar to traditional software design. However, it does have 1 more dimension associated with it, that of time. race conditions and protocol delays must be accounted for</p></li>
<li><p>As for validation, it is also different (and the same). There are 3 main approaches; </p>
<ul>
<li>Formal propagative verification (FPV): You prove through logic that it will always work</li>
<li>Directed random testing. Randomly set delays, input values, and feature enabling as defined by a seed. <em>directed</em> means that the seed puts weight on paths that have less confidence. This approach uses coverage points to indicate health</li>
<li>Focus testing. This is similar to traditional software testing </li>
</ul></li>
</ul>
<p>... for completeness, I need to also discuss best test-bench design practices... but that's for another day</p>
<p>Sorry for the length.. I was in "The Zone" :)</p>
|
Running unit tests on nested functions <p>I come from the Java world, where you can hide variables and functions and then run unit tests against them using reflection. I have used nested functions to hide implementation details of my classes so that only the public API is visible. I am trying to write unit tests against these nested functions to make sure that I don't break them as I develop. I have tried calling one of the nested functions like:</p>
<pre><code>def outer():
def inner():
pass
outer.inner()
</code></pre>
<p>which results in the error message:</p>
<blockquote>
<p>AttributeError: 'function' object has no attribute 'inner'</p>
</blockquote>
<p>Is there a way for me to write unit tests against these nested functions? If not, is there a way to trigger the name munging for function names like you can for class variables by prefixing them with __?</p>
|
<p>inner doesn't exist until outer makes it. You should either move inner up to a toplevel function for testability, or have the outer test test all the possible execution paths of itself and inner.</p>
<p>Do note that the inner function isn't a simple function, it's a closure. Consider this case:</p>
<pre><code>def outer(a):
b = compute_something_from(a)
def inner():
do_something_with(a, b)
</code></pre>
<p>That's the standard testability trade-off. If your <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity">cyclomatic complexity</a> is too high, your tests will be too numerous.</p>
|
Can I atomically rename/replace 2 or more tables and views? <p>Given a table X and a view Y (that has the same structure as X) is there a way to rename X to Z and Y to X atomically so that no query will ever see nothing named X? Renaming X and creating the view would also be valid.</p>
<p>The point would be to, as part of a schema migration plan, replace the old tables with views that simulate the old version from the new version so both sets of client code can run at the same time.</p>
<p>MySQL is my choice but info on others would be useful as well.</p>
|
<p>This is trivial in postgres and impossible in mysql.</p>
<p>mysql exempts schema modifications from transactions. I have a postgres background, so that's an obvious thing to do (begin a transaction, do some stuff, commit or rollback -- postgres isn't picky about what "do some stuff" is).</p>
<p>You can find a few bugs on this if you look through mysql's bug base.</p>
|
Comparing 2 XML docs and applying the changes to source document <p>Here's my problem.I have 2 xmlfiles with identical structure, with the second xml containing only few node compared to first.</p>
<p>File1</p>
<pre><code> <root>
<alpha>111</alpha>
<beta>22</beta>
<gamma></gamma>
<delta></delta>
</root>
</code></pre>
<p><strong>File2</strong></p>
<pre><code> <root>
<beta>XX</beta>
<delta>XX</delta>
</root>
</code></pre>
<p>This's what the result should look like </p>
<pre><code> <root>
<alpha>111</alpha>
<beta>22</beta>
<gamma></gamma>
<delta>XX</delta>
</root>
</code></pre>
<p>Basically if the node contents of any node in File1 is blank then it should read the values from File2(if it exists, that is).</p>
<p>I did try my luck with Microsoft XmlDiff API but it didn't work out for me(the patch process didn't apply changes to the source doc). Also I'm a bit worried about the DOM approach that it uses, because of the size of the xml that I'll be dealing with.
Can you please suggest a good way of doing this.
I'm using C# 2 </p>
|
<p>In XSLT you can use the <code>document()</code> function to retrieve nodes from File2 if you encounter an empty node in File1. Something like:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="root/*[.='']">
<xsl:variable name="file2node">
<xsl:copy-of select="document('File2.xml')/root/*[name()=name(current())]"/>
</xsl:variable>
<xsl:choose>
<xsl:when test="$file2node != ''">
<xsl:copy-of select="$file2node"/>
</xsl:when>
<xsl:otherwise>
<xsl:copy/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
</code></pre>
|
using a vector of column names, to generate a sql statement <p>A problem that we need to solve regularly at my workplace is how to build sql statements based on user supplied table/column names. The issue I am trying to address is the commas between column names. </p>
<p>One technique looks something like this.</p>
<pre><code>selectSql = "SELECT ";
for (z = 0; z < columns.size(); z++)
{
selectSql += columns[z]._name;
selectSql += ", ";
}
selectSql = selectSql(0, selectSql.len() - 2);
selectSql += "FROM some-table";
</code></pre>
<p>Another technique looks something like this</p>
<pre><code>selectSql = "SELECT ";
for (z = 0; z < columns.size(); z++)
{
selectSql += columns[z]._name;
if (z < columns.size() - 1)
selectSql += ", ";
}
selectSql += "FROM some-table";
</code></pre>
<p>I am not particularly enthralled by either of these implementations.</p>
<p>I am interesting in hearing ideas for other ways to address this issue, with an eye toward making the code easier to read/understand/maintain.</p>
<p>What alternate techniques are available?</p>
|
<p>In your case it is probably safe to assume that there is at least one column since otherwise there is no point in doing the select. In that case you could do:</p>
<pre><code>selectSql = "SELECT ";
selectSql += columns[0]._name;
for (z = 1; z < columns.size(); z++) {
selectSql += ", ";
selectSql += columns[z]._name;
}
selectSql += " FROM some-table";
</code></pre>
|
Cruisecontrol.NET & IIS7 Static File Handler Problem <p>I'm trying to get Cruisecontrol.NET running with Server 2008/IIS7 and when I try and navigate to the dashboard I get the following error:
HTTP Error 404.17 - Not Found
The requested content appears to be script and will not be served by the static file handler.</p>
<p>I'm a bit lost in IIS7 so it could be something pretty straightforward. They (cc.net) do some funny stuff with http handlers in the web.config which may be related to the problem:</p>
<p>
</p>
<p>Anyone have any pointers?</p>
|
<p>Is the dashboard set up as an application in IIS?</p>
<p>I've not used IIS7, but I know in IIS6 you need to enable an application and assign it to an app pool before you can run ASPX code.</p>
<p><strong>EDIT:</strong> This works in IIS6.</p>
<p>Open the IISAdmin tool on the web server. Expand the web sites folder. Find the virtual directory (directories?) for CruiseControl. Right-click on it and look at properties. On the directory tab, create a new application and give it a suitable name. Enable the application to execute "scripts only". Assign it to an application pool (you may want to create a new one just for this application -- consult the help documentation for this). You may also need to change the ASP.NET version You can do this on the ASP.NET tab -- choose either v1.1 or v2.0, whichever CruiseControl requires.</p>
|
Dynamic logical expression parsing/evaluation in PHP? <p>I have a need to evaluate user-defined logical expressions of arbitrary complexity on some PHP pages. Assuming that form fields are the primary variables, it would need to:</p>
<ul>
<li>substitute"varibles" for form
fields values;</li>
<li>handle comparison operators,
minimally ==, <, <=, >= and > by
symbol, name (eg eq, lt, le, ge, gt
respectively);</li>
<li>handle boolean operators not, and, or and
possibly xor by name, symbol (eg !,
&&, || and ^^ respectively);</li>
<li>handle literal values for strings
and numbers;</li>
<li>be plaintext not XML (eg "firstname
== '' or lastname == ''); and</li>
<li>be reasonably performant.</li>
</ul>
<p>Now in years gone by I've written recursive descent parsers that could build an expression tree and do this kind of thing but thats not a task I'm relishing in PHP so I'm hoping there are things out there that will at least get me some of the way there.</p>
<p>Suggestions?</p>
|
<p>Much time has gone by since this question was asked, and I happened to be looking for an expression parser for php. I chose to use the <a href="http://symfony.com/blog/new-in-symfony-2-4-the-expressionlanguage-component" rel="nofollow">ExpressionLanguage</a> component from Symfony 2.4. It can be installed with no dependencies from composer via <a href="https://packagist.org/packages/symfony/expression-language" rel="nofollow">packagist</a>.</p>
<p><code>composer require symfony/expression-language</code></p>
|
Removing a file in a Restricted Folder in Linux <p>I have been attempting to create a new directory for my apache server. As I tried to access the new directory, I type:</p>
<p>sudo /etc/init.d/apache2 restart</p>
<p>But I obtain this error in the Ubuntu Terminal:</p>
<p>Syntax Error on line 1 of /etc/apache2/conf.d/fqdn.save:
ServerName takes one argument, the Hostname and port of the server.</p>
<p>As I investigate, the fqdn.save file could not be accessed and is considered unknown. I want to delete this file, but I'm unable to as I believe I need root access. </p>
<p>Does anyone know how to delete this unwanted file in Ubuntu? Or does anyone know how to redirect the apache2 restart to /etc/apache2/conf.d/fqdn (instead of fqdn.save) when I type "sudo /etc/init.d/apache restart" on the terminal</p>
<p>please and thank you</p>
|
<p>You've got sudo; I'm going to assume that's the standard Ubuntu "blanket" sudo that lets you do anything.</p>
<p>Check out what's in the file by doing:</p>
<pre><code>sudo cat /etc/apache2/conf.d/fqdn.save
</code></pre>
<p>Make a backup of the file, just in case:</p>
<pre><code>sudo cp /etc/apache2/conf.d/fqdn.save /tmp
</code></pre>
<p>Remove the file:</p>
<pre><code>sudo rm /etc/apache/conf.d/fqdn.save
</code></pre>
<p>And then at that point you should be able to start the server up...</p>
|
JSCocoa and the iPhone <p>Now I have a stack of free time on my hands, I wanna get into iphone dev fo real.</p>
<p>But Objective C scares me (a bit). It feels I'm going a bit back in time. I say this because I've spent the last 8 months coding in C++.</p>
<p><a href="http://inexdo.com/JSCocoa" rel="nofollow">JSCocoa</a> looks awesome, but does this actually work on the iphone?</p>
<p>What would need to be done to get this working on the iphone?</p>
|
<p>(Hi, I'm the JSCocoa dev)
JSCocoa works on the iPhone simulator. Check out the latest version from Google svn and compile iPhoneTest2. </p>
<p>To work on the iPhone, it needs libffi. I've seen <a href="http://code.google.com/p/iphone-dev/source/browse/trunk/llvm-gcc-4.0-iphone/">http://code.google.com/p/iphone-dev/source/browse/trunk/llvm-gcc-4.0-iphone/</a> and some libffi posts regarding Python for iPhone, but have not tested any further. </p>
<p>Also I don't own an iPhone, so testing will mostly be up to someone who owns one :)</p>
|
How can I make some items in a ListBox bold? <p>In Visual c# Express Edition, is it possible to make some (but not all) items in a ListBox bold? I can't find any sort of option for this in the API.</p>
|
<p>You need to change listbox's DrawMode to DrawMode.OwnerDrawFixed. Check out these articles on msdn:<br />
<a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.drawmode.aspx">DrawMode Enumeration</a><br />
<a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.drawitem.aspx">ListBox.DrawItem Event</a><br />
<a href="http://msdn.microsoft.com/en-us/library/19sb1bw6.aspx">Graphics.DrawString Method</a></p>
<p>Also look at this question on msdn forums:<br />
<a href="http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/dacea8cd-963e-4a40-9af6-1495acf1d3c5/">Question on ListBox items</a></p>
<p>A simple example (both items - Black-Arial-10-Bold):</p>
<pre><code> public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ListBox1.Items.AddRange(new Object[] { "First Item", "Second Item"});
ListBox1.DrawMode = DrawMode.OwnerDrawFixed;
}
private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), new Font("Arial", 10, FontStyle.Bold), Brushes.Black, e.Bounds);
e.DrawFocusRectangle();
}
}
</code></pre>
|
What are some good resources for learning Grails? <p>I am planning to learn Grails. Which is the best book that I should refer for this? Is there any website available on this for beginners?</p>
|
<p>There is good book for beginners <em>The Definitive guide to Grails</em> by Graeme Keith Rocher.</p>
<p><a href="http://rads.stackoverflow.com/amzn/click/1430243775" rel="nofollow">The Definitive Guide to Grails 2</a> is out.</p>
|
logging for web application <p>I'm in the middle of building a pretty big site using asp.net (forms if it's of any interest), and I'm wondering if i need a logging framework such as log4net.
I've used such frameworks before, but i don't see how i could put it to any use in this type of project.
usually i think logging is needed for customer delivered application, where the log could be sent back and then analyzed for errors.
what do you think?</p>
|
<p>Heck no - logging is <em>incredibly</em> important for web applications. If you log appropriately, it makes troubleshooting <em>so</em> much easier.</p>
<p>Log4Net is probably a good bet as a framework. You might also want a way of gathering logs together from multiple servers - and even if you don't use more than one server at the moment, it's probably worth suggesting that you will do so at some point.</p>
<p>One option for the centralisation is to copy the logs into a database - see <a href="http://stackoverflow.com/questions/290304">this question</a> for more opinions on that front.</p>
|
batch file to keep one of ten lines <p>I have a file with n lines. (n above 100 millions)</p>
<p>I want to output a file with only 1 of 10 lines, I can't split the file in ten part and keep only one part, as it must be a little more random. later I have to do a statistical analysis I can't afford to create a strong bias in the data).</p>
<p>I was thinking of reading the file and for each record if the record number mod 10 then output it.</p>
<p>The constraints are:</p>
<ul>
<li><p>it's a windows (likely hardened) computer possibly XP Vista or Windows server 2003.</p></li>
<li><p>no development tools available</p></li>
<li><p>no network,usb,cd-rom. read no external communication.</p></li>
</ul>
<p>Therefore I was thinking of windows batch file (I can't assume powershell, and vbscript is likely to have been removed). And at the moment looking at the FOR /F command.
Still I am not an expert and I don't know how to achieve this.</p>
<p><em>Thank you Paul for your answer.
I reformat (with Hosam help) the answer to put it in a batch file:</em></p>
<pre><code>@echo off
setlocal
findstr/N . inputFile| findstr ^[0-9]*0: >temporaryFile
FOR /F "tokens=1,* delims=: " %%i in (temporaryfile) do echo %%j > outputFile
</code></pre>
<p><em>Thanks quux and Pax for the similar alternative solution. However after a quick test on a larger file Paul's answer is roughly 8 times faster. I guess the evaluation (in SET) is kind of slow, even if the logic seems brilliant.</em></p>
|
<p>Ok, I think I've cracked it:</p>
<pre><code>findstr/N . path-to-log-file | findstr ^[0-9]*0:
</code></pre>
<p>(use findstr to add the line number to the beginning of the line, then again to print only lines with a line number ending in zero)</p>
<p>So you'll get one line in 10, but with the linenumber and colon prepended to each line</p>
<p><strike>If I can think of a way using command-line tools only of stripping that out, I'll edit this answer :)</strike></p>
<p>Remove the line number and colon with</p>
<pre><code>FOR /F "tokens=1,2* delims=: " %i in (file-with-linenumbers) do echo %j
</code></pre>
<p>Paul.</p>
|
SecurityException in ASP.net application <p>I have a web app which queries a Lucene index and it works just fine in a W2K3 server in my network. Now I got my azure code so I wanted to test the service uploading the app. In order to do that I had to install Vista (I did it in a Virtual machine) cause the Azure SDK won't install on an XP box.</p>
<p>I created my Cloud Service, added the files from my app but when I run it (just F5) I get a SecurityException, when I call Lucene to query the index, saying: </p>
<blockquote>
<p>The application attempted to perform
an operation not allowed by the
security policy. To grant this
application the required permission
please contact your system
administrator or change the
application's trust level in the
configuration file.</p>
</blockquote>
<p>I've been googling around and the solutions I've found concern modifying the machine.config file which is something I won't be able to do "in the cloud".</p>
<p>Could anybody help on this?</p>
|
<p>Ok, in case somebody is facing the same issues, this is the correct answer which I got from the Azure forum:</p>
<blockquote>
<p>This is because of the trust policy
for the Windows Azure CTP. The
enviroment variablies TEMP and TMP are
avaliable and set up appropiately.
However, System.IO.Path.GetTempPath
and System.IO.GetTempFile do not work
as they require unrestricted
environment permissions. I would
suggest you contact the Lucene
developers to see if they can modify
the code so it runs properly in medium
trust environments.</p>
</blockquote>
<p>Thanks to Daniel C. Wang for the answer.</p>
|
MySQL stored procedure vs. multiple selects <p>Here's my scenario:</p>
<p>I've got a table of (let's call them) nodes. Primary key on each one is simply "node_id".</p>
<p>I've got a table maintaining a hierarchy of nodes, with only two columns: parent_node_id and child_node_id.</p>
<p>The hierarchy is maintained in a separate table because nodes can have an N:N relationship. That is to say, one node can have multiple children, and multiple parents.</p>
<p>If I start with a node and want to get all of its ancestors (i.e. everything higher up the hierarchy), I could either do several selects, or do it all in one stored procedure.</p>
<p>Anyone with any practical experience with this question know which one is likely to have the best performance? I've read things online that recommend both ways.</p>
|
<p>"which one is likely to have the best performance? " : No one can know ! The only thing you can do is try both and MEASURE. That's sadly enough the main answer to all performance related questions... except in cases where you clearly have a O(n) difference between algorithms.</p>
<p>And, by the way, "multiple parents" does not make a hierarchy (otherwise I would recommend to read some books by Joe Celko) but a DAG (Direct Acyclic Graph) a much harder beast to tame...</p>
|
Calculate time period using C <p>How do I calculate the time period between 2 dates in C (any library, etc.)? </p>
<p>The program should take two (local) dates as input and provide the duration period between them as output. </p>
<p>For example,</p>
<pre><code>startDate = OCT-09-1976 and endDate = OCT-09-2008
should show a duration of 32 years.
startDate = OCT-09-1976 and endDate = DEC-09-2008
should show a duration of 32 years and 2 months.
</code></pre>
<p>Thanks.</p>
|
<p>Convert the dates into two struct tm structures with <a href="http://www.manpagez.com/man/3/strptime/" rel="nofollow">strptime</a></p>
<p><a href="http://www.manpagez.com/man/3/difftime/" rel="nofollow">Difftime</a> gives you the difference between the two in seconds.</p>
<p>Convert that into months etc with the code <a href="http://www.daniweb.com/forums/post121350-7.html" rel="nofollow">here</a> (in C++, but the only C++ is for the string formatting, easy to change)</p>
<p>EDIT: as a commentor observed, that avoids the month issue. There is (GPL'd) code for
isodiff_from_secs that can be converted to do what you want, if you're happy with its assumption that months have 30 days. See <a href="http://www.google.com/codesearch?hl=en&sa=N&q=isodiff_from_secs+lang:c&ct=rr&cs_r=lang:c" rel="nofollow">Google codesearch</a> and the description of the standard <a href="http://en.wikipedia.org/wiki/ISO_8601#Durations" rel="nofollow">here</a></p>
<p>Doing the fully-correct solution which takes acccount of the true months between the actual days would be pretty complex. Is that required for your problem?</p>
|
WMI invalid Class error (trying to uninstall a software on remote pc) <p>All,
I am trying to uninstall a software remotely, it is working fine in the test machines, but i got problem in production servers.
test machines i have used windows xp, windows 2003 server,</p>
<p>production machine : windows server 2003.</p>
<p>what could be the cause of this error, any help would be more appreciated.
if you have any other way to unistall a software on the remote PC, please share.</p>
<pre><code>public void Uninstallwithguid(string targetServer, string product,string guid, string version)
{
this.Project.Log(Level.Info, "Starting Uninstall " );
this.Project.Log(Level.Info, "targetServer :" + targetServer );
this.Project.Log(Level.Info, "product :" + product );
this.Project.Log(Level.Info, "guid :" + guid );
this.Project.Log(Level.Info, "version :" + version );
System.Management.ConnectionOptions connoptions = new System.Management.ConnectionOptions();
connoptions.Impersonation = System.Management.ImpersonationLevel.Impersonate;
connoptions.Timeout = new TimeSpan(0, 0, 10); // 10 seconds
System.Management.ManagementScope scope = new System.Management.ManagementScope(@"\\" + targetServer + @"\root\cimv2", connoptions);
scope.Connect();
System.Management.ObjectGetOptions objoptions = new System.Management.ObjectGetOptions();
string test = @"\\" + targetServer + @"\root\cimv2";
string objPath = string.Format("Win32_Product.IdentifyingNumber='{0}',Name='{1}',Version='{2}'",guid, product, version);
System.Management.ManagementPath path = new System.Management.ManagementPath(objPath);
System.Management.ManagementObject moobj = new System.Management.ManagementObject(scope, path, null);
UInt32 res1 = 0;
try
{
res1 = (UInt32)moobj.InvokeMethod("Uninstall", null);
}
catch(Exception ex)
{
this.Project.Log(Level.Error, ex.ToString());
throw ex;
}
if (res1 != 0)
{
this.Project.Log(Level.Error, "Uninstall error " + res1.ToString());
throw new Exception("Uninstall error " + res1.ToString());
}
}
</code></pre>
<p>Error Description :</p>
<p>System.Management.ManagementException: Invalid class
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
at System.Management.ManagementObject.Initialize(Boolean getObject)
at System.Management.ManagementObject.get_ClassPath()
at System.Management.ManagementObject.GetMethodParameters(String methodName, ManagementBaseObject& inParameters, IWbemClassObjectFreeThreaded& inParametersClass, IWbemClassObjectFreeThreaded& outParametersClass)
at System.Management.ManagementObject.InvokeMethod(String methodName, Object[] args)</p>
|
<p>Win2003 doesn't have this class installed by default - you have to install it manually from the product disc.</p>
|
How to dynamically generate a pdf from Google's appengine? <p>I'd like to create an application that would run on Google's appengine.</p>
<p>However, this application needs to be able to generate PDFs dynamically.</p>
<p>How could I do this?</p>
|
<p>You can use the <a href="http://www.reportlab.org/rl_toolkit.html"><code>reportlab</code> library</a> to generate a PDF from Python. You can just include the ReportLab files in with your application's code, or you can include a <a href="http://code.google.com/appengine/articles/django10_zipimport.html">zip archive</a> of the ReportLab code, and insert it into your application's <code>sys.path</code>.</p>
|
Struts 2 & Dojo files are too heavy and affect site's performance.. Any remedies? <p>Well.. we've developed a j2ee application using struts2 ajax capabilities. We find that the dojo implementation is quite slow. We did the following things:
1. Custom build of the dojo library. (increased dojo.js from 240kb to 350kb)
2. Took all the static stuff out of the struts jar and kept it outside.</p>
<p>The performance was significantly improved. But still it is quite heavy as you can guess with 350kb size..</p>
<p>Is struts2 ajax supposed to be this heavy? or is there any lighter implementation available?</p>
<p><hr /></p>
<p>Edit: I used Firebug and YSlow with my application. Couple of changes that improved my situation hugely are mentioned below:</p>
<ol>
<li>Custom build of dojo (reduced the number of I/Os)</li>
<li>Move the static files out of Struts jar (helped a great deal)</li>
<li>tune your server to gzip the response (reduced the response size to 1/3)</li>
<li>Reduce number of images on your site.(this is obvious)</li>
</ol>
<p>Will keep updating on further changes..</p>
|
<p>First of all check that you did everything on the server to facilitate caching (e.g., setting right HTTP headers, compression, server-side caching, upstream caches, and so on). See <a href="http://lazutkin.com/blog/2007/feb/1/improving-performance/">Improving performance…</a> for more details.</p>
<p>The goal is to reduce I/O as much as possible — use Firebug or any other network traffic monitoring tool to see how much is sent back and forth. Try to minimize the number of I/O requests and the total number of bytes.</p>
<p>Don't forget that it applies to your dynamic data too — choose efficient formats, bundle several related requests together, remove all deadwood that is getting sent over and over unchanged.</p>
<p>If the custom build and server-side tweaks didn't help, consider restructuring your web app to be more light-weight. Examples:</p>
<ul>
<li>Evaluate the splash screen technique discussed in the link above.</li>
<li>If you use a lot of different form widgets, see if it is really necessary, and fall back on regular DOM elements like "input", "button", "textarea", "select".</li>
<li>The same goes for layout widgets. See if simple CSS can help you out.</li>
<li>Evaluate building Dojo in layers instead of one monolithic dojo.js so only the necessary subset is loaded by web pages. See details in <a href="http://www.dojotoolkit.org/book/dojo-book-0-9/part-4-meta-dojo/package-system-and-custom-builds">The Package System and Custom Builds</a>.</li>
</ul>
<p>Building web applications with Dojo for a living for last 2 years I still didn't see the one that cannot be optimized properly until it is fully accepted and perceived by end users as "fast", "nimble", and "light-weight".</p>
|
THotkey with win-key support? <p>Is there anyway to get the THotkey component in delphi to support the windows key?</p>
<p>Or does anyone know of a component that can do this?</p>
<p>Thanks heaps!</p>
|
<p>IMHO it is a good thing THotKey does not support this.</p>
<p>Don't use the windows key for keyboard shortcuts in your program, the "Windows Vista User Experience Guidelines" says the following under <a href="http://msdn.microsoft.com/en-us/library/bb545460.aspx">Guidelines - Interaction - Keyboard</a>:</p>
<blockquote>
<p>Don't use the Windows logo modifier key for program shortcut keys. Windows logo key is reserved for Windows use. Even if a Windows logo key combination isn't being used by Windows now, it may be in the future.</p>
</blockquote>
<p>Even if the shortcut isn't used by Windows, using such a keyboard shortcut would be confusing to users, as it would perform a function in your program, while other such shortcuts like Win+E or Win+R activate a system-wide function, deactivating your program in the process.</p>
<p><strong>Edit:</strong></p>
<p>THotKey is a light wrapper around a system control, supporting only the things that this system control supports. There is no documented way to set anything but the Alt, Ctrl and Shift modifiers for the shortcut.</p>
<p>You might be able to create your own control to display shortcuts using the Windows key, and set a global keyboard hook (look into the <em>SetWindowsHookEx()</em> API function).</p>
|
How would you read input file in Scheme? <p>I am trying to input data from a .txt file into a scheme structure. Each element is separated by a tab in the data file and each structure set is on a new line. I want to be able to read in the data from one line into a structure and make a list of each structure set in the file. Any suggestions?</p>
|
<p>Not really sure what structures you had in mind, but say you had a text file like the following:</p>
<pre>
--> cat blah.txt
foo bar baz
1 2 3 4 5
aa bb cc dd ee
</pre>
<p>You could convert it directly into a list of lists in scheme using sed:</p>
<pre>
--> echo "(define mylist '("`sed -e 's/\(.*\)/(\1)/' blah.txt`"))" > foo.txt
</pre>
<p>which then produces the following file:</p>
<pre>
--> cat foo.txt
(define mylist '((foo bar baz) (1 2 3 4 5) (aa bb cc dd ee)))
</pre>
<p>And now all you have to do is load the file into scheme:</p>
<pre>
(load "foo.txt")
</pre>
<p>And you can access the structure via the `mylist' variable.</p>
|
jQuery Autocomplete: Determining if entered text is not a match <p>I've got jQuery Autocomplete (UI 1.6rc2) up and running fine and when the user picks an item, it updates a hidden form value with the associated ID. How do I set the hidden form value to '0' when the text entered does not match a result from the autocomplete list? In this case, I'll be creating a new entry.</p>
|
<p>I did this in the autocomplete function:</p>
<pre><code>change: function(event, ui){
$(this).next("input[id^=person_id]").val('');
return false;
</code></pre>
<p>After the user selects the option and it populates my hidden input with the item ID, if any changes occur to the visible input, the hidden input value is cleared. Works like a charm!</p>
|
Monitoring a displays state in python? <p>How can I tell when Windows is changing a monitors power state?</p>
|
<p>It seems that, when Windows wants to start the screen saver or turn the monitor off, it will send a <code>WM_SYSCOMMAND</code> to the topmost window with a <code>wParam</code> of <code>SC_SCREENSAVE</code> (to start the screen saver) or a <code>wParam</code> of <code>SC_MONITORPOWER</code> and a <code>lParam</code> of 1 or 2 (to turn the monitor off). This message will then be passed to <code>DefWindowProc</code>, which will actually do the action. So, if your window happens to be the topmost one, you can intercept these events and ignore them (or do anything else you want before passing them to <code>DefWindowProc</code>).</p>
<p>On Windows Vista, there seems to be a more intuitive, and more reliable, way to know the monitor power state. You call <code>RegisterPowerSettingNotification</code> to tell the system to send your window a <code>WM_POWERBROADCAST</code> message with a <code>wParam</code> of <code>PBT_POWERSETTINGCHANGE</code> and a <code>lParam</code> pointing to a <code>POWERBROADCAST_SETTING</code> structure.</p>
<p>I cannot test either of them since I currently do not have any computer with Windows nearby. I hope, however, they point you in the right direction.</p>
<p>References:</p>
<ul>
<li><a href="http://blogs.msdn.com/oldnewthing/archive/2006/06/13/629451.aspx" rel="nofollow">The Old New Thing : Fumbling around in the dark and stumbling across the wrong solution</a></li>
<li><a href="http://groups.google.com/group/borland.public.delphi.nativeapi.win32/browse_thread/thread/81afbb4aff7503d4" rel="nofollow">Recursive hook ... - borland.public.delphi.nativeapi.win32 | Google Groups</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/aa373195(VS.85).aspx" rel="nofollow">Registering for Power Events (Windows)</a></li>
</ul>
|
Proper way to scale an SDL Surface without clipping? <p>what is the proper way to scale an SDL Surface? I found one explanation online but it required redrawing the Surface pixel by pixel. It seems like there should be some way of doing this natively through SDL rather than redrawing the image like that. I haven't been able to find anything in the SDL documentation that covers this. I am able to resize surfaces without any problem by modifying the surfaces width and height, but the resulting surface is clipped.</p>
|
<p>SDL doesn't support scaled blitting. According to the documentation of <a href="http://www.libsdl.org/cgi/docwiki.cgi/SDL_BlitSurface">SDL_BlitSurface</a>:</p>
<blockquote>
<p>Note: the SDL blitter does not (yet)
have the capability of scaling the
blitted surfaces up or down like it is
the case with other more sophisticated
blitting mechanisms. You have to
figure something out for yourself if
you want to scale images (e.g. use
SDL_gfx).</p>
</blockquote>
<p>You could find SDL_gfx <a href="http://www.ferzkopp.net/Software/SDL_gfx-2.0/">here</a>. Writing your own blitting function isn't that bad, it might be a fun and useful learning experiment (though you'd be reinventing the wheel). Using OpenGL is also an option, as stuff like scaling and rotating could be done in a single function call.</p>
|
decode a quoted printable message in php <p>I have the string which that encoded in <a href="http://en.wikipedia.org/wiki/Quoted_printable" rel="nofollow">quoted-printable</a>. How do I decode this in php?</p>
<pre><code>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vestibulum felis =
pede, vestibulum et, ullamcorper in, ultrices eget, metus. Suspendisse in n=
ulla. Sed justo. Donec dapibus auctor neque. Pellentesque faucibus ante nec=
metus. Vivamus feugiat, velit rhoncus semper suscipit, libero augue venena=
tis leo, nec ornare nulla elit eget diam. Nullam sollicitudin.
</code></pre>
|
<p>This should help: <a href="http://us2.php.net/quoted_printable_decode" rel="nofollow">quoted_printable_decode</a></p>
|
How do you do a SQL style 'IN' statement in LINQ to Entities (Entity Framework) if Contains isn't supported? <p>I'm using LINQ to Entities (not LINQ to SQL) and I'm having trouble creating an 'IN' style query. Here is my query at the moment:</p>
<pre><code>var items = db.InventoryItem
.Include("Kind")
.Include("PropertyValues")
.Include("PropertyValues.KindProperty")
.Where(itm => valueIds.Contains(itm.ID)).ToList<InventoryItem>();
</code></pre>
<p>When I do this however, the following exception is thrown:</p>
<blockquote>
<p>LINQ to Entities does not recognize the method 'Boolean Contains(Int64)' method, and this method cannot be translated into a store expression.</p>
</blockquote>
<p>Does anyone have a workaround or another solution for this?</p>
|
<p>You can use Linq's <code>Any</code> extension method for this in some cases:</p>
<pre><code>var userIds = new[] { 1, 2, 3 };
from u in Users
where userIds.Any(i => i==u.Id)
select u;
</code></pre>
<p>The generated SQL looks pretty strange in such a case, but like much Linq-to-Entities generated SQL it might be overly verbose for a human, but runs fast in practice.</p>
<pre><code>SELECT
[Extent1].[Id] AS [Id],
[Extent1].[DisplayName] AS [DisplayName],
FROM [dbo].[Users] AS [Extent1]
WHERE EXISTS (SELECT
1 AS [C1]
FROM (SELECT
[UnionAll1].[C1] AS [C1]
FROM (SELECT
1 AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
UNION ALL
SELECT
2 AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable2]) AS [UnionAll1]
UNION ALL
SELECT
3 AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable3]) AS [UnionAll2]
WHERE [UnionAll2].[C1] = [Extent1].[Id]
)
</code></pre>
|
Resolving SVN merge postponed conflicts recursively <p>I have a dev branch that hasn't been touched for a while. I merged the trunk into it to integrate many fixes/changes in the main line since it was branched out, but now I have many small conflicts (merge-left/merge-right).</p>
<p>I want the latest trunk revision to be used to resolve each conflict. Is there a command I can run that will resolve all conflicts under a working copy in one direction automatically (merge-right should be used for all conflicts)?</p>
<p>EDIT:
As indicated in the comments, I tried reverting and then running svn merge with the --accept option, only apparently there is no such option in SVN 1.0. Still looking for a solution.</p>
|
<p>I think you can use the "--accept theirs-full" option when you issue the svn merge command.
That should do what you want...</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.