input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
|---|---|
Which Facebook .NET Library is the best to use? <p>There is a list of projects <a href="http://www.marketing-ninja.com/old-stuff/list-of-facebook-sdks-for-net/">here</a>, mainly the <a href="http://www.codeplex.com/FacebookToolkit">Facebook Developer Toolkit</a> and <a href="http://www.nikhilk.net/FacebookNET.aspx">Facebook.NET</a>. However, I've seen a lot of negative feedback about the toolkit and it seems like Facebook.NET hasn't been upgraded to the latest facebook API. </p>
<p>Are either of these worth using? Any other good libraries out there?</p>
<p>Specifically I'm looking to use the library in a ASP.NET MVC application.</p>
<p>Thanks!</p>
|
<p>I also started experimenting with Facebook Developer Toolkit (FDT) but dropped it for Facebook.NET. There is a fork of the latter at <a href="http://www.codeplex.com/fbnet" rel="nofollow">http://www.codeplex.com/fbnet</a> which slowly covers recent changes in Facebook API. Have a look at this post since it has some interesting integration points for Facebook.NET and MVC <a href="http://www.coderjournal.com/2008/06/mvc-facebook-wonderful-development-platform/" rel="nofollow">http://www.coderjournal.com/2008/06/mvc-facebook-wonderful-development-platform/</a></p>
<p>FDT is made for WebForms mainly and it will take you some time to integrate it properly with MVC. And Matt is right: the documentation of FDT RC2 (last time I checked) was out of date and misleading. If you plan using this anyway check this out also <a href="http://corcoranpstech.blogspot.com/2008/06/facebook-mvc.html" rel="nofollow">http://corcoranpstech.blogspot.com/2008/06/facebook-mvc.html</a></p>
<p>You may also find a promising - still in alpha though - library (Facebook API for .NET) here: <a href="http://facebook.codeplex.com/" rel="nofollow">http://facebook.codeplex.com/</a></p>
<p>latest addition: the only library one should check right now is <a href="http://facebooksdk.codeplex.com/" rel="nofollow">http://facebooksdk.codeplex.com/</a></p>
|
Recommended spec for a build server <p>We're using CruiseControl.NET to manage our builds and we're in the process of obtaining a new build server. I've been tasked with coming up with the spec for the new server.</p>
<p>This server will need to run multiple builds concurrently and as effeciently as possible.</p>
<p>What would you consider the ideal spec for this server?</p>
<p>Any links to existing articles / blogs dealing with this topic will also be welcome!</p>
<p>Edit: Will RAID be helpful at all? (Bonus points)</p>
|
<p>Make sure the spec includes a multi-core processor, and fast HDDs (10000RPM). </p>
|
Error with C# Partial classes <p>I am using partial classes to split some functionality between 2 files, but I am getting an error. What am I doing wrong?</p>
<p>A1.cs:</p>
<pre><code>private partial class A
{
private string SomeProperty { get { return "SomeGeneratedString"; } }
}
</code></pre>
<p>A2.cs:</p>
<pre><code>private partial class A
{
void SomeFunction()
{
//trying to access this.SomeProperty produces the following compiler error, at least with C# 2.0
//error CS0117: 'A' does not contain a definition for 'SomeProperty'
}
}
</code></pre>
|
<p>Are the two partial classes in the same namespace? That could be an explanation.</p>
|
C++ testing framework: recommendation sought <p>I'm looking for a "quick and dirty" C++ testing framework I can use on my Windows/Visual Studio box. It's just me developing, so it doesn't have to be enterprise class software.
Staring at a list of testing frameworks, I am somewhat befuddled...</p>
<p><a href="http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C.2B.2B" rel="nofollow">http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C.2B.2B</a></p>
|
<p>I have used both <a href="http://unittest-cpp.sourceforge.net/">UnitTest++</a> and <a href="http://www.boost.org/doc/libs/1_36_0/libs/test/doc/html/index.html">Boost.Test</a>. They are both easy to setup and use.
Although, I wouldn't use Boost.Test if you're not already using the Boost libraries. It's a bit much to install all of Boost just to get the testing framework.</p>
|
What is the general complexity of building a canonical language representation? <p>It is often handy to have a canonical representation of a language (in my case they are usually domain specific languages); however, I believe there are strict limits on the expressiveness of the languages involved that determine whether a canonical form can be determined and/or created for an arbitrary program in that language. Unfortunately, I've been unable to find the references that I (vaguely) recall reading about this in.</p>
<p>On one hand, it seems reasonable that creating a canonical representation of a language is of comparable complexity to many hard graph problems (eg: graph isomorphism), but on the other hand, iirc, compilers like gcc, yhc, and ghc use intermediate representations to generate outputs in various formats (assembly, javascript, etc.), so this is at least in some forms, a solved problem. </p>
<p>When is it possible to determine / generate a canonical form for a given language? (How expressive can that language be, and how does language expressiveness impact the utility of the canonical forms?) Please provide references or proofs if at all possible.</p>
<p><em>Edit:</em> For example, a <a href="http://en.wikipedia.org/wiki/Regular_language" rel="nofollow">Regular Language</a> (eg: the 'pure' form of regular expressions) can not express many of the same things that a <a href="http://en.wikipedia.org/wiki/Turing_complete" rel="nofollow">Turing-complete language</a> can. In other words, you can't write a web server in a regular language, but you can with lambda calculus). My question is about the theoretical possibilities, and does have a specific answer relating to complexity theory. If I have a DSL that needs to be transmitted to another system, it will often be beneficial to generate a canonical form of that code before transmitting it, since that will decouple the independent representations used by the two different systems. <em>However</em>, if it is P-Space complete, or NP-Complete to translate a Turing-complete language into a canonical form, then you shouldn't waste time trying to build a canonical form -- either find another way to do it, or reduce the language complexity to something that <em>can</em> be canonicalized in polynomial time.</p>
|
<p>By "canonical representation" I assume you mean the following: Call programs <em>P</em> and <em>Q</em> <em>equivalent</em> if they "do the same thing" on the same inputs. "Doing the same thing" means that the programs have the same output, and either both programs halt after a finite time or both enter an infinite loop. This equivalence relation defines equivalence classes in the set of all programs. The "canonical representation" of a program <em>P</em> is a program <em>P'</em> belonging to the same equivalence class, and you require that all members of the same equivalence class have the same canonical representation. </p>
<p>For Turing-complete languages, a Turing-computable canonical representation would enable you to solve the <a href="http://en.wikipedia.org/wiki/Halting_problem" rel="nofollow">Halting Problem</a> as follows: first write a program consisting of an infinite loop and find its canonical representation <em>Q</em>. Then for any input program <em>P</em>, first transform it mechanically into a program <em>P</em><sub>0</sub> that does the same thing except that it produces no output, and then find the canonical representation <em>P</em><sub>0</sub>' of this program. If the result is <em>Q</em>, you know that <em>P</em><sub>0</sub> does not halt, and therefore neither does <em>P</em>. Otherwise, <em>P</em><sub>0</sub> halts, and so does <em>P</em>.</p>
<p>For even more fun, read some of <a href="http://en.wikipedia.org/wiki/Gregory_Chaitin" rel="nofollow">Gregory Chaitin's</a> work on what he calls "elegant" programs.</p>
|
SQL Date Range Split <p>Can you please let me know the SQL to split date ranges when they overlap?</p>
<p>Data (sample data with a date range and possibly other columns):</p>
<pre><code> Col1 FromDate ToDate
1. 1 1/1/2008 31/12/2010
2. 1 1/1/2009 31/12/2012
3. 1 1/1/2009 31/12/2014
</code></pre>
<p>Output:</p>
<pre><code> Col1 From Date ToDate
1. 1 1/1/2008 31/12/2008 (from row 1 above)
2. 1 1/1/2009 31/12/2010 (from rows 1,2 and 3 above)
3. 1 1/1/2011 31/12/2012 (from rows 2 and 3 above)
4. 1 1/1/2013 31/12/2014 (from row 3 above)
</code></pre>
|
<p>This should do the trick (MySQL dialect, but easily adaptable)</p>
<p>Initial setup</p>
<pre><code>SQL query: SELECT * FROM `test` LIMIT 0, 30 ;
Rows: 3
start end
2008-01-01 2010-12-31
2009-01-01 2012-12-31
2009-01-01 2014-12-31
</code></pre>
<p>Query</p>
<pre><code>SELECT
`start` , min( `end` )
FROM (
SELECT t1.start, t2.end
FROM test t1, test t2
WHERE t1.start < t2.end
UNION
SELECT t1.end + INTERVAL 1 DAY , t2.end
FROM test t1, test t2
WHERE t1.end + INTERVAL 1 DAY < t2.end
UNION
SELECT t1.start, t2.start - INTERVAL 1 DAY
FROM test t1, test t2
WHERE t1.start < t2.start - INTERVAL 1 DAY
) allRanges
GROUP BY `start`
</code></pre>
<p>Result</p>
<pre><code>start min( `end` )
2008-01-01 2008-12-31
2009-01-01 2010-12-31
2011-01-01 2012-12-31
2013-01-01 2014-12-31
</code></pre>
|
Navigation on validation failure in Seam/JSF <p>I've been playing with <a href="http://www.seamframework.org/" rel="nofollow">Seam</a> (2.0.2.SP1) for a few weeks, and I have most of the basics nailed down, but I haven't come up with a decent solution to the following.</p>
<p>Suppose I have a form at <code>/foo.xhtml</code>, with a rewrite rule such that URLs like <code>/foo.seam?id=<fooId></code> are converted to <code>/foo/<fooId></code>. There's a <code>commandButton</code> on the form with an action of <code>#{fooHome.update}</code>. I also have a navigation rule in <code>/foo.page.xml</code> that redirects back to a nice, bookmark-friendly GET after a successful POST:</p>
<pre><code><navigation from-action="#{fooHome.update}">
<rule if-outcome="updated">
<redirect view-id="/foo.xhtml">
<param name="id" value="#{fooHome.instance.id}"/>
</redirect>
</rule>
</navigation>
</code></pre>
<p>The problem is when a validation error occurs, at which point the navigation rules get skipped, and I end up at <code>/foo</code> after the POST.</p>
<p><strong>My question: Is there a way to redirect on validation errors, so I end up with a GET request for <code>/foo/<fooId></code> instead of the POST to <code>/foo</code>?</strong></p>
<p>I tried rolling my own validation methods in <code>fooHome</code>, returning a "failed" outcome, but I don't really want invalid data getting past the validation phase (and thus into the current conversation).</p>
|
<p>You would normally redisplay the same view on a validation failure, rather than redirect. Assuming that you are using UrlRewrite for the rewrite rules, perhaps you can use an <em>outbound-rule</em> so that the <em>/foo/{fooId}</em> URL is still shown in this case.</p>
|
CSS and lack of constants/variables issue? <p>Given a stylesheet with a fully qualified reference to an image resource on another server, is there a good way to handle promotions through different environments that require a different base URL?</p>
<blockquote>
<p>background-image: url
(evironmentSpecificURL/resourceName.foo);</p>
</blockquote>
<p>The environmentSpecificURL will vary from environment to environment and I don't want this file to be modified as it progresses from development, qa, staging, production, etc.</p>
<p>I have ideas, but am interested in how others have dealt with this -- I'll post one of my ideas.</p>
<p>Let me underscore (based on another response) that the image resource does not exist on the same server and that is the URL that will change. So relative paths do not work in that situation.</p>
<p>Also, I am trying to avoid the need to modify the css where there could be multiple instances of the URL and centralize that URL to one point of configuration.</p>
<p>any help!</p>
|
<p>The resources that you reference should really be at a relative level to your css file, that way its just a "..\resourceName.foo" away from working.</p>
<p>Of cource you could also look into build tools that auto-generate the environment specific areas of your site, so all properties such as css file, .properties files, etc... are generated dynamically via a build tool link ANT or MSBuild</p>
|
What are some best practices for handling sensitive information? <p>I'm currently creating an application for a customer that will allow them to automatically bill their customers credit cards. </p>
<p>I'm curious as to what are some <strong>best practices</strong> to safely store and access the credit card information, and for that matter, any other sensitive information, like social security numbers, account numbers and so on.</p>
<p>I'm <strong>assuming</strong> encryption of some type will be employed, but before I dig in too deep I wanted to see how others are handling these types of requirements.</p>
<p>Not that it matters, but we are designing the software using Microsoft SQL Server for the database, and using C# and ASP.NET.</p>
|
<p>Read the <a href="http://pcistandard.com/requirements.html" rel="nofollow">PCI requirements</a>. Everything will be there.</p>
<p>Actually, you <em>must</em> follow them.</p>
|
Uninitialized string offset error from PHP import script <p>I have an import-from-excel script as part of a CMS that previously ran without issue.</p>
<p>My shared-hosting provider has recently upgraded their infrastructure, including PHP from 5.1 to 5.2.6, and the script now returns "Uninitialized string offset: -XXX in /path/scriptname.php on line 27" (XXX being a decreasing number from 512 and /path/scriptname.php of course being the full path to script in question). </p>
<p>It returns this error for every line of the excel file. Line 27 is just a return from within a function that is the first point at which the imported data is being processed:</p>
<pre><code>function GetInt4d($data, $pos) {
return ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | (ord($data[$pos+3]) << 24);
}
</code></pre>
<p>It finally implodes with a "Fatal error: Allowed memory size of 47185920 bytes exhausted (tried to allocate 71 bytes) in /path/scriptname.php on line 133".</p>
<p>There's nothing useful in Apache error logs. I am stumped. Anyone have any ideas of at least where to look? Even knowing if it's likely to be something within my script or something to do with upgrade would be useful. I had another issue with a different site on same provider that (after upgrade) couldn't write sessions to tmp directory (since resolved), but am pretty sure it's not that (?).</p>
<p>EDIT: As it turned out that the answer was to do with the version of the parser being incompatible in some way with PHP 5.2.6, I thought it might be of use to someone that the parser in question is <a href="http://sourceforge.net/project/showfiles.php?group_id=99160&package_id=106368" rel="nofollow">Spreadsheet Excel Reader</a> .</p>
|
<p>Solved here:
<a href="http://www.phpbuilder.com/board/archive/index.php/t-10328608.html" rel="nofollow">http://www.phpbuilder.com/board/archive/index.php/t-10328608.html</a></p>
|
Issues with client consuming a .net web service upgraded from .NET 1.1 to 3.5 <p>I am working on a web application that was recently converted from Visual Studio 2003 to Visual Studio 2008. The application contained some web services that were written using the .NET 1.1 Framework and Web Service Enhancements 2.0. They were converted to the .NET 3.5 framework using the VS 2008 Conversion Wizard Tool.</p>
<p>A client application which is still written using the .NET 1.1 framework has a reference to the updated web service and try to consume the web service and received the following error:</p>
<p>System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: (web service URI)</p>
<p>The URL Behavior is set to static for the reference and the proxy class inheritance was changed from System.Web.Services.Protocols.SoapHttpClientProtocol namespace to Microsoft.Web.Services2.WebServicesExtension namespace</p>
<p>If you need additional information or need to see some source code, please let me know.</p>
|
<p>If you go directly to the asmx url with a web browser, and then click on the method you want to call, what's the SOAPAction that they want?</p>
<p>next, check the Reference.vb code and see what the SoapDocumentMethodAttribute attribute is set to.</p>
<p>Do they match?</p>
|
How can I concatenate regex literals in JavaScript? <p>Is it possible to do something like this?</p>
<pre><code>var pattern = /some regex segment/ + /* comment here */
/another segment/;
</code></pre>
<p>Or do I have to use new <code>RegExp()</code> syntax and concatenate a string? I'd prefer to use the literal as the code is both more self-evident and concise.</p>
|
<p>Here is how to create a regular expression without using the regular expression literal syntax. This lets you do arbitary string manipulation before it becomes a regular expression object:</p>
<pre><code>var segment_part = "some bit of the regexp";
var pattern = new RegExp("some regex segment" + /*comment here */
segment_part + /* that was defined just now */
"another segment");
</code></pre>
<p>If you have two regular expression literals, you can in fact concatenate them using this technique:</p>
<pre><code>var expression_one = /foo/;
var expression_two = /bar/;
var expression_three = new RegExp(expression_one.source + expression_two.source);
</code></pre>
<p>It's not entirely a good solution, as you lose the flags that were set on expression_one and expression_two, and is more wordy than just having expression one and two being literal strings instead of literal regular expressions.</p>
|
Convert Month Number to Month Name Function in SQL <p>I have months stored in SQL Server as 1,2,3,4,...12. I would like to display them as January,February etc. Is there a function in SQL Server like MonthName(1) = January? I am trying to avoid a CASE statement, if possible.</p>
|
<p>I think this is the best way to get the <strong>month name</strong> when you have the <strong>month number</strong></p>
<pre><code>Select DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )
</code></pre>
<p><strong>[EDIT]</strong></p>
<p>As Asif said below, another way of doing this would be </p>
<pre><code>Select DateName( month , DateAdd( month , @MonthNumber , -1 ) )
</code></pre>
|
Javascript nested class <p>How do I define nested class in Java Script. </p>
<p>Here is the code snippet I have:</p>
<pre><code>objA = new TestA();
function TestB ()
{
this.testPrint = function ()
{
print ( " Inside testPrint " );
}
}
function TestA ()
{
var myObjB = new TestB();
}
</code></pre>
<p>Now I am trying to access testPrint using objA</p>
<pre><code>objA.myObjB.testPrint();
</code></pre>
<p>But its giving error "objA has no properties"</p>
<p>How can I access testB method using objA handler?</p>
|
<p>If you want the prototype definition of the inner nested classes to be not accessible from outside the outer class, as well as a cleaner OO implementation, take a look at this.</p>
<pre><code>var BobsGarage = BobsGarage || {}; // namespace
/**
* BobsGarage.Car
* @constructor
* @returns {BobsGarage.Car}
*/
BobsGarage.Car = function() {
/**
* Engine
* @constructor
* @returns {Engine}
*/
var Engine = function() {
// definition of an engine
};
Engine.prototype.constructor = Engine;
Engine.prototype.start = function() {
console.log('start engine');
};
/**
* Tank
* @constructor
* @returns {Tank}
*/
var Tank = function() {
// definition of a tank
};
Tank.prototype.constructor = Tank;
Tank.prototype.fill = function() {
console.log('fill tank');
};
this.engine = new Engine();
this.tank = new Tank();
};
BobsGarage.Car.prototype.constructor = BobsGarage.Car;
/**
* BobsGarage.Ferrari
* Derived from BobsGarage.Car
* @constructor
* @returns {BobsGarage.Ferrari}
*/
BobsGarage.Ferrari = function() {
BobsGarage.Car.call(this);
};
BobsGarage.Ferrari.prototype = Object.create(BobsGarage.Car.prototype);
BobsGarage.Ferrari.prototype.constructor = BobsGarage.Ferrari;
BobsGarage.Ferrari.prototype.speedUp = function() {
console.log('speed up');
};
// Test it on the road
var car = new BobsGarage.Car();
car.tank.fill();
car.engine.start();
var ferrari = new BobsGarage.Ferrari();
ferrari.tank.fill();
ferrari.engine.start();
ferrari.speedUp();
// var engine = new Engine(); // ReferenceError
console.log(ferrari);
</code></pre>
<p>This way you can have <em>prototype inheritance</em> and <em>nested classes</em> so that classes defined within <code>BobsGarage.Car</code> are not accessible outside the constructor of <code>BobsGarage.Car</code> but instances of them are accessible to derived classes, as shown in the test code.</p>
<p>Note: I am referring to the concept of <em>Class</em> in Javascript as defined on the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript">MDN</a>. </p>
|
How to inflate a file with zlib.NET? <p>I'm using the <a href="http://www.componentace.com/zlib_.NET.htm" rel="nofollow">zlib.NET</a> library to try and inflate files that are compressed by zlib (on a Linux box, perhaps). Here's what I'm doing:</p>
<pre><code>zlib.ZInputStream zinput =
new zlib.ZInputStream(File.Open(path, FileMode.Open, FileAccess.Read));
while (stopByte != (data = zinput.ReadByte()))
{
// check data here
}
zinput.Close();
</code></pre>
<p>The data bytes match the compressed data bytes, so I must be doing something wrong.</p>
|
<p>It appears I made the mistake of assuming all virtual methods were overridden, which wasn't the case. I was using zlib.ZInputStream.ReadByte(), which is just the inherited Stream.ReadByte(), which doesn't do any inflate.</p>
<p>I used zlib.ZInputStream.Read() instead, and it worked like it should.</p>
|
Would you architect the control API of the next-gen Mars rover to be RESTful instead of an RPC? <p>Forgive me if this verges on being a "discussion" question, but I really would
appreciate a yes/no answer, with an appropriate explanation. </p>
<p>Suppose you have to design and implement a control API for a robot, say the next
generation Mars Rover. Do you architect this API according to RESTful
principles, or do you use a classic RPC, such as XMLRPC? </p>
<p>I ask this because I have to do something similar, though the "robot" is a collection of virtual machines. I'm being urged by one rather persuasive engineer, a well known REST advocate, to make the API RESTful. I've never used REST principles, and I'm struggling to see how they fit in designing low-level inter-process APIs. REST seems infused with the theme of interacting with a modifiable data repository, usually many hops away. What I'm trying to do feels more like closely controlling a robot. I can see how one could argue that the robot is, in the abstract, just a data repository -- "PUT left turn", "PUT travel 100 meters", "GET outside temperature". But this seems to be a rather contrived model. I certainly will receive no benefit from caching or a proxy ("Hello, JPL? This is the Akamai co-lo in Canberra. We're taking over the Rover now, ok?") </p>
<p>So, is a RESTful architecture useful here? Is it still superior to RPC even
when the interaction is so narrowly focused?</p>
|
<p>I think REST would make more sense than traditional RPC. Even the <a href="http://msdn.microsoft.com/en-us/library/bb466255.aspx">Micorosft Robotics Studio runtime application model</a> uses REST.</p>
<p>The robot can consist of different resources that are identified by URI, including one for each sensor and actuator or composite abstractions thereof.</p>
<p>REST puts emphasis on guaranteeing what the side effects of certain methods are and also it facilitates caching, both of which can be useful for something like controlling and monitoring a distant robot. And just because you can use REST it <strong>doesn't</strong> have to be the HTTP protocol.</p>
<p>A SAFE and IDEMPOTENT method like GET, though, is good for tracking the state of the robot and polling its sensor data. You can use something like the Last-Modified header to retrieve cached sensor data that doesn't change often (e.g., humidity or light levels). </p>
<p>For long distances you can use relay proxies for caching.</p>
<p>For commands that move the robot, something like POST would be used where every such message will change the robot (e.g., turn right ). A status code can be returned indicating whether the command was immediately executed or queued for processing. </p>
<p>The absolute state of any resources can be set using something like PUT where multiple messages will not change things any more than just a single message (e.g., point to north pole or dim front lights to 10% brightness). This allows for reliable messaging in case of probablity of messages getting lost en route.</p>
<p>A new resource may be created via a POST-like operation as well, e.g., a data-collection routine and a set of parameters. The POST request can send back a CREATED result with a URI for the new resource, which can be used to DELETE when no longer needed.</p>
<p>A group of robots may also speak to each other using the same REST based protocol and can enjoy the same benefits.</p>
<p>Granted, for something simple like one person controlling a single isolated local robot, a REST API may be overkill. But for multi-user and/or unreliable-communications-channels and/or Web-scale-networking, REST is something to consider.</p>
|
Modifying NSDate to represent 1 month from today <p>I'm adding repeating events to a Cocoa app I'm working on. I have repeat every day and week fine because I can define these mathematically (3600*24*7 = 1 week). I use the following code to modify the date:</p>
<pre><code>[NSDate dateWithTimeIntervalSinceNow:(3600*24*7*(weeks))]
</code></pre>
<p>I know how many months have passed since the event was repeated but I can't figure out how to make an NSDate object that represents 1 month/3 months/6 months/9 months into the future. Ideally I want the user to say repeat monthly starting Oct. 14 and it will repeat the 14th of every month.</p>
|
<p>(Almost the same as <a href="http://stackoverflow.com/questions/181459/is-there-a-better-way-to-find-midnight-tomorrow/181495#181495">this question</a>.)</p>
<p>From the <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSCalendarDate_Class/Reference/Reference.html">documentation</a>:</p>
<blockquote>
<p>Use of NSCalendarDate strongly
discouraged. It is not deprecated yet,
however it may be in the next major OS
release after Mac OS X v10.5. For
calendrical calculations, you should
use suitable combinations of
NSCalendar, NSDate, and
NSDateComponents, as described in
Calendars in <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html">Dates and Times
Programming Topics for Cocoa</a>.</p>
</blockquote>
<p>Following that advice:</p>
<pre><code>NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.month = 1;
NSDate *nextMonth = [gregorian dateByAddingComponents:components toDate:today options:0];
[components release];
NSDateComponents *nextMonthComponents = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit fromDate:nextMonth];
NSDateComponents *todayDayComponents = [gregorian components:NSDayCalendarUnit fromDate:today];
nextMonthComponents.day = todayDayComponents.day;
NSDate *nextMonthDay = [gregorian dateFromComponents:nextMonthComponents];
[gregorian release];
</code></pre>
<p>There may be a more direct or efficient implementation, but this should be accurate and should point in the right direction.</p>
|
What's is a good ratio of Class to Lines of Code for Object-Oriented languages? <p>What's is a good ratio for the number Classes to Lines of Code for an Object-Oriented language (say C++,C#,Java and their likes)?</p>
<p>Many people, including managers, like the traditional LOC (lines of code) metric to measure the complexity of software, while many hard-boiled Object Oriented developers will say LOC is worthless its Class count that matters. And personally I believe that Classes may be a more reasonable metric of complexity, but that without a LOC metric the actual complexity of those classes (amount of poltergeists and gods in there) is hard to estimate.</p>
<p>Thus does anybody know of what is likely to be a healthy ratio for some fairly well coded software?</p>
<p>Edit: In this particular case, I'm looking for a ratio to determine a ball-park estimate of how much refactoring might be required to clean up the code.</p>
<p>Edit: Does anyone know of ratios for some big OSS projects like Firefox, Apache, Webkit, etc...?</p>
|
<p>LOCs or NLOCs aren't really a good measure of quality or health of your code. I recommend using <a href="http://www.ndepend.com">NDepend</a>'s static code analysis (for you .net peeps) to see how well your solution is architected.</p>
<p>I find that LOCs is good measurement only at the method level. That is, I generally like my methods to fit on a screen (no small fonts). Other metrics like Cyclomatic Complexity and Code Coverage (for you TDDers) in addition to your unit tests can give to a better feel for how healthy your codebase is.</p>
|
How do I add to a list with Linq to SQL? <p>I have a table in the database that I'm retrieving using LINQ to SQL, and as a part of my processing I want to add to this list, then update the database with the new items + any changes I've made.</p>
<p>What I thought I could do was this:</p>
<pre><code>var list = (from item in db.Table
select item).ToList();
[do processing where I modify items & add to the list]
list = list.Distinct();
db.SubmitChanges();
</code></pre>
<p>What happens is that the modifications happed (ie. SQL updates) but any new items I add to the list don't get added.</p>
<p>Obviously I'm doing this wrong, what is the correct way to modify & add to a list of DB entities, then commit all the updates & inserts?</p>
|
<p>The List is meaningless. It's just happens to hold objects that the DataContext knows about. We need to make sure that the DataContext knows about the new ones. The important thing is that they don't have to be complete when we alert the DataContext to them:</p>
<pre><code>Item item;
if (needNewOne)
{
item = new Item();
db.InsertOnSubmit(item);
}
else
{
item = list[i];
}
/// build new or modify existing item
/// :
db.SubmitChanges();
</code></pre>
|
SQL 2005 Full-Text Catalog is randomly sloooowww <p>I've built a full-text catalog on a SQL 2005 box that, after it's re-build process completes, runs extremely slow. I've implemented a hack (i.e. try...catch{do again}) so that my users don't get a timeout error; this makes me feel bad inside. All subsequent queries are lightning fast.</p>
<p>Has anyone experienced this issue and was/is there a solution? Thanks!</p>
<p>P.S. Yes, I've Google'd it many times. Even with my left hand.</p>
|
<p>It could also be caused by this Sql Server 'feature' which we've experienced.</p>
<p><strong>You may experience a 45-second delay when you run a full-text query in an instance of SQL Server 2005 that is running on a server without Internet access</strong> </p>
<p><a href="http://support.microsoft.com/default.aspx/kb/915850" rel="nofollow">http://support.microsoft.com/default.aspx/kb/915850</a></p>
|
onClose Event in ASP.NET <p>Is there an event like onLoad? </p>
<p>just at closing the Site (onClose)?</p>
|
<p>Not in the sense that I suspect you're thinking. All your code in ASP.net runs on the server which doesn't inherently "know" when the site is closed by the user. To achieve what you're after, you'd need to use Javascript to handle the window.onunload / window.onbeforeunload events and trigger some form of request to the server.</p>
<p>Take a look at <a href="http://developer.mozilla.org/en/DOM/window.onunload" rel="nofollow">http://developer.mozilla.org/en/DOM/window.onunload</a> for more information on the window.onunload event.</p>
<p>Update: If you're using/able to use ASP.net AJAX, there's some quite tidy wrappers there that provide you with a similar set of events/beahviours to the server-side page lifecycle. There's a pretty decent tutorial from Stephen Walther <a href="http://weblogs.asp.net/stephenwalther/archive/2008/03/07/asp-net-ajax-in-depth-application-events.aspx" rel="nofollow">on his blog</a>.</p>
|
PHP's file_get_contents not returning until remote servers' keep-alive limit is exceeded <p>From one apache server file_get_contents returns the contents of a url straight away. On another apache server file_get contents won't return the contents of the same url until the keep-alive limit of the server hosting that url has been expired. The 2 php servers are retrieving the same url but through different network routes. What could be causing one php installation to wait for the remote keep-alive limit before returning? </p>
|
<p>Does using <code>fopen</code> manually work faster?</p>
<p>Rather than spending hours working out why <code>file_get_contents</code> doesn't work, you might be better-off swapping it out.</p>
<p>If <code>fopen</code> isn't any faster, there's probably a config or filesystem issue. If it is faster, it's likely a php.ini issue.</p>
|
Get Visual Studio to throw exceptions across threads <p>In my Silverlight project I have a thread that fires every x milliseconds. In this thread I was attempting to change the state of the application. This wasn't working and I didn't know why, so put a breakpoint in to the Timer callback. The breakpoint was hit, but the minute I attempted to change the state it just bailed out of the function (assuming an exception has been thrown).</p>
<p>I know <em>why</em> the error occurred - you can't change GUI stuff via a non-GUI thread.</p>
<p>My question is - how can I get Visual Studio to actually break when an exception like that occurs? (Rather than just silently bailing out, which doesn't notify me if there is a problem).</p>
<p>I've tried the "Break when exceptions cross AppDomain or managed / native boundaries", but that didn't have any effect.</p>
|
<p>Can you change the break handling for InvalidOperationException so it breaks immediately rather than only if it's unhandled?</p>
|
Create COM component and ActiveX controls <p>Is is possible to create COM component and ActiveX controls in .Net (using c# language). I searched internet but i could`t get anything.<br><br>
Thanks,<br>
santhosh</p>
|
<p>Declare an interface and implement it with class.<br>
If you have parameters/return values that are not OLE Automation compatible (custom structs, enums and so on), you might need to decorate them with the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.aspx">MarshalAs attribute</a>.<br>
Add the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.guidattribute.aspx">GUID attribute</a> to both.<br>
Add the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.comvisibleattribute.aspx">COMVisible attribute</a> to both. Alternatively, you can <a href="http://msdn.microsoft.com/en-us/library/ms182157(VS.80).aspx">mark the assembly</a> with it.<br>
Use <a href="http://msdn.microsoft.com/en-us/library/hfzzah2c.aspx">tlbexp</a> to generate a type library for native clients.</p>
|
Is it possible to specify proxy credentials in your web.config? <p>I need to configure a website to access a webservice on another machine, via a proxy. I can configure the website to use a proxy, but I can't find a way of specifying the credentials that the proxy requires, is that possible? Here is my current configuration:</p>
<pre><code><defaultProxy useDefaultCredentials="false">
<proxy usesystemdefault="true" proxyaddress="<proxy address>" bypassonlocal="true" />
</defaultProxy>
</code></pre>
<p>I know you can do this via code, but the software the website is running is a closed-source CMS so I can't do this.</p>
<p>Is there any way to do this? MSDN isn't helping me much..</p>
|
<p>Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.</p>
<p>Create an assembly called <em>SomeAssembly.dll</em> with this class :</p>
<pre><code>namespace SomeNameSpace
{
public class MyProxy : IWebProxy
{
public ICredentials Credentials
{
get { return new NetworkCredential("user", "password"); }
//or get { return new NetworkCredential("user", "password","domain"); }
set { }
}
public Uri GetProxy(Uri destination)
{
return new Uri("http://my.proxy:8080");
}
public bool IsBypassed(Uri host)
{
return false;
}
}
}
</code></pre>
<p>Add this to your config file :</p>
<pre><code><defaultProxy enabled="true" useDefaultCredentials="false">
<module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>
</code></pre>
<p>This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.</p>
<p>This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx">ConfigurationSection</a>, or add some information in the <a href="http://msdn.microsoft.com/en-us/library/ms228154.aspx">AppSettings</a>, which is far more easier.</p>
|
Interesting UTF-8 Yahoo File Download Headers <p>My company runs a webmail service, and we were trying to diagnose a problem with Word downloads not opening automatically - the same *.doc file download from Yahoo Mail would open, but one from ours would not.</p>
<p>In the course of investigating the headers we saw this coming from Yahoo:</p>
<pre><code>content-disposition attachment; filename*="utf-8''word document.doc";
</code></pre>
<p>Whereas our headers were like this:</p>
<pre><code>content-disposition attachment; filename="word document.doc";
</code></pre>
<p>What exactly is Yahoo doing with the additional asterisk and utf-8'' designation?</p>
|
<p>I think the correct answer to this is in rfc 2231:</p>
<p>Asterisks ("*") are reused to provide the indicator that language and
character set information is present and encoding is being used. A
single quote ("'") is used to delimit the character set and language
information at the beginning of the parameter value. Percent signs
("%") are used as the encoding flag, which agrees with RFC 2047.</p>
<p>Specifically, an asterisk at the end of a parameter name acts as an
indicator that character set and language information may appear at
the beginning of the parameter value. A single quote is used to
separate the character set, language, and actual value information in
the parameter value string, and an percent sign is used to flag
octets encoded in hexadecimal. For example:</p>
<pre><code> Content-Type: application/x-stuff;
title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A
</code></pre>
|
Tool for web server redirect management? <p>I'm considering rolling my own, but just in case there's a good piece of software already available, I'm asking here: Is there something that will provide an interface to webserver redirect configuration, and allow redirects to be managed by a fairly non-technical userbase. The following requirements must be fulfilled:</p>
<ul>
<li>Open-source</li>
<li>Apache</li>
<li>Support for internal / external redirects</li>
<li>Support for both web-server config and htaccess or meta-refresh files (for users who cannot restart the server)</li>
<li>Date range for validity</li>
</ul>
|
<p>You could use either a <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritemap" rel="nofollow">RewriteMap</a> script/program, or a static map (whichever is easiest for you/your users).</p>
<p>Check <a href="http://rewrite.drbacchus.com/rewritewiki/RewriteMap" rel="nofollow">http://rewrite.drbacchus.com/rewritewiki/RewriteMap</a> out for a basic example of the scripting capabilities. The performance hit is not as huge as you'd think because the process is launched one time only and stays alive until Apache is brought down. So be careful with resource management.</p>
|
What ReSharper 4+ live templates for C# do you use? <p>What ReSharper 4.0 templates for <strong>C#</strong> do you use?</p>
<p>Let's share these in the following format:</p>
<p><hr /></p>
<h2>[Title]</h2>
<p><em>Optional description</em> </p>
<p><strong>Shortcut:</strong> shortcut<br />
<strong>Available in:</strong> [AvailabilitySetting]</p>
<pre><code>// Resharper template code snippet
// comes here
</code></pre>
<p><strong>Macros properties</strong> (if present):</p>
<ul>
<li><strong>Macro1</strong> - Value - EditableOccurence</li>
<li><strong>Macro2</strong> - Value - EditableOccurence</li>
</ul>
<p><hr /></p>
<ul>
<li>One macro per answer, please!</li>
<li>Here are some samples for <a href="http://stackoverflow.com/questions/186970/what-resharper-40-templates-for-c-do-you-use#186978">NUnit test fixture</a> and <a href="http://stackoverflow.com/questions/186970/what-resharper-40-templates-for-c-do-you-use#186978">Standalone NUnit test case</a> that describe live templates in the suggested format.</li>
</ul>
|
<h2>Simple Lambda</h2>
<p>So simple, so useful - a little lambda:</p>
<p><strong>Shortcut</strong>: x</p>
<p><strong>Available</strong>: C# where expression is allowed.</p>
<pre><code>x => x.$END$
</code></pre>
<p>Macros: none.</p>
|
Large File Download - Connection With Server Reset <p>I have an asp.net website that allows the user to download largish files - 30mb to about 60mb. Sometimes the download works fine but often it fails at some varying point before the download finishes with the message saying that the connection with the server was reset.</p>
<p>Originally I was simply using Server.TransmitFile but after reading up a bit I am now using the code posted below. I am also setting the Server.ScriptTimeout value to 3600 in the Page_Init event.</p>
<pre><code>private void DownloadFile(string fname, bool forceDownload)
{
string path = MapPath(fname);
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
string type = "";
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".mp3":
type = "audio/mpeg";
break;
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".doc":
case ".rtf":
type = "Application/msword";
break;
}
}
if (forceDownload)
{
Response.AppendHeader("content-disposition",
"attachment; filename=" + name.Replace(" ", "_"));
}
if (type != "")
{
Response.ContentType = type;
}
else
{
Response.ContentType = "application/x-msdownload";
}
System.IO.Stream iStream = null;
// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
try
{
// Open the file.
iStream = new System.IO.FileStream(path, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
//Response.ContentType = "application/octet-stream";
//Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the HTML output.
Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
// Trap the error, if any.
Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
Response.Close();
}
}
</code></pre>
|
<p>Will</p>
<pre><code><configuration>
<system.web>
<httpRuntime executionTimeout="3600"/>
</system.web>
</configuration>
</code></pre>
<p>help anything?</p>
<p>The inner loop that writes the data seems a bit convoluted, I would at least change it to:</p>
<pre><code>int length;
while( Response.IsClientConnected &&
(length=iStream.Read(buffer,0,buffer.Length))>0 )
{
Response.OutputStream.Write(buffer,0,length);
Response.Flush();
}
</code></pre>
<p>There is no need to reallocate the buffer each round through the loop, you can simply re-use it after you have written it to the output.</p>
<p>A further improvement would be to use asyncronous IO but that is for another day.</p>
|
How do I return an exit code from a VBScript console application <p>I Have an old vbs script file being kicked off by an AutoSys job. Can I, and how do I, return an int return value to indicate success or failure?</p>
|
<p>Try:</p>
<pre><code>WScript.Quit n
</code></pre>
<p>Where n is the ERRORLEVEL you want to return</p>
|
Implement validation as a method or as a property? <p>I have an object that needs a test if the object data is valid. The validation itself would be called from the thread that instatiated the object, it looks like this:</p>
<pre><code> {
if (_step.Equals(string.Empty)) return false;
if (_type.Equals(string.Empty)) return false;
if (_setup.Equals(string.Empty)) return false;
return true;
}
</code></pre>
<p>Would it be better to implement this as a property, or as a method, and why? I have read the answers to a <a href="http://stackoverflow.com/questions/164023/what-guidelines-are-appropriate-for-determining-when-to-implement-a-class-membe">related question</a>, but I don't think this specific question is covered there.</p>
|
<p>My personal opinion here would be:</p>
<ul>
<li>If the "validate" method mutates the object in any way (which your example doesn't) then make it a method.</li>
<li>If the object remains un-changed after validation, make it a property.</li>
</ul>
|
Missing Workflow project templates in Visual Studio 2008 <p>I cannot add workflow item to my WPF project.</p>
<p>I create a new WPF project and want to add a sequential workflow. When I do "Add new item" there is no item template to select.</p>
<p>Any hints?</p>
|
<p>I don't think you can simply add a workflow to a WPF project. You need to create a WF project and build your workflow in that, then reference the WF project. </p>
|
Agile/Scrum resource planning cross projects <p>We have different steps in our planning for online webprojects:</p>
<p>1) Information Architecture</p>
<ul>
<li>Provides user stories</li>
<li>Provides wireframes</li>
</ul>
<p>2) Design</p>
<ul>
<li>Use Wireframes to develop a nice design</li>
</ul>
<p>3) Development</p>
<p>4) Testing</p>
<p>I know that working agile asks for dedicated teams. But it is impossible to have a dedicted IA until the end of the project. Because the projects are small developers are working in different teams. How do you plan resources when you know 50 small projects and 20 new projects are using different resources?</p>
<p>And is there a useful tool that can assist in this?</p>
|
<p>The situation where an IA (or a UI designer or anyone else for that matter) could not be committed for the whole length of the project is quite common.</p>
<p>However with Agile the problem is easily resolved: commit a resource for the length of the iteration where he is needed. I.e. if you need an architect for a spike or for a particular user story make sure that she could work with your team for the length of that iteration when the user story will be implemented. Later on if you will need her again do the same thing.</p>
<p>If your iteration is too long for that approach try committing the resource for the length of a particular user story or a spike only.</p>
|
Why use Ruby instead of Smalltalk? <p>Ruby is becoming <a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html" rel="nofollow">popular</a>, largely from the influence Ruby on Rails, but it feels like it is currently struggling through its adolescence. There are a lot of similarities between Ruby and Smalltalk -- <a href="http://ruby.gemstone.com/" rel="nofollow">maglev</a> is a testament to that. Despite having a more unusual syntax, Smalltalk has all (if not more) of the object-oriented beauty of Ruby. </p>
<p>From what I have read, Smalltalk seems to have Ruby beat on:</p>
<ul>
<li>Maturity (developed in the 1970's)</li>
<li>Stability</li>
<li>Commercial support</li>
<li><a href="http://www.wiresong.ca/monticello/" rel="nofollow">Distributed source control</a> (understands structure of code, not just text diffing)</li>
<li>Several <a href="http://en.wikipedia.org/wiki/Smalltalk#List_of_implementations" rel="nofollow">implementations of the VM</a></li>
<li>Cross-platform support</li>
<li>The <a href="http://www.seaside.st/" rel="nofollow">seaside web framework</a> as a <a href="http://www.sauria.com/blog/2005/11/10" rel="nofollow">strong alternative to Rails</a> </li>
</ul>
<p>It seems like Ruby is just reinventing the wheel. So, why don't Ruby developers use SmallTalk? <strong>What does Ruby have the Smalltalk doesn't?</strong> </p>
<p><em>For the record: I'm a Ruby guy with little to no experience in Smalltalk, but I'm starting to wonder why.</em></p>
<hr>
<p><strong>Edit:</strong> I think the ease-of-scripting issue has been addressed by <a href="http://en.wikipedia.org/wiki/GNU_Smalltalk" rel="nofollow">GNU Smalltalk</a>. As I understand it, this allows you to write smalltalk in regular old text files, and you no longer need to be in the Smalltalk IDE. You can then <a href="http://www.gnu.org/software/smalltalk/manual/html_node/Invocation.html#Invocation" rel="nofollow">run your scripts</a> with:</p>
<pre><code>gst smalltalk_file
</code></pre>
|
<p>I'm more of a Pythonista than a Ruby user, however the same things hold for Ruby for much the same reasons.</p>
<ul>
<li><p>The architecture of Smalltalk is somewhat insular whereas Python and Ruby were built from the ground up to facilitate integration. Smalltalk never really gained a body of hybrid application support in the way that Python and Ruby have, so the concept of 'smalltalk as embedded scripting language' never caught on.<br><br>As an aside, Java was not the easiest thing to interface with other code bases (JNI is fairly clumsy), but that did not stop it from gaining mindshare. IMO the interfacing argument is significant - ease of embedding hasn't hurt Python - but this argument only holds moderate weight as not all applications require this capability. Also, later versions of Smalltalk did substantially address the insularity.</p></li>
<li><p>The class library of most of the main smalltalk implementations (VisualWorks, VisualAge etc.) was large and had reputation for a fairly steep learning curve. Most key functionality in Smalltalk is hidden away somewhere in the class library, even basic stuff like streams and collections. The language paradigm is also something of a culture shock for someone not familiar with it, and the piecemeal view of the program presented by the browser is quite different to what most people were used to.<br><br>The overall effect is that Smalltalk got a (somewhat deserved) reputation for being difficult to learn; it takes quite a bit of time and effort to become a really proficient Smalltalk programmer. Ruby and Python are much easier to learn and to bring new programmers up to speed with.</p></li>
<li><p>Historically, mainstream Smalltalk implementations were quite expensive and needed exotic hardware to run, as can be seen <a href="http://groups.google.co.uk/group/net.lang.st80/browse_thread/thread/c35c4ad7fad659c4?hl=en#">this net.lang.st80 posting from 1983</a>. Windows 3.1, NT and '95 and OS/2 were the first mass market operating systems on mainstream hardware capable of supporting a Smalltalk implementation with decent native system integration. Previously, Mac or workstation hardware were the cheapest platforms capable of running Smalltalk effectively. Some implementations (particularly Digitalk) supported PC operating systems quite well and did succeed in gaining some traction.<br><br>However, OS/2 was never that successful and Windows did not achieve mainstream acceptance until the mid 1990s. Unfortunately this coincided with the rise of the Web as a platform and a large marketing push behind Java. Java grabbed most of the mindshare in the latter part of the 1990s, rendering Smalltalk a bit of an also-ran.</p></li>
<li><p>Ruby and Python work in a more conventional toolchain and are not tightly coupled to a specific development environment. While the Smalltalk IDEs I have used are nice enough I use PythonWin for Python development largely because it has a nice editor with syntax highlighting and doesn't get underfoot.<br><br>However, Smalltalk is was designed to be used with an IDE (in fact, Smalltalk was the original graphical IDE) and still has some nice features not replicated by other systems. Testing code with highlight and 'Show it' is still a very nice feature that I have never seen in a Python IDE, although I can't speak for Ruby.</p></li>
<li><p>Smalltalk was somewhat late coming to the web application party. Early efforts such as VisualWave were never terribly successful and it was not until Seaside came out that a decent web framework got acceptance in Smalltalk circles. In the meantime Java EE has had a complete acceptance lifecycle starting with raving fanboys promoting it and finally getting bored and moving onto Ruby ;-}<br><br>Ironically, Seaside is starting to get a bit of mindshare among the cognoscenti so we may find that Smalltalk rides that cycle back into popularity.</p></li>
</ul>
<p>Having said that, Smalltalk is a very nice system once you've worked out how to drive it. </p>
|
Preprocessing source code as a part of a maven build <p>I have a lot of Java source code that requires custom pre-processing. I'd like rid of it but that's not feasible right now so I'm stuck with it. Given that I have an unfortunate problem that shouldn't have existed in the first place, how do I solve it using maven? </p>
<p>(For the full story, I'm replacing a python-based build system with a maven one, so one improvement at a time please. Fixing the non-standard source code is harder, and will come later.)</p>
<p>Is it possible using any existing Maven plugins to actually alter the source files during compile time? (Obviously leaving the original, unprocessed code alone)</p>
<p>To be clear, by preprocessing I mean preprocessing in the same sense as antenna or a C compiler would preprocess the code, and by custom I mean that it's completely proprietary and looks nothing at all like C or antenna preprocessing.</p>
|
<p>This is something that is very doable and I've done something very similar in the past.</p>
<p>An example from a project of mine, where I used the antrun plug-in to execute an external program to process sources:</p>
<pre><code> <build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>process-sources</id>
<phase>process-sources</phase>
<configuration>
<tasks>
<!-- Put the code to run the program here -->
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</code></pre>
<p>Note the tag where I indicate the phase where this is run. Documentation for the lifecycles in Maven is <a href="http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html">here</a>. Another option is to actually write your own Maven plug-in that does this. It's a little more complex, but is also doable. You will still configure it similarly to what I have documented here.</p>
|
How to migrate a 3rd party web part from SharePoint 2 (2003) to SharePoint 3 (2007) <p>I am migrating a site from SharePoint 2 to 3 (in fact, from SharePoint Portal Server 2003 to Microsoft Office SharePoint Server 2007). There are a handful of 3rd party web parts and since this is a migration, not an in-place upgrade, I need to install these web parts on the new farm.</p>
<p>How do I do this, given that I have the packaged up web parts as provided by the SharePoint Configuration Analyzer in the form of cab files? Can I simply deploy these cab files somehow, even though they are not packaged as solutions? Or do I need to pull the cab files apart and repackage them as solutions? Or do I need to get new versions of the web parts, written for SharePoint 3, and maybe edit the pages that use them?</p>
|
<p>You can still install .CAB files with WSSv3 using the same STSADM command as you used in WSSv2</p>
<pre><code>STSADM -o addwppack -filename <filename.CAB>
</code></pre>
<p>However, maybe you should get in touch with the providers of these 3rd party web parts? Perhaps they will have versions for WSSv3 packaged as WSP's? </p>
<p>Also can you be sure that the WSSv2 versions will actually work on WSSv3? They often do, but not always.</p>
|
Can a WinForms app be configured to run as "x86" without recompiling? <p>Can a WinForms app compiled for "Any CPU" be configured to run as "x86" on a 64-bit server without recompiling the app? Specifically, I'm looking for an app.config setting or Control Panel applet to accomplish this end. All the customer's clients are x86, but the server is x64, and we like to install the WinForms app on the server for administrators to configure and monitor the system. We would much rather not recompile just for the server.</p>
|
<p>From <a href="http://www.request-response.com/blog/PermaLink,guid,34966ef8-3142-46b2-84e0-372b5c36ddcc.aspx" rel="nofollow">http://www.request-response.com/blog/PermaLink,guid,34966ef8-3142-46b2-84e0-372b5c36ddcc.aspx</a></p>
<blockquote>
<p>You can, however, control and
override this default behaviour even
after your code has been compiled.
There's a handy tool called
corflags.exe present in the SDK that
allows you to force 'anycpu' compiled
code to use 32-bit process in 64-bit
world.</p>
</blockquote>
<p>The usage of this utility is found here <a href="http://msdn.microsoft.com/en-us/library/ms164699(VS.80).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms164699(VS.80).aspx</a></p>
|
Default parameters with C++ constructors <p>Is it good practice to have a class constructor that uses default parameters, or should I use separate overloaded constructors? For example:</p>
<pre><code>// Use this...
class foo
{
private:
std::string name_;
unsigned int age_;
public:
foo(const std::string& name = "", const unsigned int age = 0) :
name_(name),
age_(age)
{
...
}
};
// Or this?
class foo
{
private:
std::string name_;
unsigned int age_;
public:
foo() :
name_(""),
age_(0)
{
}
foo(const std::string& name, const unsigned int age) :
name_(name),
age_(age)
{
...
}
};
</code></pre>
<p>Either version seems to work, e.g.:</p>
<pre><code>foo f1;
foo f2("Name", 30);
</code></pre>
<p>Which style do you prefer or recommend and why?</p>
|
<p>Definitely a matter of style. I prefer constructors with default parameters, so long as the parameters make sense. Classes in the standard use them as well, which speaks in their favor.</p>
<p>One thing to watch out for is if you have defaults for all but one parameter, your class can be implicitly converted from that parameter type. Check out <a href="http://stackoverflow.com/questions/174349/forcing-single-argument-constructors-to-be-explicit-in-c">this thread</a> for more info.</p>
|
Copy tables from one database to another in SQL Server <p>I have a database called foo and a database called bar. I have a table in foo called tblFoobar that I want to move (data and all) to database bar from database foo. What is the SQL statement to do this?</p>
|
<p>SQL Server Management Studio's "Import Data" task (right-click on the DB name, then tasks) will do most of this for you. Run it from the database you want to copy the data into.</p>
<p>If the tables don't exist it will create them for you, but you'll probably have to recreate any indexes and such. If the tables do exist, it will append the new data by default but you can adjust that (edit mappings) so it will delete all existing data.</p>
<p>I use this all the time and it works fairly well.</p>
|
Relocate JSF-generated javascript <p>I am using lots of commandLinks in my app. For them to work, JSF generates some wild Javascript ( <code>function dpf(f) {var adp...</code> ). Sadly, the script-tag destroys my layout. (It really does - I am sure about that).</p>
<p>Is there a way to force JSF to generate the script-tag somewhere else?</p>
|
<p>Maybe you can try to externalize your Javascript.
Instead of putting the Javascript code within your page, it will only include a script tag that points to a Javascript file.
To do that, modify your web.xml file to have that:</p>
<pre><code><context-param>
<param-name>com.sun.faces.externalizeJavaScript</param-name>
<param-value>true</param-value>
</context-param>
</code></pre>
|
Adding click event to button to fire javascript, through VB.NET <p>I have an ASP.NET page which pulls a set of images from a database table, and using an enumerator, goes through all of them and displays then.</p>
<p>This all happens in the codebehind (VB.NET), where the code adds the placeholder and some controls inside tables (tables inside the placeholder).</p>
<p>I've added a button to this placeholder (inside a table cell), all programatically, but how can I add a click event to the button programatically? I want to fire a javascript (lightbox) which shows a large preview of the image (this works when the user clicks a small image, which invokes a string hyperlink on the code that points to the javascript).</p>
|
<p><code>cmdMyButton.attributes.add("onclick", "alert('hello');")</code> ?</p>
|
DBCC CHECKIDENT on a temporary table throwing permissions error for wrong user <p>I'm logged into a SQL Server 2005 database as a non-sa user, 'bhk', that is a member of the 'public' server role only. The following code tries to execute within a stored procedure called by user 'bhk'. This line of code...</p>
<pre><code>TRUNCATE TABLE #Table1
DBCC CHECKIDENT('#Table1', RESEED, @SequenceNumber) WITH NO_INFOMSGS
</code></pre>
<p>causes this error...</p>
<blockquote>
<p>User 'guest' does not have permission
to run DBCC CHECKIDENT for object<br />
'#Table1__00000000007F'.</p>
</blockquote>
<p>I'm aware of the permissions required to run DBCC CHECKIDENT...<br />
<strong>*Caller must own the table</strong>, or be a member of the sysadmin fixed server role, the db_owner fixed database role, or the db_ddladmin fixed database role.*</p>
<p>So I have two questions:</p>
<ol>
<li>Since 'bhk' is calling a stored
procedure that creates a temporary
table, shouldn't 'bhk' be the owner
and be allowed to run DBCC
CHECKIDENT?</li>
<li>Why does the error
message return that user 'guest'
doesn't have permission? To my knowledge, I'm not
logged in as 'guest'.</li>
</ol>
<p>Any help would be greatly appreciated.</p>
|
<p>Here is an alternate solution, that may work if you need to re-seed with a sequence number of more than 1.</p>
<pre><code>TRUNCATE #Table1
SET IDENTITY_INSERT #Table1 ON
INSERT INTO #Table1 (TableID) -- This is your primary key field
VALUES (@SequenceNumber - 1)
SET IDENTITY_INSERT #Table1 OFF
DELETE FROM #Table1
</code></pre>
<p>What this is doing is to set the IDENTITY_INSERT on your temporary table, to allow you to add a row with an explicit ID. You can then delete this row, but further inserts should start from the last sequence number.</p>
|
Why does GCC-Windows depend on cygwin? <p>I'm not a C++ developer, but I've always been interested in compilers, and I'm interested in tinkering with some of the GCC stuff (particularly LLVM).</p>
<p>On Windows, GCC requires a POSIX-emulation layer (cygwin or MinGW) to run correctly.</p>
<p>Why is that?</p>
<p>I use lots of other software, written in C++ and cross-compiled for different platforms (Subversion, Firefox, Apache, MySQL), and none of them require cygwin or MinGW.</p>
<p>My understanding about C++ best-practice programming is that you can write reasonably platform-neutral code and deal with all the differences during the compilation process.</p>
<p>So what's the deal with GCC? Why can't it run natively on Windows?</p>
<p><hr /></p>
<p>EDIT:</p>
<p>Okay, the two replies so far say, basically, "GCC uses the posix layer because it uses the posix headers".</p>
<p>But that doesn't really answer the question.</p>
<p>Let's say I already have a set of headers for my favorite standard library. Why would I still need the posix headers?</p>
<p>Does GCC require cygwin/mingw to actually <em>RUN</em>?</p>
<p>Or does it only need the emulation layer for headers and libraries? If so, why can't I just give it a "lib" directory with the required resources?</p>
<p><hr /></p>
<p>EDIT AGAIN:</p>
<p>Okay, I'll try again to clarify the question...</p>
<p>I also write code in <a href="http://digitalmars.com/d">the D Programming Language</a>. The official compiler is named "dmd" and there are official compiler binaries for both Windows and linux.</p>
<p>The Windows version doesn't require any kind of POSIX emulation. And the Linux version doesn't require any kind of Win32 emulation. If the compiler has assumptions about its environment, it hides those assumptions pretty well.</p>
<p>Of course, I have to tell the compiler where to find the standard library and where to find libraries to statically or dynamically link against.</p>
<p>GCC, by contrast, insists on pretending it's operating within a posix environment, and it asks ME to humor those assumptions by setting up an emulation layer.</p>
<p>But what, exactly, within GCC relies on that layer? Is it just looking for stdlib headers, and it assumes it'll find those headers within "/usr/lib"?</p>
<p>If that's the case, shouldn't I just be able to tell it to look in "C:/gcc/lib" to find those header files?</p>
<p>Or does GCC itself rely on the POSIX libraries to access the file system (and to do other low-level stuff)? If that's the case, then I wonder why they don't just statically link with their favorite windows POSIX libraries. Why require the user to set up the dependencies, when they could build those dependencies right into the application?</p>
|
<p>Actually, the question premise is wrong: <a href="http://www.mingw.org/">MinGW</a> GCC does <strong>NOT</strong> require Cygwin.</p>
<p>You will see you don't need Cygwin at all. It runs natively on Windows (32-bit, at least). Both the toolchain and the produced binaries are independent of Cygwin.</p>
<p>The MinGW compilers available in Cygwin are different: they are built on the Cygwin platform, to generate code which does not depend on the Cygwin runtime. The compilers themselves do depend on Cygwin in that case. But that's because you installed them from Cygwin.</p>
|
Mathematics and Game Programming <p>I want to program graphical 2D games more complex than the basic 2D stuff I already know. I don't want to do 3D programming. Just more complex 2D stuff. I dropped high school before I could learn a lot of stuff so I walked away with enough algebra knowledge to balance my checkbook and do some light 2D Cartesian programming.</p>
<p>Are there any good resources out there for a guy with a limited attention span (say 20 minutes apiece for a subject I'm keenly interested in) to learn, gradually, how to do something more useful with math in programming?</p>
|
<p>You need to be competent in Trigonometry: <a href="http://en.wikipedia.org/wiki/Trigonometry">Wikipedia</a> and <a href="http://mathworld.wolfram.com/topics/Trigonometry.html">Mathworld</a></p>
<p>Even though you don't wish to do 3D programming, 2D games also use vectors and matrices. (from Linear Algebra)</p>
<p>Linear Algebra resources: <a href="http://en.wikipedia.org/wiki/Linear_algebra">Wikepedia</a> and <a href="http://mathworld.wolfram.com/LinearAlgebra.html">Mathworld</a></p>
<p>One point that will save you a lot of effort in Trig programming is realizing the need for the <a href="http://en.wikipedia.org/wiki/Atan2">atan2()</a> function, rather than the atan() function. This is important when determining the direction between two points.</p>
<p>Being able to move between various coordinate systems is a big plus. This will come with experience. Two common things that trip people up are:</p>
<p>a) Most screen systems place the origin (0,0) in the upper left corner, with the positive x axis extending to the right and the positive y axis extending down. Standard Cartesian coordinates suppose the origin of Quadrant 1 (where x and y are always positive or zero) in the lower left. This requires a programmer to 'flip' the y orientation at some stage.</p>
<p>b) Typical geography places 0 degrees as North and positive degrees sweep clockwise. All the Trig functions place 0 degrees as East with positive degrees sweeping counter-clockwise. </p>
<p>Finally, even though we tend to think in degrees, real libraries will use radians.
A best practice is to store angles as radians (in 'math' orientation rather than 'geo') and convert things when displaying debug information..</p>
|
Can I specify my explicit type comparator inline? <p>So .NET 3.0/3.5 provides us with lots of new ways to query, sort, and manipulate data, thanks to all the neat functions supplied with LINQ. Sometimes, I need to compare user-defined types that don't have a built-in comparison operator. In many cases, the comparison is really simple -- something like foo1.key ?= foo2.key. Rather than creating a new IEqualityComparer for the type, can I simply specify the comparison inline using anonymous delegates/lambda functions? Something like:</p>
<pre><code>var f1 = ...,
f2 = ...;
var f3 = f1.Except(
f2, new IEqualityComparer(
(Foo a, Foo b) => a.key.CompareTo(b.key)
) );
</code></pre>
<p>I'm pretty sure the above doesn't actually work. I just don't want to have to make something as "heavy" as a whole class just to tell the program how to compare apples to apples.</p>
|
<p>My <a href="http://pobox.com/~skeet/csharp/miscutil">MiscUtil</a> library contains a ProjectionComparer to build an IComparer<T> from a projection delegate. It would be the work of 10 minutes to make a ProjectionEqualityComparer to do the same thing.</p>
<p>EDIT: Here's the code for ProjectionEqualityComparer:</p>
<pre><code>using System;
using System.Collections.Generic;
/// <summary>
/// Non-generic class to produce instances of the generic class,
/// optionally using type inference.
/// </summary>
public static class ProjectionEqualityComparer
{
/// <summary>
/// Creates an instance of ProjectionEqualityComparer using the specified projection.
/// </summary>
/// <typeparam name="TSource">Type parameter for the elements to be compared</typeparam>
/// <typeparam name="TKey">Type parameter for the keys to be compared,
/// after being projected from the elements</typeparam>
/// <param name="projection">Projection to use when determining the key of an element</param>
/// <returns>A comparer which will compare elements by projecting
/// each element to its key, and comparing keys</returns>
public static ProjectionEqualityComparer<TSource, TKey> Create<TSource, TKey>(Func<TSource, TKey> projection)
{
return new ProjectionEqualityComparer<TSource, TKey>(projection);
}
/// <summary>
/// Creates an instance of ProjectionEqualityComparer using the specified projection.
/// The ignored parameter is solely present to aid type inference.
/// </summary>
/// <typeparam name="TSource">Type parameter for the elements to be compared</typeparam>
/// <typeparam name="TKey">Type parameter for the keys to be compared,
/// after being projected from the elements</typeparam>
/// <param name="ignored">Value is ignored - type may be used by type inference</param>
/// <param name="projection">Projection to use when determining the key of an element</param>
/// <returns>A comparer which will compare elements by projecting
/// each element to its key, and comparing keys</returns>
public static ProjectionEqualityComparer<TSource, TKey> Create<TSource, TKey>
(TSource ignored,
Func<TSource, TKey> projection)
{
return new ProjectionEqualityComparer<TSource, TKey>(projection);
}
}
/// <summary>
/// Class generic in the source only to produce instances of the
/// doubly generic class, optionally using type inference.
/// </summary>
public static class ProjectionEqualityComparer<TSource>
{
/// <summary>
/// Creates an instance of ProjectionEqualityComparer using the specified projection.
/// </summary>
/// <typeparam name="TKey">Type parameter for the keys to be compared,
/// after being projected from the elements</typeparam>
/// <param name="projection">Projection to use when determining the key of an element</param>
/// <returns>A comparer which will compare elements by projecting each element to its key,
/// and comparing keys</returns>
public static ProjectionEqualityComparer<TSource, TKey> Create<TKey>(Func<TSource, TKey> projection)
{
return new ProjectionEqualityComparer<TSource, TKey>(projection);
}
}
/// <summary>
/// Comparer which projects each element of the comparison to a key, and then compares
/// those keys using the specified (or default) comparer for the key type.
/// </summary>
/// <typeparam name="TSource">Type of elements which this comparer
/// will be asked to compare</typeparam>
/// <typeparam name="TKey">Type of the key projected
/// from the element</typeparam>
public class ProjectionEqualityComparer<TSource, TKey> : IEqualityComparer<TSource>
{
readonly Func<TSource, TKey> projection;
readonly IEqualityComparer<TKey> comparer;
/// <summary>
/// Creates a new instance using the specified projection, which must not be null.
/// The default comparer for the projected type is used.
/// </summary>
/// <param name="projection">Projection to use during comparisons</param>
public ProjectionEqualityComparer(Func<TSource, TKey> projection)
: this(projection, null)
{
}
/// <summary>
/// Creates a new instance using the specified projection, which must not be null.
/// </summary>
/// <param name="projection">Projection to use during comparisons</param>
/// <param name="comparer">The comparer to use on the keys. May be null, in
/// which case the default comparer will be used.</param>
public ProjectionEqualityComparer(Func<TSource, TKey> projection, IEqualityComparer<TKey> comparer)
{
if (projection == null)
{
throw new ArgumentNullException("projection");
}
this.comparer = comparer ?? EqualityComparer<TKey>.Default;
this.projection = projection;
}
/// <summary>
/// Compares the two specified values for equality by applying the projection
/// to each value and then using the equality comparer on the resulting keys. Null
/// references are never passed to the projection.
/// </summary>
public bool Equals(TSource x, TSource y)
{
if (x == null && y == null)
{
return true;
}
if (x == null || y == null)
{
return false;
}
return comparer.Equals(projection(x), projection(y));
}
/// <summary>
/// Produces a hash code for the given value by projecting it and
/// then asking the equality comparer to find the hash code of
/// the resulting key.
/// </summary>
public int GetHashCode(TSource obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
return comparer.GetHashCode(projection(obj));
}
}
</code></pre>
<p>And here's a sample use:</p>
<pre><code>var f3 = f1.Except(f2, ProjectionEqualityComparer<Foo>.Create(a => a.key));
</code></pre>
|
How Do You Handle Validation In Silverlight? <p>How have you decided to handle data/control validation in your silverlight applications? </p>
|
<p>You can throw and capture data validation exceptions.</p>
<p>To manage both of these types of errors need to take 3 steps:</p>
<ol>
<li>Identify the error handler either in the control or higher in the visiblity hierarchy (e.g., a container; in this case the grid that contains the text box)</li>
<li>Set NotifyOnValidationError and ValidateOnException to true. The latter tells the Binding Engine to create a validation error event when an exception occurs. The former tells the Binding Engine to raise the BindingValidationError event when a validation error occurs.</li>
<li>Create the event handler named in step 1.</li>
</ol>
<p>Taken from <a href="http://silverlight.net/blogs/jesseliberty/archive/2008/10/13/data-binding-data-validation.aspx" rel="nofollow">here</a>.</p>
<p>Sample code:</p>
<pre><code>// page.xaml.cs
private bool clean = true;
private void LayoutRoot_BindingValidationError(
object sender, ValidationErrorEventArgs e )
{
if ( e.Action == ValidationErrorEventAction.Added )
{
QuantityOnHand.Background = new SolidColorBrush( Colors.Red );
clean = false;
}
else if ( e.Action == ValidationErrorEventAction.Removed )
{
QuantityOnHand.Background = new SolidColorBrush( Colors.White );
clean = true;
}
}
// page.xaml
<Grid x:Name="LayoutRoot" Background="White" BindingValidationError="LayoutRoot_BindingValidationError" >
<TextBox x:Name="QuantityOnHand"
Text="{Binding Mode=TwoWay, Path=QuantityOnHand,
NotifyOnValidationError=true, ValidatesOnExceptions=true }"
VerticalAlignment="Bottom"
HorizontalAlignment="Left"
Height="30" Width="90"red
Grid.Row="4" Grid.Column="1" />
// book.cs
public int QuantityOnHand
{
get { return quantityOnHand; }
set
{
if ( value < 0 )
{
throw new Exception( "Quantity on hand cannot be negative!" );
}
quantityOnHand = value;
NotifyPropertyChanged( "QuantityOnHand" );
} // end set
}
</code></pre>
|
What's the best version control system for handling projects with graphics? <p>I'm part of a small team (usually just two people), I handle the code, he handles the graphic design. In the past I've used CVS to handle version control of the code files, and while we've included the graphics in the repository, he hasn't derived nearly as much value from it as I have. </p>
<p>Are there other packages that provide the better features for supporting graphics? The system would need to have an easy to use GUI interface, as I don't think it's fair to expect a graphic designer to learn command-line tools.</p>
<p>Additional aspect: The client software needs to run smoothly on OS X (for the designer), and Windows (for the programmer).</p>
|
<p>I would recommend Subversion with TortoiseSVN. It integrates into Windows Explorer and allows you to do everything you need from the context menu (update, commit, branch, merge... anything). It can handle all kinds of files, and best of all, both Subversion and TortoiseSVN are free (along with the other SVN tools).</p>
|
How do you execute a stored procedure using Castle ActiveRecord? <p>I believe there is a discussion on this very topic somewhere on the net but I lost the url and I am unable to find it via googling.</p>
<p>What I might try right now would be:</p>
<pre><code>ISessionFactoryHolder factoryHolder = ActiveRecordMediator<EntityClass>.GetSessionFactoryHolder();
ISession session = factoryHolder.CreateSession(typeof(EntityClass));
try
{
IDbCommand cmd = session.Connection.CreateCommand();
cmd.CommandText = "spName";
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
}
finally
{
factoryHolder.ReleaseSession(session);
}
</code></pre>
<p>However, I am not quite sure if this is the correct way to do this or if perhaps a better way exists.</p>
|
<p>This works for me (stored procedure with params and dynamic result table):</p>
<pre><code>// get Connection
System.Data.IDbConnection con = ActiveRecordMediator.GetSessionFactoryHolder()
.GetSessionFactory(typeof(Autocomplete))
.ConnectionProvider.GetConnection();
// set Command
System.Data.IDbCommand cmd = con.CreateCommand();
cmd.CommandText = "name_of_stored_procedure";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
// set Parameter of Stored Procedure
System.Data.SqlClient.SqlParameter param = new System.Data.SqlClient.SqlParameter("@parameter_name", System.Data.SqlDbType.NVarChar);
param.Value = "value_of_parameter";
((System.Data.SqlClient.SqlParameterCollection)cmd.Parameters).Add(param);
// call Stored Procedure (without getting result)
cmd.ExecuteNonQuery();
// ... or read results
System.Data.SqlClient.SqlDataReader r = (System.Data.SqlClientSqlDataReader)cmd.ExecuteReader();
while(r.Read()) {
System.Console.WriteLine("result first col: " + r.GetString(0));
}
</code></pre>
|
Expose Java class as SOAP WebService - how? <p>I am looking for a framework to turn given Java class into WebService (may be with some limitations on method parameters etc)</p>
<p>Thanks</p>
|
<p>You can use <a href="http://ws.apache.org/axis2/" rel="nofollow">axis2</a>, or <a href="http://xfire.codehaus.org/" rel="nofollow">xfire</a>. I'm sure there are other ways also, but these are the two that I've used.</p>
|
How do I add an extra source directory that will be used by the maven-jxr-plugin? <p>I'm using the build-helper-maven-plugin to add it to my build, but I'd
like to see the XREF source for this extra source directory as well.</p>
<p>FYI:</p>
<p><a href="http://maven.apache.org/plugins/maven-jxr-plugin/index.html" rel="nofollow">maven-jxr-plugin</a> - The JXR plugin produces a cross-reference of the project's sources. The generated reports make it easier for the user to reference or find specific lines of code. It is also handy when used with the PMD plugin for referencing errors found in the code.</p>
<p><a href="http://mojo.codehaus.org/build-helper-maven-plugin/index.html" rel="nofollow">build-helper-maven-plugin</a> - This plugin contains various small independent goals to assist with Maven build lifecycle.</p>
|
<p>You can tell JXR what files to index using a file pattern, following Ant guidelines. For example, to include all java files in src/main/java and all source in src/main/java2, the following configuration in your file should work:</p>
<pre><code><project>
...
<reporting>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
<configuration>
...
<includes>
<include>src/main/java/**/*.java</include>
<include>src/main/java2/**/*.java</include>
<includes>
...
</configuration>
</plugin>
</plugins>
...
</reporting>
...
</project>
</code></pre>
|
How to format a string as a telephone number in C# <p>I have a string "1112224444' it is a telephone number. I want to format as 111-222-4444 before I store it in a file. It is on a datarecord and I would prefer to be able to do this without assigning a new variable.</p>
<p>I was thinking:</p>
<pre><code>String.Format("{0:###-###-####}", i["MyPhone"].ToString() );
</code></pre>
<p>but that does not seem to do the trick.</p>
<p>** UPDATE **</p>
<p>Ok. I went with this solution</p>
<pre><code>Convert.ToInt64(i["Customer Phone"]).ToString("###-###-#### ####")
</code></pre>
<p>Now its gets messed up when the extension is less than 4 digits. It will fill in the numbers from the right. so</p>
<pre><code>1112224444 333 becomes
11-221-244 3334
</code></pre>
<p>Any ideas?</p>
|
<p>From a <a href="http://blog.stevex.net/index.php/string-formatting-in-csharp/">good page</a> full of examples:</p>
<pre><code>String.Format("{0:(###) ###-####}", 8005551212);
This will output "(800) 555-1212".
</code></pre>
<p>Although a regex may work even better, keep in mind the old programming quote:</p>
<blockquote>
<p>Some people, when confronted with a
problem, think âI know, Iâll use
regular expressions.â Now they have
two problems.<br>
--Jamie Zawinski, in comp.lang.emacs</p>
</blockquote>
|
Recommendations for converting raster images to vector graphics <p>If a person is looking to batch convert a large number of raster images into vector graphics, are there any tools out there that do that well?</p>
<p>For an example, think of just about any diagram that has standard shapes (ellipses, rectangles) and text.</p>
|
<p><a href="http://www.inkscape.org/doc/tracing/tutorial-tracing.html">Inkscape uses</a> the Potrace engine to trace raster graphics. You usually have to play with it a bit to get useful output, but it does surprisingly well and is easy to use.</p>
|
Any way to transfer value from one cell to another? <p>Is there any way in the SQL language or in MySQL (or other DBMA) to transfer a value from one cell to another? For example, say there is a table called user_cars with the following structure:</p>
<pre><code>|id| |user_name| |num_cars|
</code></pre>
<p>Bob has 5 cars, and John has 3 cars. Is there any way to in one query subtract 2 cars from Bob and add 2 to John? I know this can be done with two update queries, but I'd just like to know if there was a more efficient way.</p>
|
<p>For Oracle you could do this. Don't know if there is an equivalent in mysql. Obviously this particular statement is very specific to the example you stated.</p>
<pre><code> UPDATE user_cars
SET num_cars = num_cars +
CASE WHEN user_name='Bob' THEN -2
WHEN user_name='John' THEN +2
END
WHERE user_name IN ( 'Bob', 'John' )
</code></pre>
|
How to launch multiple Internet Explorer windows/tabs from batch file? <p>I would like a batch file to launch two separate programs then have the command line window close. Actually, to clarify, I am launching Internet Explorer with two different URLs.</p>
<p>So far I have something like this:</p>
<pre><code>start "~\iexplore.exe" "url1"
start "~\iexplore.exe" "url2"
</code></pre>
<p>What I get is one instance of Internet Explorer with only the second URL loaded. Seems the second is replacing the second. I seem to remember a syntax where I would load a new command line window and pass the command to execute on load, but can't find the reference.</p>
<p>As a second part of the question: what is a good reference URL to keep for the times you need to write a quick batch file?</p>
<p>Edit: I have marked an answer, because it does work. I now have two windows open, one for each URL. (thanks!) The funny thing is that without the /d approach using my original syntax I get different results based on whether I have a pre-existing Internet Explorer instance open. </p>
<ul>
<li>If I do I get two new tabs added for
my two URLs (sweet!) </li>
<li>If not I get only one final tab for the second URL I passed in.</li>
</ul>
|
<p>Try this in your batch file:</p>
<pre><code>@echo off
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.google.com
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.yahoo.com
</code></pre>
|
How to use C# to sanitize input on an html page? <p>Is there a library or acceptable method for sanitizing the input to an html page?</p>
<p>In this case I have a form with just a name, phone number, and email address. </p>
<p>Code must be C#.</p>
<p>For example:</p>
<pre><code>"<script src='bobs.js'>John Doe</script>" should become "John Doe"
</code></pre>
|
<p>If by sanitize you mean REMOVE the tags entirely, the RegEx example referenced by Bryant is the type of solution you want.</p>
<p>If you just want to ensure that the code DOESN'T mess with your design and render to the user. You can use the HttpUtility.HtmlEncode method to prevent against that!</p>
|
What is the correct LINQtoSQL-ish way to do a table truncate? <p>I have a project with a formidable data access layer using LinqtoSQL for just about anything touching our databases. I needed to build a helper class that bridges some common crud operations from CLSA objects to LinqToSql ones. Everything has been operating swimmingly until I needed to do a truncate on a table and all I had were âdeleteâ methods.</p>
<p>Uh-oh. A quick search reveals that some people are using YourContext.ExecuteCommand(), which is nice and all, but I am trying to go ât-sql-lessâ as much as possible these days.</p>
<p>Is there a LINQ way to perform a <a href="http://msdn.microsoft.com/en-us/library/aa260621(SQL.80).aspx" rel="nofollow">truncate on a table</a>? Or am I just <a href="http://en.wikipedia.org/wiki/Clueless_(film)" rel="nofollow">clueless</a>?</p>
|
<p>This is not possible without doing a custom T-SQL query. Doing a .Delete() and SubmitChanges afterwords would, as you probably already know, result in a DELETE statement.</p>
<p>Of course you could create a stored procedure that truncates the table, and then call the procedure from LINQ, but that isn't really what you're looking for I believe.</p>
|
How To Get Photo IDs from Flickr API? <p>I am trying to use JQUERY to grab photos from a Flickr group. I can get back valid JSON, but can't figure out how to get access to the actual photos. The JSON that is returned contains an empty list where I would expect photos.</p>
<p>So when I plug this into the browser:</p>
<pre><code>http://api.flickr.com/services/rest?method=flickr.groups.pools.getPhotos&api_key=2c4df0060561b03151cda6a1xxxx&format=json&group_id=919043@N22&jsoncallback=?
</code></pre>
<p>The json that I get back is this:</p>
<pre><code> jsonFlickrApi({"photos":{"page":1, "pages":1, "perpage":100, "total":"6", "photo":[]}, "stat":"ok"})
</code></pre>
<p>It seems like it knows that there are six photos, but the photo list is empty. I assume I am missing a step. Any help would be appreciated.</p>
|
<p>I just pasted that same url into Firefox (using my own Flickr api key) and it worked fine, I got (anonymized):</p>
<pre><code>jsonFlickrApi(
{"photos": {"page":1, "pages":1, "perpage":100, "total":"6", "photo":
[{"id": "292744xxxx", "owner":"11363xxx@xxx", "secret":"f084efxxxx",
"server":"3xxx", "farm":4, "title":"Pink Floyd", "ispublic":1,
"isfriend":0, "isfamily":0, "ownername":"moexxxxx", "dateadded":"122358xxxx"},
{"id":
...
}
...
},
"stat":"ok"})
</code></pre>
|
Good language & framework for cross platform (windows & mac) desktop application <p>The last cross platform desktop development I did was Java/Swing. What about flex?</p>
|
<p>Don't do it. If you need to go cross-platform, write the main guts of your application in a business logic layer that doesn't depend on any GUI framework and then use the native platform API to finish each app.</p>
<p>Your users will thank you.</p>
|
Replace in multiple files - graphical tool for Linux <p>It needs to be graphical. No sed, awk, grep, perl, whatever. I know how to use those and I do use them now, but I need to cherry-pick each replace in 300+ files.</p>
<p>I want a tool where I can:</p>
<ul>
<li>type a search string</li>
<li>type a replace string</li>
<li>select a directory and file extension</li>
</ul>
<p>and it would recursively go into each file in that directory and its sub-directories, open it and scroll to the place where search string is and offer two options:</p>
<ul>
<li>replace (and find next)</li>
<li>find next</li>
</ul>
<p>Nothing more. Reg.exp. support is a plus, but not required.</p>
<p>SOLVED: Regexxer is exactly what I needed. In case someone needs it on Slackware, <a href="http://swoes.blogspot.com/2008/10/regexxer-on-slackware-121.html">here's</a> what you need to download and how to compile it (choosing correct version of each dependency can be a PITA)</p>
|
<p>I think <a href="http://regexxer.sourceforge.net/">regexxer</a> is exactly what you're looking for:</p>
<h3><a href="http://regexxer.sourceforge.net/">Regexxer</a></h3>
<blockquote>
<p>regexxer is a nifty GUI search/replace tool featuring Perl-style regular
expressions. If you need project-wide substitution and youâre tired of
hacking sed command lines together, then you should definitely give it a try.</p>
</blockquote>
<p>See also the screenshot, looks a lot like what you're describing: </p>
<p><a href="http://regexxer.sourceforge.net/images/regexxer-screenshot.png"><img src="http://regexxer.sourceforge.net/images/regexxer-screenshot-thumb.jpg" alt="screenshot" /></a></p>
|
Problem using SQLite :memory: with NHibernate <p>I use NHibernate for my dataacess, and for awhile not I've been using SQLite for local integration tests. I've been using a file, but I thought I would out the :memory: option. When I fire up any of the integration tests, the database seems to be created (NHibernate spits out the table creation sql) but interfacting with the database causes an error.</p>
<p>Has anyone every gotten NHibernate working with an in memory database? Is it even possible? The connection string I'm using is this:</p>
<pre><code>Data Source=:memory:;Version=3;New=True
</code></pre>
|
<p>A SQLite memory database only exists as long as the connection to it remains open. To use it in unit tests with NHibernate:<br />
1. Open an ISession at the beginning of your test (maybe in a [SetUp] method).<br />
2. Use the connection from that session in your SchemaExport call.<br />
3. Use that same session in your tests.<br />
4. Close the session at the end of your test (maybe in a [TearDown] method).</p>
|
Detect GCC compile-time flags of a binary <p>Is there a way to find out what gcc flags a particular binary was compiled with?</p>
|
<p>A quick look at the GCC documentation doesn't turn anything up.</p>
<p>The Boost guys are some of the smartest C++ developers out there, and they <a href="http://www.boost.org/doc/libs/1%5F36%5F0/more/getting%5Fstarted/unix-variants.html#library-naming">resort</a> to naming <a href="http://www.boost.org/doc/libs/1%5F36%5F0/more/getting%5Fstarted/windows.html#library-naming">conventions</a> because this is generally not possible any other way (the executable could have been created in any number of languages, by any number of compiler versions, after all). </p>
<p><hr></p>
<p>(Added much later): <a href="http://dberkholz.wordpress.com/2007/10/12/new-gcc-hotness/?referer=sphere%5Frelated%5Fcontent/">Turns out GCC has this feature in 4.3 if asked for when you compile the code</a>:</p>
<blockquote>
<p>A new command-line switch -frecord-gcc-switches ... causes the command line that was used to invoke the compiler to be recorded into the object file that is being created. The exact format of this recording is target and binary file format dependent, but it usually takes the form of a note section containing ASCII text.</p>
</blockquote>
|
How to put WPF Tab Control tabs on the side <p>I am trying to create a Tab Control in WPF that has the tabs arranged down the right side of the control, with the text rotated 90 degrees The look is similar to those plastic tabs you can buy and use in a notebook. I have tried changing the TabStripPlacement to Right, but it just stacks the tabs up on the top right side of the control - not at all what I had in mind.</p>
|
<p>The effect I believe you are seeking is achieved by providing a HeaderTemplate for the TabItem's in you Tab collection.</p>
<pre><code><TabControl TabStripPlacement="Right">
<TabControl.Resources>
<Style TargetType="{x:Type TabItem}">
<Setter Property="Padding" Value="4" />
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<ContentPresenter Content="{TemplateBinding Content}">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="90" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.Resources>
<TabItem Header="Tab Item 1" />
<TabItem Header="Tab Item 2" />
<TabItem Header="Tab Item 3" />
<TabItem Header="Tab Item 4" />
</TabControl>
</code></pre>
<p>Hope this helps!</p>
|
Detect that the Internet connection is offline? <p>How to detect that the Internet connection is offline in JavaScript?</p>
|
<p>You can determine that the connection is lost by making <strong>failed XHR requests</strong>.</p>
<p>The standard approach is to <strong>retry the request</strong> a few times. If it doesn't go through, <strong>alert the user</strong> to check the connection, and <strong>fail gracefully</strong>.</p>
<p><strong>Sidenote:</strong> To put the entire application in an "offline" state may lead to a lot of error-prone work of handling state.. wireless connections may come and go, etc. So your best bet may be to just fail gracefully, preserve the data, and alert the user.. allowing them to eventually fix the connection problem if there is one, and to continue using your app with a fair amount of forgiveness.</p>
<p><strong>Sidenote:</strong> You could check a reliable site like google for connectivity, but this may not be entirely useful as just trying to make your own request, because while google may be available, your own application may not be, and you're still going to have to handle your own connection problem. Trying to send a ping to google would be a good way to confirm that the internet connection itself is down, so if that information is useful to you, then it might be worth the trouble.</p>
<p><strong>Sidenote</strong>: <em>Sending a Ping</em> could be achieved in the same way that you would make any kind of two-way ajax request, but sending a ping to google in this case would pose some challenges. First, we'd have the same cross-domain issues that are typically encountered in making ajax communications. One option is to set up a server-side proxy, wherein we actually <code>ping</code> google (or whatever site), and return the results of the ping to the app.. This is a <strong>catch-22</strong>, because if the internet connection is actually the problem, we won't be able to get to the server, and if the connection problem is only on our own domain, we won't be able to tell the difference. Other cross-domain techniques could be tried, for example, embedding an iframe in your page which points to google.com, and then polling the iframe for success/failure (examine the contents, etc). Embedding an image may not really tell us anything, because we need a useful response from the communication mechanism in order to draw a good conclusion about what's going on. So again, determining the state of the internet connection as a whole may be more trouble than it's worth. You'll have to weight these options out for your specific app.</p>
|
Where can I find my .emacs file for Emacs running on Windows? <p>I tried looking for the .emacs file for my Windows install for Emacs but could not find it. Does it have the same filename under Windows as in Unix? Do I have to create it myself? If so, under what specific directory does it go?</p>
|
<p>Copy'n'paste from the emacs FAQ:
<a href="http://www.gnu.org/software/emacs/windows/">http://www.gnu.org/software/emacs/windows/</a></p>
<h3><a href="http://www.gnu.org/software/emacs/manual/html_node/efaq-w32/Location-of-init-file.html#Location-of-init-file">Where do I put my init file?</a></h3>
<p>On Windows, the <code>.emacs</code> file may be called <code>_emacs</code> for backward compatibility with DOS and FAT filesystems where filenames could not start with a dot. Some users prefer to continue using such a name, because Explorer cannot create a file with a name starting with a dot, even though the filesystem and most other programs can handle it. In Emacs 22 and later, the init file may also be called <code>.emacs.d/init.el</code>. Many of the other files that are created by lisp packages are now stored in the <code>.emacs.d</code> directory too, so this keeps all your Emacs related files in one place.</p>
<p>All the files mentioned above should go in your HOME directory. The HOME directory is determined by following the steps below:</p>
<ol>
<li>If the environment variable HOME is set, use the directory it indicates.</li>
<li>If the registry entry HKCU\SOFTWARE\GNU\Emacs\HOME is set, use the directory it indicates.</li>
<li>If the registry entry HKLM\SOFTWARE\GNU\Emacs\HOME is set, use the directory it indicates. Not recommended, as it results in users sharing the same HOME directory.</li>
<li>If <code>C:\.emacs</code> exists, then use <code>C:/</code>. This is for backward compatibility, as previous versions defaulted to <code>C:/</code> if HOME was not set.</li>
<li>Use the user's AppData directory, usually a directory called Application Data under the user's profile directory, the location of which varies according to Windows version and whether the computer is part of a domain. </li>
</ol>
<p>Within Emacs, <code>~</code> at the beginning of a file name is expanded to your HOME directory, so you can always find your .emacs file with <code>C-x C-f ~/.emacs</code>.</p>
<p>There's further information at <a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Windows-HOME.html#Windows-HOME">HOME and Startup Directories on MS-Windows</a>.</p>
|
Speed of multiple variable assignment in T-SQL <p>Imagine I have a chunk of initialisation code at the top of a stored procedure with a number of variable assignments:</p>
<pre><code>SET @proc = 'sp_madeupname'
SET @magic_number = 42
SET @tomorrows_date = DATEADD(dd, 1, GETDATE())
...
</code></pre>
<p>Clearly doing all of the above as one SELECT would be faster:</p>
<pre><code>SELECT
@proc = 'sp_madeupname'
,@magic_number = 42
,@tomorrows_date = DATEADD(dd, 1, GETDATE())
...
</code></pre>
<p>But <em>how much</em> faster? Say if this stored procedure was executed as part of a loop, several thousand times, is it going to make any significant difference to the performance?</p>
|
<p>In this case, SELECT wins, performance-wise, when performing multiple assignments.</p>
<p>Here is some more information about it:</p>
<p><a href="http://www.sqlmag.com/Articles/ArticleID/94555/94555.html" rel="nofollow">SELECT vs. SET: Optimizing Loops</a></p>
|
MS Office hyperlinks change code page? <p>When you paste the following URL into IE: <a href="http://technet.microsoft.com/en-us/sysinternals/bb897434.aspx" rel="nofollow">http://technet.microsoft.com/en-us/sysinternals/bb897434.aspx</a>, the link on the right of the page cleanly says "Download Zoomit (77 KB)". If you paste the link into an Office document (Word, Excel, PowerPoint -- tested using Office 2003), and activate the link from the document, that same text has picked up a couple of A-circumflex symbols. This is because the source HTML contains "&nbsp;" entities (non-breaking space) which get translated to Unicode 00A0. In UTF-8, this is expressed as X'C2A0', and then the X'C2' gets displayed as a A-circumflex. I don't completely understand how the code pages get mixed up like this, but I'd really like to find a HTML meta http-equiv charset value that will cause my pages containing the nbsp-entity to display properly even when linked from an Office document.</p>
|
<p>I found an answer that seems to be working. First I added an alert to display the document.charset. This displayed "utf-8" when invoked directly, and "windows-1252" when invoked from a hyperlink in a MS Office document. I therefore inserted the following meta-tag, and pages seem to display correctly even when invoked from Office documents: </p>
<pre><code><meta http-equiv="content-type" content="text/html; charset=utf-8" />
</code></pre>
|
Database localization <p>i am looking for opinions if the following problem maybe has a better/different/common solution:</p>
<p><hr /></p>
<p>I have a database for products which contains the names of the products in english (the default language of this application) and i need translations of the names if available.</p>
<p>Currently i have this setup:</p>
<p>A product table</p>
<pre><code>CREATE TABLE products
(
id serial NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT products_pkey PRIMARY KEY (id)
)
</code></pre>
<p>and a product localization table</p>
<pre><code>CREATE TABLE products_l10n
(
product_id serial NOT NULL,
"language" character(2) NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT products_l10n_pkey PRIMARY KEY (product_id, language),
CONSTRAINT products_l10n_product_id_fkey FOREIGN KEY (product_id)
REFERENCES products (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
</code></pre>
<p>and i use the following query to retrieve a list of localized products (german in this case) with fallback to the default english names:</p>
<pre><code>SELECT p.id, COALESCE(pl.name, p.name)
from products p LEFT
JOIN products_l10n pl ON p.id = pl.product_id AND language = 'de';
</code></pre>
<p>The SQL code is in postgres dialect. Data is stored as UTF-8.</p>
|
<p>Looks good to me. The one thing I might change is the way you handle languages: that should probably be a separate table. Thus, you would have:</p>
<pre><code>CREATE TABLE products_l10n
(
product_id serial NOT NULL,
language_id int NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT products_l10n_pkey PRIMARY KEY (product_id, language),
CONSTRAINT products_l10n_product_id_fkey FOREIGN KEY (product_id)
REFERENCES products (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
CONSTRAINT products_l10n_language_id_fkey FOREIGN KEY (language_id)
REFERENCES languages (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
CREATE TABLE languages
)
id serial not null
"language" character(2) NOT NULL
)
</code></pre>
<p>Besides that, I think you've got just about the best possible solution.</p>
|
Retrieving the new ID from a SQLDataAdaptor.Update <p>How would you go about retrieving the @@IDENTITY value for each row when the SQLDataAdapater.Update is executed on a table?</p>
<p>eg. Is it possible to modify/intercept the InsertCommand, generated by the SQLCommandBuilder, to say add an output parameter, and then retrieve its value in the da.RowUpdated event???</p>
|
<p>Bill Vaughn knows a thing or two about this. They key is tweaking your InsertCommand.</p>
<p>See <a href="http://www.betav.com/Files/Content/Articles/Managing%20and%20Identity%20Crisis.pdf" rel="nofollow">"Managing an @@IDENTITY Crisis"</a>.</p>
<p>Note: the actual solution uses SCOPE_IDENTITY() in order to be trigger-safe.</p>
|
Why is Apache executing .php.html files as PHP? <p>I have an odd problem...I'm using a documentation generator which generates a lot of output like docs/foo.php.html. It's XHTML, and thus contains <code><?xml...></code> tags at the beginning of file. The problem is, Apache has somehow decided to run it through the PHP interpreter, even though ".php" appears in the middle of the filename, and not at the end. This in turn triggers a PHP error, because it sees "<code><?</code>" as the command to start executing PHP code, and immediately gets confused by the "<code>xml...</code>" which follows it.</p>
<p>How do I configure Apache to ONLY execute .php files, and not .php.html files? The string "php.html" does not appear explicitly anywhere in my Apache config files. There is a line "<code>AddHandler php5-script .php</code>", but I don't see how that would also include ".php.html" files.</p>
|
<p>The problem seems to be in <a href="http://httpd.apache.org/docs/2.2/mod/mod_mime.html">mod_mime</a>.</p>
<p>Quote from the Apache mod_mime documentation page:</p>
<blockquote>
<p>If you would prefer only the last dot-separated part of the filename to be mapped to a particular piece of meta-data, then do not use the Add* directives. For example, if you wish to have the file foo.html.cgi processed as a CGI script, but not the file bar.cgi.html, then instead of using AddHandler cgi-script .cgi, use</p>
<p><code><FilesMatch \.cgi$></code></p>
<p><code>SetHandler cgi-script</code></p>
<p><code></FilesMatch></code></p>
</blockquote>
<p>Also, you can google for <code>apache mod_mime "multiple extensions"</code></p>
|
IE6 generated strange worksheet name when doing export from java application <p>I am encountering error like </p>
<pre><code>test(10)[1].csv file cannot be found at
C:\Documents and Settings\Ron\Local Settings\Temporary Internet Files\Content.IE5\PQ0STUVW
</code></pre>
<p>When trying to do export of CSV file using the following codes.
Anyone have any idea what could be wrong? This issue does not occur in IE7 / Firefox and is only specific to IE6. </p>
<pre><code>response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + fileFullName);
</code></pre>
|
<p>I've already got that problem and asked the <a href="http://stackoverflow.com/questions/120497/how-to-work-around-the-1-ie-bug-while-saving-an-excel-file-from-a-web-server">question that as a correct answer</a> (or, shall I say, a good workaround for IE).</p>
|
What is the javascript MIME type for the type attribute of a script tag? <p>What is the <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type of javascript? </p>
<p>More specifically, what is the right thing to put in the "type" attribute of a script tag? <code>application/x-javascript</code> and <code>text/javascript</code> seem to be the main contenders.</p>
|
<p>This is a common mistake. The MIME type for javascript wasn't standardized for years. It's now <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">officially</a>: "<strong>application/javascript</strong>".</p>
<p>The real kicker here is that most browsers won't use that attribute anyway, at least not in the case of the script tag. They actually peek inside the packet and determine the type for themselves.</p>
<p>So the bottom line is that the type="text/javascript" doesn't do anything as far as the javascript is concerned, but it's part of the spec for both <strong>HTML 4</strong> and <strong>XHTML 1.0</strong>.</p>
|
Daemon Threads Explanation <p>In the <a href="https://docs.python.org/2/library/threading.html#thread-objects">Python documentation</a>
it says:</p>
<blockquote>
<p>A thread can be flagged as a "daemon thread". The significance of this
flag is that the entire Python program exits when only daemon threads
are left. The initial value is inherited from the creating thread.</p>
</blockquote>
<p>Does anyone have a clearer explanation of what that means or a practical example showing where you would want to set threads as <code>daemonic</code>?</p>
<hr>
<p>To clarify for me:</p>
<p>so the only time you <strong>wouldn't</strong> set threads as daemonic is if you wanted them to continue running after the main thread exits?</p>
|
<p>Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These are only useful when the main program is running, and it's okay to kill them off once the other, non-daemon, threads have exited.</p>
<p>Without daemon threads, you'd have to keep track of them, and tell them to exit, before your program can completely quit. By setting them as daemon threads, you can let them run and forget about them, and when your program quits, any daemon threads are killed automatically.</p>
|
Where and how does Windows XP store wep/wpa keys? <p>Like the title says Where and How (i.e. if encrypted, with what method) does Windows XP store WEP/WPA Keys?</p>
|
<p>I found this: <a href="http://msdn.microsoft.com/en-us/library/ms706987(VS.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms706987(VS.85).aspx</a>.</p>
|
How do I create the migrations for a legacy database? <p>I am currently developing a Rails application using a database that was designed before I was aware of Rails existence.<br />
I have currently created some migrations to add some new tables and new columns to existing tables.</p>
<p>I would like to have the migrations to recreate the full database.</p>
<p>Which steps should I follow?<br />
Should I create all the migrations by hand?</p>
<p>EDIT: I am interested in the database schema not in the database contents</p>
|
<p>We had this exact issue when we ported a PHP application to rails. What we did is similar to tomtoday's suggestion. First we pointed the rails configuration to the current database. Then we did a rake db:schema:dump and copied the db/schema.rb file to something like db/schema_base.rb. Then you make your first migration loading that schema. For example:</p>
<pre><code>class CreateTables < ActiveRecord::Migration
def self.up
`cp #{Rails.root}/db/schema_base.rb #{Rails.root}/db/schema.rb`
Rake::Task['db:schema:load'].invoke
end
def self.down
end
end
</code></pre>
<p>Just force this to be the first migration and you will be on your way. Then you start writing migrations to transform the database to be more compliant with the Rails way. We wrote migrations to properly rename id columns, foreign key relationships, table names, etc.<br>
Remember that schema dump doesn't support foreign key constraints and triggers if you use those. </p>
|
Installing ASP.Net 2.0 after IIS <p>I just got a dedicated server from a hosting company, and for some reason, it didn't have IIS installed.
It did have .Net 2.0, though.</p>
<p>So I installed IIS, but now my ASP.net websites won't work.
I just get a 404, no event log entries, nothing...</p>
<p>I noticed in the redistributable package information that:
"To access the features of ASP.NET, IIS with the latest security updates must be installed prior to installing the .NET Framework"</p>
<p>I also can't uninstall .Net, it just won't let me...</p>
<p>Is there a way to reinstall .Net 2.0, or somehow do whatever it is it does to IIS to make it work?</p>
<p>Thanks!
Daniel</p>
|
<p>run from the command line</p>
<pre><code>aspnet_regiis -i
</code></pre>
<p>You may have to navigate to the folder it was installed.
Mine and the default is</p>
<pre><code>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
</code></pre>
|
Windows swapping redundantly? <p>This may not be strictly programming related but more OS-structure related.</p>
<p>Running Vista 32 bit on a brand new laptop with 3GB of memory, Running idle the system consumes about 40% of its memory. Other then the fact that this is outrageous on its own right, the OS <strong>should be able to fit all of the processes nicely into memory</strong> and not need to swap to disk EVER.<br />
Yet looking at the task manager I see processes having page faults all the time. Not many but still. for instance explorer.exe has one every second approximately.</p>
<p>Why is that? Why does the OS feel the need to swap out pages although it has plenty of physical memory?</p>
|
<p>A page fault doesn't necessarily mean that something was paged to disk. A modern OS has many levels of state that a page might be in, for example Windows will probably distinguish between a page of memory that is being actively used, and a page of memory that hasn't been touched in a while and could be paged to disk if needed. (This makes the pager's job easier, because it only has to look at the second kind of page to find out which ones it can page.) Now, how does a page get from the second state back to the first one? The kernel sets a bit on that page indicating that if anything accesses it, then the page will be marked as "active" and moved back to the first state. This results in a page fault.</p>
<p>Other things that might cause a page fault are things like memory mapped files. An application requests that a file be mapped to memory, that is it just <em>appears</em> in memory whenever the app wants to read from it. Obviously it would be tremendously expensive to load the whole file into memory all at once, so the kernel just marks the memory space with the "please page fault if this is ever accessed" bit, and reads from the disk if the app ever touches that page.</p>
<p>The real situation is a lot more complex than the above, but that should give you a general idea of what might be going on.</p>
|
Storing more than 1 data item at a single index in a linked-list? <p>I am trying to store more than 1 data item at a single index in my linked-list. All of the examples in my textbook seem to illustrate adding only 1 piece of data per index. I'm assuming it is possible to add more?</p>
<p>For example, using the Collections API to store an integer I would do the following:</p>
<pre><code>LinkedList <Integer>linky = new LinkedList<Integer>();
int num1 = 2, num2 = 22, num3 = 25, num4 = 1337;
linky.add(num1);
</code></pre>
<p>How would I go about adding num2, num3, and num4 to the same first index in the list? Thanks guys. </p>
|
<p>There seems to be a little confusion about how linked lists work. Essentially, a linked list is composed of nodes, each of which contains one datum (an object, which itself can contain several member variables, to be precise), and a link to the next node in the list (or a null pointer if there is no such next node). You can also have a doubly-linked list, where each node also has a pointer to the previous node in the list, to speed up certain kinds of access patterns.</p>
<p>To add multiple "pieces of data" to a single node sounds like adding several links off of one node, which turns your linked list into an N-ary <em>tree</em>.</p>
<p>To add multiple pieces of data onto the end of the list, in the manner most commonly associated with a linked list, just do:</p>
<pre><code>LinkedList <Integer>linky = new LinkedList<Integer>();
int num1 = 2, num2 = 22, num3 = 25, num4 = 1337;
linky.add(num1);
linky.add(num2);
linky.add(num3);
linky.add(num4);
</code></pre>
<h2>Alternately, if you want each node of the linked list to have several pieces of data</h2>
<p>These data should be packaged up into an <strong>object</strong> (by defining a <code>class</code> that has them all as member variables). For example:</p>
<pre><code>class GroupOfFourInts
{
int myInt1;
int myInt2;
int myInt3;
int myInt4;
public GroupOfFourInts(int a, int b, int c, int d)
{
myInt1 = a; myInt2 = b; myInt3 = c; myInt4 = d;
}
}
class someOtherClass
{
public static void main(String[] args)
{
LinkedList<GroupOfFourInts> linky = new LinkedList<GroupOfFourInts>();
GroupOfFourInts group1 = new GroupOfFourInts(1,2,3,4);
GroupOfFourInts group2 = new GroupOfFourInts(1337,7331,2345,6789);
linky.add(group1);
linky.add(group2);
}
}
</code></pre>
<p>Now, <code>linky</code> will have 2 nodes, each of which will contain 4 <code>int</code>s, <em>myInt1</em>, <em>myInt2</em>, <em>myInt3</em>, and <em>myInt4</em>.</p>
<h2>Note</h2>
<p>None of the above is specific to linked lists. This pattern should be used whenever you want to store a bunch of data together as a unit. You create a class that has member variables for every piece of data you want to be stored together, then create any Java Collections type (ArrayList, LinkedList, TreeList, ...) of that type.</p>
<p>Be sure that you want to use a linked list (as there's no penalty in terms of programming difficulty in choosing an ArrayList or TreeList). This will depend on your data access pattern. Linked lists provide O(1) addition and deletion, but O(n) lookup, whereas ArrayLists provide O(1) lookup, but O(n) arbitrary add and delete. TreeLists provide O(log n) insertion, deletion, and lookup. The tradeoffs between these depend on the amount of data you have and how you're going to be modifying and accessing the data structure.</p>
<p>Of course, none of this matters if you'll only have, say, <100 elements in your list ;-)</p>
<p>Hope this helps!</p>
|
Specify parts of the header that have to be signed and/or encrypted in WCF with binding that support standards <p>Using Ws2007HttpBinding and securing the service, the WSDL file generated shows in the policy section that all the ws-addressing headers and the body will be signed, and that the body will be encrypted.</p>
<pre><code><sp:SignedParts>
<sp:Body />
<sp:Header Name="To" Namespace="http://www.w3.org/2005/08/addressing" />
<sp:Header Name="From" Namespace="http://www.w3.org/2005/08/addressing" />
<sp:Header Name="FaultTo" Namespace="http://www.w3.org/2005/08/addressing" />
<sp:Header Name="ReplyTo" Namespace="http://www.w3.org/2005/08/addressing" />
<sp:Header Name="MessageID" Namespace="http://www.w3.org/2005/08/addressing" />
<sp:Header Name="RelatesTo" Namespace="http://www.w3.org/2005/08/addressing" />
<sp:Header Name="Action" Namespace="http://www.w3.org/2005/08/addressing" />
</sp:SignedParts>
<sp:EncryptedParts>
<sp:Body />
</sp:EncryptedParts>
</code></pre>
<p>We would like to specify which headers have to be signed and/or encrypted, like it is possible in Apache rampart. For custom header or body elements, it is possible using annotations in the code, but for these elements that are added by the binding itself, is is possible?</p>
|
<p>Nevermind, after a few days I found an answer over here: <a href="http://blogs.msdn.com/drnick/archive/2007/01/19/securing-custom-headers-version-2.aspx" rel="nofollow">http://blogs.msdn.com/drnick/archive/2007/01/19/securing-custom-headers-version-2.aspx</a></p>
|
How can I store multiple values in a Perl hash table? <p>Up until recently, I've been storing multiple values into different hashes with the same keys as follows:</p>
<pre><code>%boss = (
"Allan" => "George",
"Bob" => "George",
"George" => "lisa" );
%status = (
"Allan" => "Contractor",
"Bob" => "Part-time",
"George" => "Full-time" );
</code></pre>
<p>and then I can reference <code>$boss("Bob")</code> and <code>$status("Bob")</code> but this gets unwieldy if there's a lot of properties each key can have and I have to worry about keeping the hashes in sync.</p>
<p>Is there a better way for storing multiple values in a hash? I could store the values as</p>
<pre><code> "Bob" => "George:Part-time"
</code></pre>
<p>and then disassemble the strings with split, but there must be a more elegant way.</p>
|
<p>This is the standard way, as per <a href="http://perldoc.perl.org/perldsc.html">perldoc perldsc</a>.</p>
<pre><code>~> more test.pl
%chums = ( "Allan" => {"Boss" => "George", "Status" => "Contractor"},
"Bob" => {"Boss" => "Peter", "Status" => "Part-time"} );
print $chums{"Allan"}{"Boss"}."\n";
print $chums{"Bob"}{"Boss"}."\n";
print $chums{"Bob"}{"Status"}."\n";
$chums{"Bob"}{"Wife"} = "Pam";
print $chums{"Bob"}{"Wife"}."\n";
~> perl test.pl
George
Peter
Part-time
Pam
</code></pre>
|
Apache + mod_lisp + clisp <p>How to to configure apache + mod_lisp + clisp and set up a "Hello World!"? I couldn't find any complete howto on the subject. Thanks.</p>
<p>Edit: Vebjorn's solution works, but then I don't how to code the "hello world!". Can anyone tell me how to proceed? There's something like SWANKing the clisp, then connect to it with SLIME, but then when I launch mod_lisp's demo, the test page is not served and my slime doesn't return?</p>
<p>Thanks again.</p>
|
<ol>
<li>Download <a href="http://www.fractalconcept.com:8000/public/open-source/mod_lisp/mod_lisp.c">http://www.fractalconcept.com:8000/public/open-source/mod_lisp/mod_lisp.c</a></li>
<li>Compile and install Apache module with <code>sudo apxs -i -c mod_lisp.c</code></li>
<li>Add the following to your <code>httpd.conf</code>:
<pre>
LoadModule lisp_module libexec/httpd/mod_lisp.so
AddModule mod_lisp.c
LispServer 127.0.0.1 3000 "foo"
<Location /foo>
SetHandler lisp-handler
</Location>
</pre></li>
<li>Restart apache with <code>sudo apachectl restart</code></li>
<li>Download example of Lisp-side handling in CLISP: <a href="http://www.fractalconcept.com/fcweb/download/modlisp-clisp.lisp">http://www.fractalconcept.com/fcweb/download/modlisp-clisp.lisp</a></li>
<li><p>Start CLISP and evaluate:</p>
<pre>
(load "modlisp-clisp")
(modlisp:modlisp-server)
</pre></li>
<li><p>Point your browser to <a href="http://localhost/foo">http://localhost/foo</a>. You should see:</p></li>
</ol>
<blockquote>
<p>mod_lisp 2.0</p>
<p>This is a constant html string sent by
mod_lisp 2.0 + CLISP + apache + Linux</p>
</blockquote>
|
jQuery animate backgroundColor <p>I am trying to animate a change in backgroundColor using jQuery on mouseover.</p>
<p>I have checked some example and I seem to have it right, it works with other properties like fontSize, but with backgroundColor I get and "Invalid Property" js error.
The element I am working with is a div.</p>
<pre><code>$(".usercontent").mouseover(function() {
$(this).animate({ backgroundColor: "olive" }, "slow");
});
</code></pre>
<p>Any ideas?</p>
|
<p>The color plugin is only 4kb so much cheaper than the UI library. Of course you'll want to use a <a href="http://github.com/jquery/jquery-color">decent version</a> of the plugin and not <a href="http://plugins.jquery.com/project/color">some buggy old thing</a> which doesn't handle Safari and crashes when the transitions are too fast. Since a minified version isn't supplied you might like test various compressors and <a href="http://compressorrater.thruhere.net/">make your own</a> min version. YUI gets the best compression in this case needing only 2317 bytes and since it is so small - here it is:</p>
<pre><code>(function (d) {
d.each(["backgroundColor", "borderBottomColor", "borderLeftColor", "borderRightColor", "borderTopColor", "color", "outlineColor"], function (f, e) {
d.fx.step[e] = function (g) {
if (!g.colorInit) {
g.start = c(g.elem, e);
g.end = b(g.end);
g.colorInit = true
}
g.elem.style[e] = "rgb(" + [Math.max(Math.min(parseInt((g.pos * (g.end[0] - g.start[0])) + g.start[0]), 255), 0), Math.max(Math.min(parseInt((g.pos * (g.end[1] - g.start[1])) + g.start[1]), 255), 0), Math.max(Math.min(parseInt((g.pos * (g.end[2] - g.start[2])) + g.start[2]), 255), 0)].join(",") + ")"
}
});
function b(f) {
var e;
if (f && f.constructor == Array && f.length == 3) {
return f
}
if (e = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)) {
return [parseInt(e[1]), parseInt(e[2]), parseInt(e[3])]
}
if (e = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)) {
return [parseFloat(e[1]) * 2.55, parseFloat(e[2]) * 2.55, parseFloat(e[3]) * 2.55]
}
if (e = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)) {
return [parseInt(e[1], 16), parseInt(e[2], 16), parseInt(e[3], 16)]
}
if (e = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)) {
return [parseInt(e[1] + e[1], 16), parseInt(e[2] + e[2], 16), parseInt(e[3] + e[3], 16)]
}
if (e = /rgba\(0, 0, 0, 0\)/.exec(f)) {
return a.transparent
}
return a[d.trim(f).toLowerCase()]
}
function c(g, e) {
var f;
do {
f = d.css(g, e);
if (f != "" && f != "transparent" || d.nodeName(g, "body")) {
break
}
e = "backgroundColor"
} while (g = g.parentNode);
return b(f)
}
var a = {
aqua: [0, 255, 255],
azure: [240, 255, 255],
beige: [245, 245, 220],
black: [0, 0, 0],
blue: [0, 0, 255],
brown: [165, 42, 42],
cyan: [0, 255, 255],
darkblue: [0, 0, 139],
darkcyan: [0, 139, 139],
darkgrey: [169, 169, 169],
darkgreen: [0, 100, 0],
darkkhaki: [189, 183, 107],
darkmagenta: [139, 0, 139],
darkolivegreen: [85, 107, 47],
darkorange: [255, 140, 0],
darkorchid: [153, 50, 204],
darkred: [139, 0, 0],
darksalmon: [233, 150, 122],
darkviolet: [148, 0, 211],
fuchsia: [255, 0, 255],
gold: [255, 215, 0],
green: [0, 128, 0],
indigo: [75, 0, 130],
khaki: [240, 230, 140],
lightblue: [173, 216, 230],
lightcyan: [224, 255, 255],
lightgreen: [144, 238, 144],
lightgrey: [211, 211, 211],
lightpink: [255, 182, 193],
lightyellow: [255, 255, 224],
lime: [0, 255, 0],
magenta: [255, 0, 255],
maroon: [128, 0, 0],
navy: [0, 0, 128],
olive: [128, 128, 0],
orange: [255, 165, 0],
pink: [255, 192, 203],
purple: [128, 0, 128],
violet: [128, 0, 128],
red: [255, 0, 0],
silver: [192, 192, 192],
white: [255, 255, 255],
yellow: [255, 255, 0],
transparent: [255, 255, 255]
}
})(jQuery);
</code></pre>
|
Does Ruby have a built-in do ... while? <p>Ruby has a wealth of conditional constructs, including <code>if</code>/<code>unless</code>, <code>while</code>/<code>until</code> etc.</p>
<p>The <code>while</code> block from C:</p>
<pre><code>while (condition) {
...
}
</code></pre>
<p>can be directly translated to Ruby:</p>
<pre><code>while condition
...
end
</code></pre>
<p>However, I can't seem to find a <em>built-in</em> equivalent in Ruby for a C-like <code>do ... while</code> block in which the block contents are executed at least once:</p>
<pre><code>do {
...
} while (condition);
</code></pre>
<p>Any suggestions?</p>
|
<p>...The best I could come up with is the <code>loop</code> construct with a <code>break</code> at the end: </p>
<pre><code>loop do
...
break unless condition
end
</code></pre>
|
Setting ruby hash .default to a list <p>I thought I understood what the default method does to a hash... </p>
<p>Give a default value for a key if it doesn't exist:</p>
<pre><code>irb(main):001:0> a = {}
=> {}
irb(main):002:0> a.default = 4
=> 4
irb(main):003:0> a[8]
=> 4
irb(main):004:0> a[9] += 1
=> 5
irb(main):005:0> a
=> {9=>5}
</code></pre>
<p>All good.</p>
<p>But if I set the default to be a empty list, or empty hash, I don't understand it's behaviour at <strong>all</strong>....</p>
<pre><code>irb(main):001:0> a = {}
=> {}
irb(main):002:0> a.default = []
=> []
irb(main):003:0> a[8] << 9
=> [9] # great!
irb(main):004:0> a
=> {} # ?! would have expected {8=>[9]}
irb(main):005:0> a[8]
=> [9] # awesome!
irb(main):006:0> a[9]
=> [9] # unawesome! shouldn't this be [] ??
</code></pre>
<p>I was hoping/expecting the same behaviour as if I had used the ||= operator...</p>
<pre><code>irb(main):001:0> a = {}
=> {}
irb(main):002:0> a[8] ||= []
=> []
irb(main):003:0> a[8] << 9
=> [9]
irb(main):004:0> a
=> {8=>[9]}
irb(main):005:0> a[9]
=> nil
</code></pre>
<p>Can anyone explain what is going on?</p>
|
<p>This is a very useful idiom:</p>
<pre><code>(myhash[key] ||= []) << value
</code></pre>
<p>It can even be nested:</p>
<pre><code>((myhash[key1] ||= {})[key2] ||= []) << value
</code></pre>
<p>The other way is to do:</p>
<pre><code>myhash = Hash.new {|hash,key| hash[key] = []}
</code></pre>
<p>But this has the significant side-effect that <strong>asking</strong> about a key will create it, which renders has_key? fairly useless, so I avoid this method.</p>
|
C# controls in a MFC Application <p>I am responsible for the User Interface of an application written completely in Visual C++ using MFC and some third-part controls. I would like to use C# (WinForms or even better WPF) to improve the application look&feel.</p>
<p>I would like some advices about how to do it. Links, articles, examples...</p>
<p>Right now the user interface is isolated in a single project and I don't want to compile the whole module with CLR. So how do I have to manage that from the architectural point of view?</p>
<p>I have already looked at the Internet for the subject and read MSDN information. I would like more detailed information...is it convinient? pros/cons? have you used this approach successfully in a "big" application?
I don't want to compile the whole ui project with CLR...can I just have all the .NET code in a isolated project and call it from the ui project? what's the best way to do it?</p>
<p>Thanks in advance.</p>
|
<p>A good starting point is the <a href="http://msdn.microsoft.com/en-us/library/ms742522.aspx" rel="nofollow">Win32 and WPF interop</a> page on MSDN.</p>
|
How can I convert my current page to pdf after some content dynamically added via AJAX? <p>I have found some libraries or web services in PHP that does the job. The problem is that the conversion is done when the page is fully loaded, I would like to <strong>convert the page to PDF</strong> <strong>after some content dynamically added via AJAX</strong> in onload event. </p>
<p>Thank you very much,
Omar</p>
|
<p>You could post back <code>document.getElementsByTagName('html')[0].innerHTML</code> to the server (possibly using AJAX) and generate a PDF from that.</p>
|
Order of tags in <head></head> <p>does it matter at all what order the <code><link></code> or <code><script></code> or <code><meta></code> tags are in in the <code><head></head></code>?</p>
<p>(daft question but one of those things i've never given any thought to until now.)</p>
|
<p><strong>Optimization</strong></p>
<p>According to the folks over at Yahoo! you should <a href="http://developer.yahoo.com/performance/rules.html#css_top">put CSS at the top</a> and <a href="http://developer.yahoo.com/performance/rules.html#js_bottom">scripts at the bottom</a> because scripts block parallel downloads. But that is mostly a matter of optimization and is not critical for the page actually working. <a href="http://stackoverflow.com/users/20980/joeri-sebrechts">Joeri Sebrechts</a> pointed out that <a href="http://stevesouders.com/cuzillion/">Cuzillion</a> is a great way to test this and see the speed improvement for yourself.</p>
<p><strong>Multiple Stylesheets</strong></p>
<p>If you are linking multiple stylesheets, the order they are linked may affect how your pages are styled depending on the <a href="http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html">specificity of your selectors</a>. In other words, if you have two stylesheets that define the same selector in two different ways, the latter will take precedence. For example:</p>
<p>Stylesheet 1:</p>
<pre><code>h1 { color: #f00; }
</code></pre>
<p>Stylesheet 2:</p>
<pre><code>h1 { color: #00f; }
</code></pre>
<p>In this example, <code>h1</code> elements will have the color <code>#00f</code> because it was defined last with the same specificity:</p>
<p><strong>Multiple Scripts</strong></p>
<p>If you are using multiple scripts, the order they are used may be important if one of the scripts depends on something in another script. In this case, if the scripts are linked in the wrong order, some of your scripts may throw errors or not work as expected. This, however, is highly dependent on what scripts you are using.</p>
|
T4 Template directory missing on build server <p>I've just set up a new build server with the Windows 2008 .NET 3.5 SDK, and for some reason it hasn't installed c:\Program Files\Common Files\Microsoft Shared\TextTemplating so I can't run t4 templates on it. I had a look at the install options in add/remove programs and every single option is checked. </p>
<p>Any ideas why it is missing? Any ideas how to get it back?</p>
|
<p>My understanding is that the T4 engine is a feature of Visual Studio, not the .NET Framework SDK. </p>
|
How to get a complete list of object's methods and attributes? <pre><code>dir(re.compile(pattern))
</code></pre>
<p>does not return pattern as one of the lists's elements. Namely it returns:</p>
<pre><code>['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']
</code></pre>
<p>According to the manual, it is supposed to contain </p>
<blockquote>
<p>the object's attributes' names, the
names of its class's attributes, and
recursively of the attributes of its
class's base classes.</p>
</blockquote>
<p>It says also that</p>
<blockquote>
<p>The list is not necessarily complete.</p>
</blockquote>
<p>Is there a way to get the <strong>complete</strong> list? I always assumed that dir returns a complete list but apparently it does not...</p>
<p>Also: is there a way to list only attributes? Or only methods?</p>
<p><em>Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)</em></p>
|
<p>For the <strong>complete</strong> list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the <code>getattr</code> built-in function. As the user can reimplement <code>__getattr__</code>, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The <code>dir</code> function returns the keys in the <code>__dict__</code> attribute, i.e. all the attributes accessible if the <code>__getattr__</code> method is not reimplemented.</p>
<p>For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the <code>inspect</code> module determine the class methods, methods or functions.</p>
|
QDockWidget initial width <p>How do I set the initial width of a QDockWidget?</p>
<p>I have implemented the sizeHint function but what next?</p>
|
<p>The documentation for <code>QDockWidget</code> says:</p>
<blockquote>
A QDockWidget acts as a wrapper for its child widget, set with setWidget(). Custom size hints, minimum and maximum sizes and size policies should be <b>implemented in the child widget</b>. QDockWidget will respect them, adjusting its own constraints to include the frame and title. <b>Size constraints should not be set on the QDockWidget itself</b>, because they change depending on wether it is docked; a docked QDockWidget has no frame and a smaller title bar.
</blockquote>
<p>So the size hint is taken from whatever you put in the dock widget. Have you tried setting the size of the <code>QDockWidget</code>'s child?</p>
<p>But, I agree with Marius, the best thing to do is probably to use <code>QSettings</code> to save and restore the widths of all the dock windows when the application starts. Have a look at <code>QMainWindow::saveState</code> Apart from getting the data from <code>saveState</code> rather than from individual functions my save function looks very similar to the one given by Marius.</p>
|
Built in code generation in vs.net 2008? or free via MS? <p>What code generation tools are built-in to vs.net 2008 or are officially available via Microsoft?</p>
<p>I know of:</p>
<ul>
<li>Entity Framework</li>
<li>sqlmetal</li>
</ul>
<p>What else is there?</p>
<p>Ideally i'm looking for something that will generate from an existing database schema.</p>
|
<p>How about <a href="http://www.mygenerationsoftware.com" rel="nofollow">http://www.mygenerationsoftware.com</a>?</p>
|
How do I extract the version and path from an SVN working copy into a nant variable? <p>I am creating a new build process for a DotNet project which is to be held in Subversion.</p>
<p>For each dll/exe that I compile (via Nant) I would like to include 2 additional attibutes in the dlls that are built.</p>
<p>I already understand the workings of the 'asminfo' nant task. But I need help retrieving the information which I hope to embed in my binaries.</p>
<p>The build will always happen from a full working copy (checked out by the build process itself.) and will therefore always have an .svn directory available.</p>
<p>The attributes I want to add are RepositoryVersion and RepositoryPath. (I understand that these are not the names this information goes by in svn)</p>
<p>In order to do this I will need to extract the RepositoryVersion and RepositoryPath represented by the working copy folder that the BuildFile sits within.</p>
<p><strong>How do I extract this information from any given .svn folder into the 2 nant variables?</strong> </p>
|
<p>Firstly, you can use "svn info --xml >out.xml" to get the svn information to a text file. You can then use a Nant xml-peek to get a value out of the file into a variable.</p>
<pre><code><xmlpeek file="out.xml" xpath="/info/entry/url" property="svn.url" />
</code></pre>
|
How to find the installation directory of a third-party application, such as Google Earth, using C#? <p>I have the following code fragment that starts a <a href="http://en.wikipedia.org/wiki/Google_Earth" rel="nofollow">Google Earth</a> process using a hardcoded path:</p>
<pre><code>var process =
new Process
{
StartInfo =
{
//TODO: Get location of google earth executable from registry
FileName = @"C:\Program Files\Google\Google Earth\googleearth.exe",
Arguments = "\"" + kmlPath + "\""
}
};
process.Start();
</code></pre>
<p>I want to programmatically fetch the installation location of <em>googleearth.exe</em> from somewhere (most likely the registry).</p>
|
<p>From the example given you can gauge that I'm actually trying to pass a KML file to Google Earth. Because of this, the simplest way of resolving this problem is relying on the file association of KML with Google Earth and using the following as a replacement for the entire example:</p>
<pre><code>Process.Start(kmlPath);
</code></pre>
<p>This was found by reviewing the answers to <a href="http://stackoverflow.com/questions/181719/how-to-start-a-process-from-c-winforms">this</a> question.</p>
|
ASP.Net: Approaches to multilingual websites with Javascript and AJAX <p>We've recently completed phase 1 of a ASP.Net website in English and French. We went with using resource files to store language specific strings, but because the site used ASP.Net AJAX and javascript heavily we rigged up a solution to pass the right files through the ASP.Net pipeline where we could catch "tokens" and replace them with the appropriate text pulled from the resource files. </p>
<p>This is the second project I've been involved in that had these kinds of challenges, the first one stored the text strings in a database, and instead of ASP.Net AJAX, it used the AJAX tools that come with the Prototype library and put all Javascript into aspx files so that the tokens could be replaced on the way out.</p>
<p>What I'm wondering is, has anyone else encountered a similar scenario? What approach did you take? What lessons were learned? How did you deal with things like internationalized date formats?</p>
|
<p>In my main project (a RAD framework using PHP with gettext for translations) we're doing already alot of prepare operations on javascript files like merging and minifying them. Within this preperations we parse for gettext-markers and replace them with the language specific text.</p>
<p>The result get save as javascript file and normal included into the html.</p>
<pre><code><script scr="var/scripts/en_GB-76909c49e9222ec2bb2f45e0a3c8baef80deb665.js"></script>
</code></pre>
<p>The filename contains Locale and a hash value for caching.</p>
<p>Date and money values get always converted from system format to Locale format on output and visa versa for input.</p>
|
How does one weed out dependencies in a large project? <p>I'm about to inherit a rather large Java enterprise project that has a large amount of third party dependencies. There is at least seventy JARs included and some of them would seem to be unused e.g. spring.jar which I know isn't used.</p>
<p>It seems that over the years as various developers have touched upon the code base they have all tried out new project-of-the-month type libraries.</p>
<p><strong>How does one go about getting rid of these?</strong> Within reason of course, as clearly some dependencies are helpful to not have to re-invent the wheel. </p>
<p>I'm obviously interested in java based projects but I'm welcome to answers across languages that people think will be helpful.</p>
|
<p>Personally, I think you have to start by assessing the scale of the problem. It's going to be fairly painful, but I'd make a list of the dependencies and work out exactly which parts of the project use which ones.</p>
<p>Then I'd work out exactly what features of each you're actually making use of (in many cases, you'll end up having a massive third party library which you're using a tiny part of).</p>
<p>Once you have this information, you'll at least know what you're dealing with.</p>
<p>My next step would be to look at all of the dependencies that you only use to a small extent. Checking around might uncover things that you could use from other libraries that would eliminate the lesser used libraries.</p>
<p>I'd also have a look around to see if there's anything small that you could just re-write and include in your own code-base.</p>
<p>Finally, I'd have a look around at the vendors of your dependencies and their competitors to see if the latest versions contain more functionality that will allow you to eliminate a few others.</p>
<p>Then you're just left wondering whether it's better to be highly dependent on a few vendors, or less dependent on a lot of vendors!! ;o)</p>
|
How do I protect all worksheet in an Excel workbook with a single click? <p>I have around 25 worksheets in my workbook (Excel spreadsheet).
Is there a way I can protect all the 25 worksheets in single click ? or this feature is not available and I will have to write a VBA code to accomplish this. I need very often to protect all sheets and unprotect all sheets and doing individually is time consuming</p>
|
<p>I don't believe there's a way to do it without using VBA. If you are interested in a VBA solution, here is the code:</p>
<pre><code>Dim ws as Worksheet
Dim pwd as String
pwd = "" ' Put your password here
For Each ws In Worksheets
ws.Protect Password:=pwd
Next ws
</code></pre>
<p>Unprotecting is virtually the same:</p>
<pre><code>Dim ws as Worksheet
Dim pwd as String
pwd = "" ' Put your password here
For Each ws In Worksheets
ws.Unprotect Password:=pwd
Next ws
</code></pre>
|
Find beginning of sentence in String <p>I want to display the results of a searchquery in a website with a title and a short description. The short description should be a small part of the page which holds the searchterm. What i want to do is:
1 strip tags in page
2 find first position of seachterm
3 from that position, going back find the beginning (if there is one) of that sentence.
4 Start at the found position in step 3 and display ie 200 characters from there</p>
<p>I need some help with step 3. I think i need an regex that finds the first capital or dot...</p>
|
<p>Even that will ultimately fail. Given the sentence "We went to Dr. Smith's office", if your search term is "office", virtually any criterion you use will give you "Smith's office" as your sentence.</p>
|
How do you change your apparent country of origin to test a site? <p>I want to be able to set my country of origin - does this involve testing through a proxy, or is there something that can be set else where?</p>
|
<p>I would use <a href="http://www.torproject.org/">TOR</a> for this purpose. That way you are sure you are hitting the site from a different country.</p>
|
Get null == null in SQL <p>I wish to search a database table on a nullable column. Sometimes the value I'm search for is itself NULL. Since Null is equal to nothing, even NULL, saying</p>
<pre><code>where MYCOLUMN=SEARCHVALUE
</code></pre>
<p>will fail. Right now I have to resort to</p>
<pre><code>where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL))
</code></pre>
<p>Is there a simpler way of saying that?</p>
<p>(I'm using Oracle if that matters)</p>
|
<p>You can do the IsNull or NVL stuff, but it's just going to make the engine do more work. You'll be calling functions to do column conversions which then have to have the results compared.</p>
<p>Use what you have</p>
<pre><code>where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL))
</code></pre>
|
Strange LINQ Exception (Index out of bounds) <p>I have a table, we'll call <code>Users</code>. This table has a single primary key defined in SQL Server - an autoincrement <code>int ID</code>.</p>
<p>Sometimes, my LINQ queries against this table fail with an <code>"Index was outside the range"</code> error - even the most simplest of queries. The query itself doesn't use any indexers.</p>
<p>For example: </p>
<pre><code>User = Users.Take(1);
</code></pre>
<p>or</p>
<pre><code>IEnumerable<Users> = Users.ToList();
</code></pre>
<p>Both of the queries threw the same error. Using the debugger Visualizer to look at the generated query - I copy and paste the query in SQL and it works fine. I also click "execute" on the visualizer and it works fine. But executing the code by itself throws this error. I don't implement any of the partial methods on the class, so nothing is happening there. If I restart my debugger, the problem goes away, only to rear it's head again randomly a few hours later. More critically, I see this bug in my error logs from the app running in production. </p>
<p>I do a ton of LINQ in my app, against a dozen or so different entities in my database, but I only see this problem on queries related to a specific entity in my table. Some googling has suggested that this problem might be related to an incorrect relationship specified between my model and another entity, but I don't have <em>any</em> relationships with this object. It seems to be working 95% of the time, it's just the other 5% that fail.</p>
<p>I have completely deleted the object from the designer, and re-added it from a "refreshed" server browser, and that did not fix the problem.</p>
<p>Any ideas what's going on here?</p>
<p>Here's the full error message and stack trace:</p>
<blockquote>
<p>Index was out of range. Must be non-negative and less than the size of
the collection. Parameter name: index at
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query,
QueryInfo queryInfo, IObjectReaderFactory factory, Object[]
parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object
lastResult) at
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query,
QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[]
userArguments, ICompiledSubQuery[] subQueries) at
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression
query) at
System.Data.Linq.Table<code>1.System.Linq.IQueryProvider.Execute[TResult](Expression
expression) at
System.Linq.Queryable.FirstOrDefault[TSource](IQueryable</code>1 source,
Expression`1 predicate) at MyProject.FindUserByType(String typeId)</p>
</blockquote>
<p>EDIT: As requested, below is a copy of the table schema.</p>
<pre><code>CREATE TABLE [dbo].[Container](
[ID] [int] IDENTITY(1,1) NOT NULL,
[MarketCode] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Description] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Capacity] [int] NOT NULL,
[Volume] [float] NOT NULL
CONSTRAINT [PK_Container] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
</code></pre>
<p>EDIT: The stack trace shows <code>FirstOrDefault</code>, but I duplicated the error using both <code>Take()</code> and <code>ToList()</code>. The stack trace is identical between all of these, simply interchangnig <code>FirstOrDefault/Take/ToList</code>. The move down the stack to <code>SqlProvider.Execute</code> is in fact identical. </p>
|
<p>This almost certainly won't be everyone's root cause, but I encountered this exact same exception in my project - and found that the root cause was that an exception was being thrown during construction of an entity class. Oddly, the true exception is "lost" and instead manifests as an ArgumentOutOfRange exception originating at the iterator of the Linq statement that retrieves the object/s. </p>
<p>If you are receiving this error and you have introduced OnCreated or OnLoaded methods on your POCOs, try stepping through those methods. </p>
|
Configuring python <p>I am new to python and struggling to find how to control the amount of memory a python process can take? I am running python on a Cento OS machine with more than 2 GB of main memory size. Python is taking up only 128mb of this and I want to allocate it more. I tried to search all over the internet on this for last half an hour and found absolutely nothing! Why is it so difficult to find information on python related stuff :(</p>
<p>I would be happy if someone could throw some light on how to configure python for various things like allowed memory size, number of threads etc.</p>
<p>A link to a site where most controllable parameters of python are described would be appreciated well.</p>
|
<p>Forget all that, python just allocates more memory as needed, there is not a myriad of comandline arguments for the VM as in java, just let it run. For all comandline switches you can just run python -h or read man python.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.