instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>Greetings!</p>
<p>I have a WebService that contains a WebMethod that does some work and returns a boolean value. The work that it does may or may not take some time, so I'd like to call it asynchronously.</p>
<pre><code>[WebService(Namespace = "http://tempuri.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class MyWebSvc : System.Web.Services.WebService
{
[WebMethod]
public bool DoWork()
{
bool succ = false;
try
{
// do some work, which might take a while
}
catch (Exception ex)
{
// handle
succ = false;
}
return succ;
}
}
</code></pre>
<p>This WebService exists on each server in a web farm. So to call the DoWork() method on each server, I have a class library to do so, based on a list of server URLs:</p>
<pre><code>static public class WebSvcsMgr
{
static public void DoAllWork(ICollection<string> servers)
{
MyWebSvc myWebSvc = new MyWebSvc();
foreach (string svr_url in servers)
{
myWebSvc.Url = svr_url;
myWebSvc.DoWork();
}
}
}
</code></pre>
<p>Finally, this is called from the Web interface in an asp:Button click event like so:</p>
<pre><code>WebSvcsMgr.DoAllWork(server_list);
</code></pre>
<p>For the static DoAllWork() method called by the Web Form, I plan to make this an asynchronous call via IAsyncResult. However, I'd like to report a success/fail of the DoWork() WebMethod for each server in the farm as the results are returned. What would be the best approach to this in conjuction with an UpdatePanel? A GridView? Labels? And how could this be returned by the static helper class to the Web Form?</p>
|
<p><a href="http://msdn.microsoft.com/en-us/magazine/cc163725.aspx" rel="nofollow noreferrer">Asynchronous pages</a> are helpful in scenarios when you need to asynchronously call web service methods.</p>
|
<p>A Literal in a conditional Update Panel would be fine.</p>
<pre><code><asp:UpdatePanel ID="up" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Literal ID="litUpdateMe" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</code></pre>
| 18,552
|
<p>I have configured Tomcat 6 to serve Perl CGI scripts. That part is <a href="http://tomcat.apache.org/tomcat-6.0-doc/cgi-howto.html" rel="nofollow noreferrer">well documented</a> and works ok for me.</p>
<p>But, when a browser requests an image from this CGI dir, Tomcat's CGI servlet refuses to serve the image, displaying instead merely the url of the image. I believe this is a security feature to prevent users from seeing the contents of such files in general. </p>
<p>How do I configure tomcat, the tomcat CGI servlet, and/or the tomcat default servlet, to actually serve up an image file which happens to be located in my CGI dir? Is that possible?</p>
|
<p>Why do you want to put images inside your CGI directory? Shouldn't they be under the normal document root?</p>
<p>If you are constructing relative paths in the output of your script, add a BASE tag to the HTML head, or make the links absolute URLs.</p>
|
<p>OK, I have written a short how-to on installing Bugzilla on Apache Tomcat 6 (on Ubuntu 10.04 + MysSQL).</p>
<p>I was playing around with the BZ instance and it seems to be functioning normally.</p>
<p><a href="http://blog.inmite.eu/2010/08/installing-bugzilla-on-the-apache-tomcat-6/" rel="nofollow noreferrer">http://blog.inmite.eu/2010/08/installing-bugzilla-on-the-apache-tomcat-6/</a></p>
<p>Good luck!</p>
<p>petr@inmite[dot]eu</p>
| 47,207
|
<p>We are using PowerDesigner at work for database modelling. But there is a hell of a price tag on that piece of software. And frankly, all I use is physical diagrams for MS SQL, which is about 1% of what PD knows.</p>
<p>Are there any good alternatives? I know about Visio and MS SQL Diagrams, but looking for other options.</p>
|
<p><a href="http://www.sqlpower.ca/page/architect" rel="noreferrer">Power*Architect</a> is the way to go. It's free, open source, and does a really great job helping you build your ERDs. Plus, it works on Windows, Linux, and OSX.</p>
|
<p>You might want to look at <a href="https://www.xcase.com/demo.php" rel="nofollow noreferrer">https://www.xcase.com/demo.php</a>. It's not free, but it's quite a bit cheaper than PowerDesigner, as far as I can tell. I've used earlier versions, but lately I've had easy access to Visio, so have continued with that instead of investing in xCase.</p>
| 10,199
|
<p>Given numbers like 499, 73433, 2348 what VBA can I use to round to the nearest 5 or 10? or an arbitrary number?</p>
<p>By 5:</p>
<pre><code> 499 -> 500
2348 -> 2350
7343 -> 7345
</code></pre>
<p>By 10:</p>
<pre><code> 499 -> 500
2348 -> 2350
7343 -> 7340
</code></pre>
<p>etc.</p>
|
<p>It's simple math. Given a number X and a rounding factor N, the formula would be:</p>
<p>round(X / N)*N</p>
|
<p>To mimic in Visual Basic the way the round function works in Excel, you just have to use:
WorksheetFunction.Round(number, decimals)</p>
<p>This way the banking or accounting rounding don't do the rounding.</p>
| 42,307
|
<p>I'm currently writing a program to generate really enormous (65536x65536 pixels and above) Mandelbrot images, and I'd like to devise a spectrum and coloring scheme that does them justice. The <a href="http://en.wikipedia.org/wiki/File:Mandel_zoom_00_mandelbrot_set.jpg" rel="noreferrer">wikipedia featured mandelbrot image</a> seems like an excellent example, especially how the palette remains varied at all zoom levels of the sequence. I'm not sure if it's rotating the palette or doing some other trick to achieve this, though.</p>
<p>I'm familiar with the <a href="http://en.wikipedia.org/wiki/Mandelbrot_set#Continuous_.28smooth.29_coloring" rel="noreferrer">smooth coloring algorithm</a> for the mandelbrot set, so I can avoid banding, but I still need a way to assign colors to output values from this algorithm.</p>
<p>The images I'm generating are pyramidal (eg, a series of images, each of which has half the dimensions of the previous one), so I can use a rotating palette of some sort, as long as the change in the palette between subsequent zoom levels isn't too obvious.</p>
|
<p><strong>This is the smooth color algorithm:</strong></p>
<p>Lets say you start with the complex number <code>z0</code> and iterate <code>n</code> times until it escapes. Let the end point be <code>zn</code>.</p>
<p>A smooth value would be </p>
<pre><code>nsmooth := n + 1 - Math.log(Math.log(zn.abs()))/Math.log(2)
</code></pre>
<p>This only works for mandelbrot, if you want to compute a smooth function for julia sets, then use</p>
<pre><code>Complex z = new Complex(x,y);
double smoothcolor = Math.exp(-z.abs());
for(i=0;i<max_iter && z.abs() < 30;i++) {
z = f(z);
smoothcolor += Math.exp(-z.abs());
}
</code></pre>
<p>Then <code>smoothcolor</code> is in the interval <code>(0,max_iter)</code>.</p>
<p>Divide <code>smoothcolor</code> with <code>max_iter</code> to get a value between 0 and 1.</p>
<p><strong>To get a smooth color from the value:</strong></p>
<p>This can be called, for example (in Java):</p>
<pre><code>Color.HSBtoRGB(0.95f + 10 * smoothcolor ,0.6f,1.0f);
</code></pre>
<p>since the first value in HSB color parameters is used to define the color from the color circle.</p>
|
<p>here you can find a version with javascript</p>
<p>usage :</p>
<pre><code>var rgbcol = [] ;
var rgbcol = MapColor ( Iteration , Zy2,Zx2 ) ;
point ( ctx , iX, iY ,rgbcol[0],rgbcol[1],rgbcol[2] );
</code></pre>
<p>function</p>
<pre><code>/*
* The Mandelbrot Set, in HTML5 canvas and javascript.
* https://github.com/cslarsen/mandelbrot-js
*
* Copyright (C) 2012 Christian Stigen Larsen
*/
/*
* Convert hue-saturation-value/luminosity to RGB.
*
* Input ranges:
* H = [0, 360] (integer degrees)
* S = [0.0, 1.0] (float)
* V = [0.0, 1.0] (float)
*/
function hsv_to_rgb(h, s, v)
{
if ( v > 1.0 ) v = 1.0;
var hp = h/60.0;
var c = v * s;
var x = c*(1 - Math.abs((hp % 2) - 1));
var rgb = [0,0,0];
if ( 0<=hp && hp<1 ) rgb = [c, x, 0];
if ( 1<=hp && hp<2 ) rgb = [x, c, 0];
if ( 2<=hp && hp<3 ) rgb = [0, c, x];
if ( 3<=hp && hp<4 ) rgb = [0, x, c];
if ( 4<=hp && hp<5 ) rgb = [x, 0, c];
if ( 5<=hp && hp<6 ) rgb = [c, 0, x];
var m = v - c;
rgb[0] += m;
rgb[1] += m;
rgb[2] += m;
rgb[0] *= 255;
rgb[1] *= 255;
rgb[2] *= 255;
rgb[0] = parseInt ( rgb[0] );
rgb[1] = parseInt ( rgb[1] );
rgb[2] = parseInt ( rgb[2] );
return rgb;
}
// http://stackoverflow.com/questions/369438/smooth-spectrum-for-mandelbrot-set-rendering
// alex russel : http://stackoverflow.com/users/2146829/alex-russell
function MapColor(i,r,c)
{
var di= i;
var zn;
var hue;
zn = Math.sqrt(r + c);
hue = di + 1.0 - Math.log(Math.log(Math.abs(zn))) / Math.log(2.0); // 2 is escape radius
hue = 0.95 + 20.0 * hue; // adjust to make it prettier
// the hsv function expects values from 0 to 360
while (hue > 360.0)
hue -= 360.0;
while (hue < 0.0)
hue += 360.0;
return hsv_to_rgb(hue, 0.8, 1.0);
}
</code></pre>
| 48,251
|
<p>We're using interfaces to represent entity classes in our domain model. We have concrete implementations of these by virtue of using LinqToSql. We have added a factory method to each LinqToSql class which our service layer uses to instantiate a new entity (note; as opposed to the controller's DataBind attribute doing it).</p>
<p>MonoRail's default DataBinder implementation will ignore properties that are defined as interfaces.</p>
<p>Ideally, we don't want to instantiate our data-layer classes in MonoRail - the whole point of the interfaces is to separate these concerns. </p>
<p>Also, we don't really want to create another set of non-LinqToSql concrete classes whose only job is to translate between layers.</p>
<p>It's the end of a <strong>really</strong> long day over here; please can someone have mercy and point us at the parts of IDataBinder that we should overload with our own implementations, or hint at other approaches we might attempt? ;-)</p>
|
<p>You should be looking at IParameterBinder. take a look at <a href="http://www.kenegozi.com/Blog/2008/09/15/creating-a-custom-parameter-binder-for-monorail-actions-iparameterbinder.aspx" rel="nofollow noreferrer">a post I've written on the subject</a></p>
|
<p>As Ken pointed, your idea could be implemented with a custom IParameterBinder.</p>
<p>A solution would be to use IOC:</p>
<ul>
<li>resolve concrete instance of the form from it's interface</li>
<li>then use IDataBinder to bind the instance to the request params</li>
</ul>
<p>Another one would be using IDictionaryAdapter:</p>
<ul>
<li>generate a dto proxy for your interface</li>
<li>then use IDataBinder to bind the dto proxy instance to the request params</li>
</ul>
<p>NB: second option won't work if interface:</p>
<ul>
<li>is not public (hum)</li>
<li>has methods</li>
<li>or events</li>
<li>or readonly properties</li>
<li>or setonly properties</li>
</ul>
<p>Last, I'm unsure of what is the problem exposing concrete class in controller's signature.</p>
<p>I myself use concrete form in controllers implementing interface defined in application layer services, it allows me to have concerns separated on both side:</p>
<ul>
<li>controller side is Http mapping and first level data validation of the form/command</li>
<li>application layer services is business validation and processing of the form/command</li>
</ul>
| 39,378
|
<p>I realize this is a quite general question, but I am wondering about the performance impact of implementing business logic with WF contra imperative code in fairly large enterprise system. I would like to hear others experiences in this regard.</p>
|
<p>You can check <a href="http://msdn.microsoft.com/en-us/library/aa973808.aspx" rel="noreferrer">Performance Characteristics of Windows Workflow Foundation</a> for key performance considerations and modeling guidelines that are important when developing applications on top of the Windows Workflow Foundation.</p>
<p>However I would suggest to wait for the WF 4.0 announcement at PDC (end of October) since <a href="http://download.microsoft.com/download/5/9/B/59B74A2A-245D-4304-802E-E0A0800FACD3/Dublin__NET_4_overview.docx" rel="noreferrer">they are promising</a></p>
<blockquote>
<p><strong>Significant improvements in
performance and scalability</strong> (Ten-fold
improvement in performance)</p>
</blockquote>
<hr>
<p>EDIT (after PDC, 11Nov08): </p>
<p>OK, not much revealed about performance at PDC, although Kenny Wolf <a href="http://channel9.msdn.com/pdc2008/TL17/" rel="noreferrer">said in his talk</a> that there are 10-100X performance improvements from execution speed to persistence sizes.</p>
<p>Moreover, Rick Garibay posted some post-talk discussions with Kenny Wolf <a href="http://rickgaribay.net/archive/2008/10/28/wf-4.0-big-changes-ahead.aspx" rel="noreferrer">here</a>. I am copying a relevant passage:</p>
<blockquote>
<p>My first question was around the
impetus for such a major overhaul.
Kenny shared that they focused very,
very deeply on key customer requests
and opportunities based on earlier
versions of the framework. There were
3 feature types that resonated most.
First, is delivering a truly
model-based framework that allows
every aspect of the WF to be
represented declaratively. Second, was
being able to truly participate in the
repository ecosystem, which is key for
deployment, management and operations
scenarios. And last, but not least was
performance.</p>
<p>Earlier in his talk, Kenny cited
intriguing improvements, including 10x
to 100x performance improvements and
persisted workflows becoming
essentially "free" with WF 4.0. In our
more one-on-one discussion after his
talk, he used the analogy of swinging
at a baseball with a wooden baseball
bat. While the wooden baseball bat is
effective, it feels a bit heavy, if
not clunky at times. When you pick up
an aluminum baseball bat, it is
markedly lighter, and feels
significantly more aerodynamic. WF 3.0
and 3.5 work, but WF 4 is a new and
improved aluminum baseball bat.</p>
</blockquote>
|
<p>I once did some benchmark about WF performance. It turns out that "declarative condition" is pretty slow. I believe that it is due to a lot of reflection is done in the process.</p>
| 25,071
|
<p><em>Problem:</em> Customer X has requested that pages using XML DataBinding and Databound tables in MSIE be re-factored to work cross-browser.</p>
<p><strong>Question:</strong> What is the best-practice way to mimic the <a href="http://www.globalguideline.com/xml/XML_Data_Island.php" rel="nofollow noreferrer">MSIE DataBinding</a> feature of MSIE cross-browser (i.e., in both MSIE and Firefox).</p>
<p><em>Features:</em> Customer X already gets the following using <a href="http://www.globalguideline.com/xml/XML_Data_Island.php" rel="nofollow noreferrer">MSIE DataBinding</a> in a single web page ...</p>
<ul>
<li>a <a href="http://simile.mit.edu/timeline/examples/jfk/jfk.xml" rel="nofollow noreferrer">single-url xml dump</a> in its entirety as the datasource (assume no server-side paging and no cross-domain problems)</li>
<li>web page markup that does nothing more than specify the datasource URL (just like MSIE)</li>
<li>the ability to load very large tables (e.g. 3k records minimum) without triggering javascript "out of memory" or "latency" errors on the client side</li>
<li>the ability to carry this out in a normal HTML table element with the possibility of row-striping (optional but not required since MSIE does not do this already)</li>
</ul>
<p><em>Background:</em> You probably have to be familiar with <a href="http://www.globalguideline.com/xml/XML_Data_Island.php" rel="nofollow noreferrer">MSIE DataBinding</a> to get in synch with this particular question. This feature of MSIE allows you to point to a single XML data source (of no particular schema, just as long as its in a standard "table") and the browser renders the data visually and asyncrhonously. </p>
<p>The benefit of this is that the page renders quickly, because the page load does not wait for the entirety of the table to be filled in before showing the user some output. The table rows get filled in progressively.</p>
<p><em>False Starts:</em> The following have already been attempted and rejected by Customer X.</p>
<ul>
<li>JQuery: works great for loading the data, and clean-maintainable HTML markup, but large data sources cause latency and memory problems when rendering client-side</li>
<li>XSLT: this scares Customer X because it involves a lot more than just specifying a "datasource" attribute on a <table> tag, and thus appears to be less maintainable in his opinion</li>
<li>Server-side data pagination: this is not an option because Customer X religiously wants to avoid segmenting the XML data or doing any "data munging" on the server side.</li>
</ul>
|
<p>In order to see the SQL query you can just configure hibernate.show_sql=true in your hibernate.cfg.xml file. Then you should see the queries in the console window during application execution.</p>
<p>That's the feature of the hibernate runtime, when Tools provide you with HQL editor, so you can test the queries before you put them into the code.</p>
|
<p>In order to see the SQL query you can just configure hibernate.show_sql=true in your hibernate.cfg.xml file. Then you should see the queries in the console window during application execution.</p>
<p>That's the feature of the hibernate runtime, when Tools provide you with HQL editor, so you can test the queries before you put them into the code.</p>
| 45,794
|
<p>I have a requirement to install multiple web setup projects (using VS2005 and ASP.Net/C#) into the same virtual folder. The projects share some assembly references (the file systems are all structured to use the same 'bin' folder), making deployment of changes to those assemblies problematic since the MS installer will only overwrite assemblies if the currently installed version is older than the one in the MSI.</p>
<p>I'm not suggesting that the pessimistic installation scheme is wrong - only that it creates a problem in the environment I've been given to work with. Since there are a sizable number of common assemblies and a significant number of developers who might change a common assembly but forget to update its version number, trying to manage versioning manually will eventually lead to massive confusion at install time.</p>
<p>On the flip side of this issue, it's also important not to spontaneously update version numbers and replace <em>all</em> common assemblies with <em>every</em> install, since that could (temporarily at least) obscure cases where actual changes were made.</p>
<p>That said, what I'm looking for is a means to update assembly version information (preferably using MSBuild) only in cases where the assembly constituents (code modules, resources etc) has/have actually changed.</p>
<p>I've found a few references that are at least partially pertinent <a href="http://code.msdn.microsoft.com/AssemblyInfoTaskvers/Release/ProjectReleases.aspx?ReleaseId=232" rel="noreferrer" title="here">here </a> (AssemblyInfo task on MSDN) and <a href="http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/94054d89-ba19-4658-9e4e-ce7d8ff4dea3/" rel="noreferrer" title="here">here</a> (looks similar to what I need, but more than two years old and without a clear solution).</p>
<p>My team also uses TFS version control, so an automated solution should probably include a means by which the AssebmlyInfo can be checked out/in during the build.</p>
<p>Any help would be much appreciated.</p>
<p>Thanks in advance.</p>
|
<p>I cannot answer all your questions, as I don't have experience with TFS.</p>
<p>But I can recommend a better approach to use for updating your AssemblyInfo.cs files than using the AssemblyInfo task. That task appears to just recreate a standard AssemblyInfo file from scratch, and loses any custom portions you may have added.</p>
<p>For that reason, I suggest you look into the FileUpdate task, from the MSBuild Community Tasks project. It can look for specific content in a file and replace it, like this:</p>
<pre><code><FileUpdate
Files="$(WebDir)\Properties\AssemblyInfo.cs"
Regex="(\d+)\.(\d+)\.(\d+)\.(\d+)"
ReplacementText="$(Major).$(ServicePack).$(Build).$(Revision)"
Condition="'$(Configuration)' == 'Release'"
/>
</code></pre>
<p>There are several ways you can control the incrementing of the build number. Because I only want the build number to increment if the build is completely successful, I use a 2-step method:</p>
<ul>
<li>read a number from a text file (the only thing in the file is the number) and add 1 without changing the file;</li>
<li>as a final step in the build process, if everything succeeded, save the incremented number back to the text file.</li>
</ul>
<p>There are tasks such as ReadLinesFromFile, that can help you with this, but I found it easiest to write a small custom task:</p>
<pre><code>using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace CredibleCustomBuildTasks
{
public class IncrementTask : Task
{
[Required]
public bool SaveChange { get; set; }
[Required]
public string IncrementFileName { get; set; }
[Output]
public int Increment { get; set; }
public override bool Execute()
{
if (File.Exists(IncrementFileName))
{
string lines = File.ReadAllText(IncrementFileName);
int result;
if(Int32.TryParse(lines, out result))
{
Increment = result + 1;
}
else
{
Log.LogError("Unable to parse integer in '{0}' (contents of {1})");
return false;
}
}
else
{
Increment = 1;
}
if (SaveChange)
{
File.Delete(IncrementFileName);
File.WriteAllText(IncrementFileName, Increment.ToString());
}
return true;
}
}
}
</code></pre>
<p>I use this before the FileUpdateTask to get the next build number:</p>
<pre><code><IncrementTask
IncrementFileName="$(BuildNumberFile)"
SaveChange="false">
<Output TaskParameter="Increment" PropertyName="Build" />
</IncrementTask>
</code></pre>
<p>and as my final step (before notifying others) in the build:</p>
<pre><code><IncrementTask
IncrementFileName="$(BuildNumberFile)"
SaveChange="true"
Condition="'$(Configuration)' == 'Release'" />
</code></pre>
<p>Your other question of how to update the version number only when source code has changed is highly dependent on your how your build process interacts with your source control. Normally, checking in source file changes should initiate a Continuous Integration build. That is the one to use to update the relevant version number.</p>
|
<p>I have written one custome task you can refer the code below. It will create an utility to which you can pass assemblyinfo path Major,minor and build number. you can modify it to get revision number. Since in my case this task was done by developer i used to search it and again replace whole string.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace UpdateVersion
{
class SetVersion
{
static void Main(string[] args)
{
String FilePath = args[0];
String MajVersion=args[1];
String MinVersion = args[2];
String BuildNumber = args[3];
string RevisionNumber = null;
StreamReader Reader = File.OpenText(FilePath);
string contents = Reader.ReadToEnd();
Reader.Close();
MatchCollection match = Regex.Matches(contents, @"\[assembly: AssemblyVersion\("".*""\)\]", RegexOptions.IgnoreCase);
if (match[0].Value != null)
{
string strRevisionNumber = match[0].Value;
RevisionNumber = strRevisionNumber.Substring(strRevisionNumber.LastIndexOf(".") + 1, (strRevisionNumber.LastIndexOf("\"")-1) - strRevisionNumber.LastIndexOf("."));
String replaceWithText = String.Format("[assembly: AssemblyVersion(\"{0}.{1}.{2}.{3}\")]", MajVersion, MinVersion, BuildNumber, RevisionNumber);
string newText = Regex.Replace(contents, @"\[assembly: AssemblyVersion\("".*""\)\]", replaceWithText);
StreamWriter writer = new StreamWriter(FilePath, false);
writer.Write(newText);
writer.Close();
}
else
{
Console.WriteLine("No matching values found");
}
}
}
}
</code></pre>
| 27,557
|
<p>I was reading the great article about binding and unbinding events (because I am a js beginner using jQuery) on <a href="http://www.learningjquery.com/2008/05/working-with-events-part-2" rel="nofollow noreferrer">Karl Swedberg's blog</a>, and I became totally puzzled at this part of the code (simplified for brevity):</p>
<pre><code> function addItemUnbind() {
$Add a button but it won't have it's event added;
addItemUnbind();
});
</code></pre>
<p>Why is it that by putting the same function within itself it doesn't keep executing into an infinite loop? However, it is used to re-bind the event to the element...!?</p>
|
<p>As far as i can tell your example will. However your example is not the same as the example on the website you reference.</p>
<pre><code>function addItemUnbind() {
$('#list6 li.special button')
.unbind('click')
.bind('click', function() {
var $newLi = $('<li class="special">special and new <button>I am new</button></li>');
$(this).parent().after($newLi);
addItemUnbind();
});
}
</code></pre>
<p>In this example the 'addItemUnbind' is called when the user clicks on the button.</p>
|
<p>The answer is hiding in part of the code you took out. What you've posted is indeed an infinite loop. However, here's a more complete (but still simplified) example, modified from the linked blog post:</p>
<pre><code>function addItemUnbind() {
bind('click', function() {
addItemUnbind();
});
}
</code></pre>
<p>The call to addItemUnbind is inside a closure--a new anonymous function that's separate from the addItemUnbind function that created it. Rather than being called right away, a reference to the new function is being passed into the bind function. So if the bind function looked like this:</p>
<pre><code>function bind(eventName, eventHandler) {
eventHandler();
}
</code></pre>
<p>then you'd have an infinite loop, because the call to eventHandler would lead back into addItemUnblind. But if it looks like this:</p>
<pre><code>function bind(eventName, eventHandler) {
this.events[eventName] = eventHandler; // save the event handler to call when an event happens
}
</code></pre>
<p>then there's no problem. It doesn't call addItemUnbind, it just saves a reference to a function that will call it later on.</p>
| 46,726
|
<p>I'm expanding my Ruby understanding by coding an equivalent of Kent Beck's xUnit in Ruby. Python (which Kent writes in) has an assert() method in the language which is used extensively. Ruby does not. I think it should be easy to add this but is Kernel the right place to put it?</p>
<p>BTW, <em>I know of the existence of the various Unit frameworks in Ruby</em> - this is an exercise to learn the Ruby idioms, rather than to "get something done".</p>
|
<p>No it's not a best practice. The best analogy to assert() in Ruby is just raising</p>
<pre><code> raise "This is wrong" unless expr
</code></pre>
<p>and you can implement your own exceptions if you want to provide for more specific exception handling</p>
|
<p>My understanding is that you're writing your own testing suite as a way of becoming more familiar with Ruby. So while Test::Unit might be useful as a guide, it's probably not what you're looking for (because it's already done the job).</p>
<p>That said, python's assert is (to me, at least), more analogous to C's <a href="http://www.manpagez.com/man/3/assert/" rel="noreferrer">assert(3)</a>. It's not specifically designed for unit-tests, rather to catch cases where "this should never happen".</p>
<p>How Ruby's built-in unit tests tend to view the problem, then, is that each individual test case class is a subclass of <a href="http://www.ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit/TestCase.html" rel="noreferrer">TestCase</a>, and that includes an "assert" statement which checks the validity of what was passed to it and records it for reporting.</p>
| 17,822
|
<p>For example, java.io.File is just a concrete class. My replacement for it supports resolving Windows shortcuts. I need to preprocess constructor parameters to resolve possible .lnk files because the FileSystem object that does normalizing/canonicalision/resolving on the abstract paths is not accessible. The need for preprocessing rules out pure subclassing - can't do preprocessing before calling super(...) and File is immutable. So I extend File and use a delegate, overriding all of File's constructors and methods (calling super("") in all constructors).</p>
<p>This works nicely, but is obviously not ideal - if File changes, I will not have overridden any new methods or constructors and this will expose the underlying empty abstract pathname. Am I missing something obvious? It seems like there should be a simpler/better way.</p>
|
<p>In the specific case you suggest it looks to me like you're better off with a separate factory class that makes the decisions about normalizing/canonicalision/resolving. </p>
<p>Then you can just let File be File. Simpler.</p>
|
<p>If you really want the subclass route, you can cheat the requirement that a call to <code>super()</code> has to be the first line of a subclass constructor by placing your cleanup code outside of your class, or in a static block:</p>
<pre><code>public class MyFile extends File {
public MyFile(String path) {
// static blocks aren't ideal, this is just for demo purposes:
super(cleanPath(path));
}
private static String cleanPath(String uncleanPath) {...}
}
</code></pre>
<p>The factory pattern suggested by krosenvold is another good solution.</p>
| 46,368
|
<p>For a model that has raised text on it, how do go about painting the very top layer of text, to make it stand out from the background? Lets say I printed the whole model the same color, what type of paint would work well, and not get on the background too?</p>
<p>Here's an example of a model that has raised text: <a href="https://www.thingiverse.com/thing:3025280" rel="nofollow noreferrer">https://www.thingiverse.com/thing:3025280</a></p>
|
<p>You don't provide any dimensions or sizes, but...</p>
<p>Assuming that the text is sufficiently elevated from the rest of the model, you could use a firm solid (as opposed to soft and spongey) roller, of an appropriate width.</p>
<p>This should enable you to paint just the text without getting paint on the rest of the model.</p>
<ul>
<li><p>If the text is small and in a "valley" or groove, then a narrow roller would be required, in order to avoid the surface either side of the text.</p></li>
<li><p>If the text is not on a flat, or smooth surface, then a small diameter roller might be required.</p></li>
<li><p>If you can't find a tiny paint roller, you could <em><a href="https://en.wikipedia.org/wiki/Jury_rigging" rel="nofollow noreferrer">jerry-rig</a></em> one using a paper clip and a roller wheel from an old cassette tape</p></li>
</ul>
|
<p>The technique you look for is <em>drybrushing</em> and not dependant on a specific type of color, as long as it can be applied with a brush.</p>
<p>An alternative technique might be carefully applying glue and leaf metal.</p>
| 1,513
|
<p>Been trying to upgrade my subversion installation, but due to (what I believe) are limited rights (I'm using hosted Linux account), I'm not able to properly "./configure" and compile the source code (see posts <a href="https://stackoverflow.com/questions/189906/upgrade-subversion-143-to-152-on-debian-hosted-account">Post1</a> and <a href="https://stackoverflow.com/questions/274656/building-subversion-154-on-debian-could-not-find-library-containing-rsanew">Post2</a> if very interested)</p>
<p>So, I'm thinking if I could just download <strong>pre-compiled binaries</strong>, the just might solve my problems. If you have better ideas - I'd love to hear that too!</p>
<p>NB: I'm not able to call <strong>aptitude</strong> or <strong>apt-get install subversion</strong> as suggested by <a href="http://subversion.tigris.org/getting.html#debian" rel="nofollow noreferrer">subversion.tigris.com</a></p>
<p><strong>I'm also interested in knowing how I would go about installing those pre-compiled binaries :)</strong></p>
|
<p>You can extract the binaries from the deb package for your architecture (which you can download from <a href="http://packages.debian.org/search?keywords=subversion&exact=1" rel="nofollow noreferrer">here</a>) using <code>dpkg-deb -x</code>.</p>
<p>So for example you can do this if you're on i386:</p>
<pre>
wget ftp://ftp.debian.org/debian/pool/main/s/subversion/subversion_1.5.4dfsg1-1_i386.deb
dpkg -x subversion_1.5.4dfsg1-1_i386.deb subversion
</pre>
<p>Of course you might have to do some tweaking to make it work. Extracting a package is not the same thing as installing it.</p>
|
<p>Look at the Debian list of <a href="http://packages.debian.org/search?keywords=subversion&exact=1" rel="nofollow noreferrer">SVN packages</a>, I would assume the <a href="http://packages.debian.org/etch/subversion" rel="nofollow noreferrer">etch (stable)</a> is the one you need.</p>
| 35,306
|
<p>I have noticed jQuery (or is it Firefox) will turn some of my <code><span class="presentational"></span> into <span class="presentational" /></code></p>
<p>Now my question is, is this okay to write my markup like this? Will any browsers choke on it?</p>
<p>Personally, I think it looks cleaner to do <code><span class="presentational" /></code> if it's going to be empty.</p>
|
<p>I'm assuming your question has to do with the red trailing slash on self-closing elements when you view source in Firefox. If so, you've stumbled into one of the most vehement, yet simultaneously passive aggressive debates in the browser maker vs. web developer wars. XHTML is NOT just about a document's markup. It's also about how documents are meant to be served over the web. </p>
<p>Before I begin; I'm trying hard not to take sides here.</p>
<p>The XHTML 1.1 spec says that a web server should serve XHTML with a Content-Type of application/xhtml+xml. Firefox is singling out those trailing slashes as invalid because your document is being served as text/html rather than application/xhtml+xml. Take these two examples; identical markup, one served as application/xhtml+xml, the other as text/html.</p>
<p><a href="http://alanstorm.com/testbed/xhtml-as-html.php" rel="noreferrer">http://alanstorm.com/testbed/xhtml-as-html.php</a></p>
<p><a href="http://alanstorm.com/testbed/xhtml-as-xhtml.php" rel="noreferrer">http://alanstorm.com/testbed/xhtml-as-xhtml.php</a></p>
<p>Firefox flags the trailing slash in the meta tag as invalid for the document served with text/html, and valid for the document served with application/xhtml+xml.</p>
<h2>Why this is Controversial</h2>
<p>To a browser developer, the point of XHTML is you can treat your document as XML, which means if someone sends you something that's not valid, the spec says you don't have to parse it. So, if a document is served as application/xhtml+xml and has non-well formed content, the developer is allowed to say "not my problem". You can see that in action here</p>
<p><a href="http://alanstorm.com/testbed/xhtml-not-valid.php" rel="noreferrer">http://alanstorm.com/testbed/xhtml-not-valid.php</a></p>
<p>When a document is served as text/html, Firefox treats it as a plain old HTML document and uses the forgiving, fix it for you, parsing routines </p>
<p><a href="http://alanstorm.com/testbed/xhtml-not-valid-as-html.php" rel="noreferrer">http://alanstorm.com/testbed/xhtml-not-valid-as-html.php</a></p>
<p>So, to a browser maker, XHTML served as text/html is ludicrous, because it's never treated as XML by the browser's rendering engine.</p>
<p>A bunch of years ago, web developers looking to be more than tag monkeys (Disclaimer: I include myself as one of them) started looking for ways to develop best practices that didn't involved thrice nested tables, but still allowed a compelling design experience. They/We latched onto XHTML/CSS, because the W3C said this was the future, and the only other choice was a world where a single vendor (Microsoft) controlled the defacto markup spec. The real evil there being the <em>single vendor</em>, and not so much Microsoft. I swear.</p>
<p>So where's the controversy? There are two problems with application/xhtml+xml. The first is Internet Explorer. There's a legacy bug/feature in IE where content served as application/xhtml+xml will prompt the user to download the document. If you tried to visit the xhtml-as-xhtml.php listed above with IE that's likely what happened. This means if you want to use application/xhtml+xml, you have to <s>browser sniff for IE</s>, check the Accepts header and only serve application/xhtml+xml to those browsers that accept it. This is <a href="https://stackoverflow.com/questions/351380/xhtml-what-are-the-problems-associated-with-serving-pages-with-content-applicat#351908">not as trivial</a> as it sounds to get right, and also went against the "write once" principle that the web developers were striving for.</p>
<p>The second problem is the harshness of XML. This is, again, one of those flame prone issues, but there's some people who think a single bad tag, or single character improperly encoded shouldn't result in a user not seeing the document they want to. In other words, yes, the spec says you should stop processing XML if it's not well formed, but the user doesn't care about the spec, they care that their cat's website is broken.</p>
<p>Adding even more gasoline to the issue is the XHTML 1.0 (not 1.1) spec says that XHTML documents <em>may</em> be served as text/html, assuming certain <a href="http://www.w3.org/TR/xhtml1/#guidelines" rel="noreferrer">compatibility guidelines</a> are followed. Things like the img tag being self closing and the like. The key word here is <em>may</em>. In <a href="http://www.rfc-editor.org/rfc/rfc2119.txt" rel="noreferrer">RFC speak</a>, may means optional. Firefox has chosen NOT to treat documents served with an XHTML doctype but a content type of text/html as XHTML. However, the W3C validator will happily report these documents as valid.</p>
<p>I'll leave the reader to ponder the simultaneous wonder/horror of a culture that writes a document to define what they mean by the word <em>may</em>.</p>
<h2>Moving Forward</h2>
<p>Finally, this is what the whole <a href="http://blog.whatwg.org/category/weekly-review" rel="noreferrer">HTML 5</a> thing is about. XHTML became such a political hot potato that a bunch of people who wanted to move the language forward decided to go in another direction. They produced a spec for HTML 5. This is currently being hashed out in the W3C, and expected to finish sometime in the next decade. In the meantime, browser vendors are picking and choosing features from the in-progress spec and implementing them.</p>
<h2>Updates from the Comments</h2>
<p>In the comments, <a href="https://stackoverflow.com/users/31671/alex">Alex</a> points out that if you're going to sniff for something, you should check the Accept header to see if application/xhtml+xml is accepted by the user agent.</p>
<p>This is absolutely correct. In general, if you're going to sniff, sniff for the feature, not for the browser.</p>
|
<p>Generally it's not a problem to use shorthand for empty elements, but there are some exceptions where it can cause problems.</p>
<p><code><script></code> is an important one that needs to be closed with <code></script></code> to avoid issues.</p>
<p>Another is <code><meta></code> which works much better with spiders written as <code><meta></meta></code> instead of <code><meta /></code></p>
<p>Not exactly the question, but related, in terms of formatting, versions of IE have problems with just empty elements such as <code><div></div></code> or <code><div /></code>. In this case, <code><div>&nbsp;</div></code> is required to maintain the formatting.</p>
| 45,374
|
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p>
<p>How can I represent the equivalent of an Enum in Python? </p>
|
<p><a href="https://docs.python.org/3/library/enum.html" rel="noreferrer">Enums</a> have been added to Python 3.4 as described in <a href="http://www.python.org/dev/peps/pep-0435/" rel="noreferrer">PEP 435</a>. It has also been <a href="https://pypi.python.org/pypi/enum34" rel="noreferrer">backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4</a> on pypi.</p>
<p>For more advanced Enum techniques try the <a href="https://pypi.python.org/pypi/aenum" rel="noreferrer">aenum library</a> (2.7, 3.3+, same author as <code>enum34</code>. Code is not perfectly compatible between py2 and py3, e.g. you'll need <a href="https://stackoverflow.com/a/25982264/57461"><code>__order__</code> in python 2</a>).</p>
<ul>
<li>To use <code>enum34</code>, do <code>$ pip install enum34</code></li>
<li>To use <code>aenum</code>, do <code>$ pip install aenum</code></li>
</ul>
<p>Installing <code>enum</code> (no numbers) will install a completely different and incompatible version.</p>
<hr />
<pre><code>from enum import Enum # for enum34, or the stdlib version
# from aenum import Enum # for the aenum version
Animal = Enum('Animal', 'ant bee cat dog')
Animal.ant # returns <Animal.ant: 1>
Animal['ant'] # returns <Animal.ant: 1> (string lookup)
Animal.ant.name # returns 'ant' (inverse lookup)
</code></pre>
<p>or equivalently:</p>
<pre><code>class Animal(Enum):
ant = 1
bee = 2
cat = 3
dog = 4
</code></pre>
<hr />
<p>In earlier versions, one way of accomplishing enums is:</p>
<pre><code>def enum(**enums):
return type('Enum', (), enums)
</code></pre>
<p>which is used like so:</p>
<pre><code>>>> Numbers = enum(ONE=1, TWO=2, THREE='three')
>>> Numbers.ONE
1
>>> Numbers.TWO
2
>>> Numbers.THREE
'three'
</code></pre>
<p>You can also easily support automatic enumeration with something like this:</p>
<pre><code>def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
</code></pre>
<p>and used like so:</p>
<pre><code>>>> Numbers = enum('ZERO', 'ONE', 'TWO')
>>> Numbers.ZERO
0
>>> Numbers.ONE
1
</code></pre>
<p>Support for converting the values back to names can be added this way:</p>
<pre><code>def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
reverse = dict((value, key) for key, value in enums.iteritems())
enums['reverse_mapping'] = reverse
return type('Enum', (), enums)
</code></pre>
<p>This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw a <code>KeyError</code> if the reverse mapping doesn't exist. With the first example:</p>
<pre><code>>>> Numbers.reverse_mapping['three']
'THREE'
</code></pre>
<hr />
<p>If you are using MyPy another way to express "enums" is with <a href="https://mypy.readthedocs.io/en/stable/literal_types.html#parameterizing-literals" rel="noreferrer"><code>typing.Literal</code></a>.</p>
<p>For example:</p>
<pre class="lang-py prettyprint-override"><code>from typing import Literal #python >=3.8
from typing_extensions import Literal #python 2.7, 3.4-3.7
Animal = Literal['ant', 'bee', 'cat', 'dog']
def hello_animal(animal: Animal):
print(f"hello {animal}")
hello_animal('rock') # error
hello_animal('bee') # passes
</code></pre>
|
<pre><code>def enum( *names ):
'''
Makes enum.
Usage:
E = enum( 'YOUR', 'KEYS', 'HERE' )
print( E.HERE )
'''
class Enum():
pass
for index, name in enumerate( names ):
setattr( Enum, name, index )
return Enum
</code></pre>
| 5,755
|
<p>When I believed in American dream about encapsulation and polymorphism, intrusion of Web Services washed my objects off with RPC calls...</p>
<p>When I cherished my resurrected PONOs, ugly army of barbarians called proxy objects conquered my lands...</p>
<p>Later, peace seemed to come back with DDD and NHibernate on the server side, but the SilverLightning hit my castle, now there's hunger again, delicious lazy loading is only in my memories, and for years now my poor objects have to consume stale services again...</p>
<p>And I am full of fear...the world is talking more and more about some other terrifying procedural monsters...they call them "Workflows"...</p>
<p>How can I save my objects?
Literally, I do not provide anyone any services. I am building a simple small system. I don't want to use services to find my data. I do not want to use services to talk from my web interface to my web interface...as I don't want to use snail mail to talk to my colleagues.</p>
<p>Any ideas? Did you manage to save your objects? Did you manage to save more than your domain model? (hopefully you managed the latter...)</p>
<p><strong>Update:</strong>
If this was not clear...
We have a killed architecture because everything is using web service based.
There was a fashion "OO - is dead", services rule.
In SOA, it is still quite hard to focus on objects when everything is focusing on verbs ("operation contracts"). I feel it is hard to take care of your design.</p>
|
<p>Beware you foolish mortals. The Entity That Is has indeed fed on your polymorphed objects. But this also means that you have inherited the Big Slimy Interface that lurks in the dark. So you can retire your puny barbarians (by proxy if you wish). </p>
<p>And yes, thanks to the Entity That Is, your objects got lazy and have their garbage collected. So their joy is only temporary because their life is immediate ended when they move out of scope. And not a single one of then can get away.</p>
<p>If you show fear to the Entity That Is, dead is only a destructor away. So be careful when you ride the waves of the workflow, because they are as unpredictable as the average market stock.</p>
<p>Your objects are never save for the Entity That Is. Persistance can back them up for a while but eventually all wil fail as the last clock cycle has rung. Fortunately thanks to persistance, your objects can be send to better places where they can multiply and live in peace. </p>
<p>The Entity That Is, is strict but fair, so if you use the propert command, your virtual doors to other realities wil open and allow swift and reliable trafic.</p>
<p>Good luck and honour the Entity That Is, you may not always agree with it, but its rule is the law and death the only penalty.</p>
|
<p>Clearly you haven't take your abstraction pills this morning. Now, take your nice medicine and you'll feel better in a little while...</p>
| 39,387
|
<p>I've alluded to this project before, in this question, but the scope of redesign has been slightly tightened, i.e. I can't redesign the whole thing, so I 'd like some general advice on how to structure the existing artefacts in the application as an incremental step in improving the design.</p>
<ol>
<li><p>The site has two areas of functionality, v.i.z. reporting and maintenance. This is the major function of the site, not data manipulation, but just presentation. The site includes a small number of maintenance pages that use standard GridViews and FormViews for maintaining a small area of data. This is why I have decided against a rich, complex DAL in favour of the Enterprise Library DAAB and plain vanilla datasets. </p></li>
<li><p>Each report is an isolated page that uses results of a dynamic SQL query to explicitly render HTML table rows for the report. In order to not maintain one set of queries for both mySQL and MSSQL for each report, I will move all data access to stored procedures, removing coupling to either DB engine through the DAAB.</p></li>
<li><p>I am looking at reporting tools to decouple the report structure definition from the report presentation. I would prefer to not define report structure in classes, as telerik reporting does, but have yet to look at other reporting tools.</p></li>
<li><p>All reports share a common filter page that is presented on choosing a report from a menu, which redirects to the chosen report once the user is happy with their filter selections. Is there any guidance available for this very common scenario that I seem to have to keep reinventing? </p></li>
</ol>
<p>I am looking for general advice on how to move this toward a better structured product, without actually restructuring the whole project. Simple stuff like separating maintenance pages from report pages in sub-directories, etc. </p>
<p>I'm not looking for others to do my work, and will in due course have implemented many improvements of my own making, but I would appreciate general opinions on how other people would handle a project like this.</p>
|
<p>For presentation of reports based upon a database of facts I would investigate one of the tools that has got all the core functionality already implemented, such as BIRT (and I am sure that there are some .NET alternatives). You might think a table of data is good enough for an intelligent person to parse, but down the line someone will ask for graphs and PDFs.</p>
<p>The maintenance / admin pages can be a standard website - forms and backend, using whatever framework you are comfortable with.</p>
<p>Architecturally wise, are you going to be running the reports against a live database, or an archive database (or the failover/replication DB)?</p>
<p>Are you generating aggregate data tables (fact tables) to generate reports from, or running against the more complex main schema?</p>
|
<p>For presentation of reports based upon a database of facts I would investigate one of the tools that has got all the core functionality already implemented, such as BIRT (and I am sure that there are some .NET alternatives). You might think a table of data is good enough for an intelligent person to parse, but down the line someone will ask for graphs and PDFs.</p>
<p>The maintenance / admin pages can be a standard website - forms and backend, using whatever framework you are comfortable with.</p>
<p>Architecturally wise, are you going to be running the reports against a live database, or an archive database (or the failover/replication DB)?</p>
<p>Are you generating aggregate data tables (fact tables) to generate reports from, or running against the more complex main schema?</p>
| 43,253
|
<p>I have a one-dimensional array of strings in JavaScript that I'd like to turn into a comma-separated list. Is there a simple way in garden-variety JavaScript (or jQuery) to turn that into a comma-separated list? (I know how to iterate through the array and build the string myself by concatenation if that's the only way.)</p>
|
<p>The <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join" rel="noreferrer">Array.prototype.join()</a> method:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = ["Zero", "One", "Two"];
document.write(arr.join(", "));</code></pre>
</div>
</div>
</p>
|
<pre><code>var arr = ["Pro1", "Pro2", "Pro3"];
console.log(arr.join());// Pro1,Pro2,Pro3
console.log(arr.join(', '));// Pro1, Pro2, Pro3
</code></pre>
| 24,641
|
<p>I'd like to run a subcommand from Perl (or pipe it into a Perl script) and have the script process the command's output immediately, rather than waiting for a timeout, a newline, or a certain number of blocks. For example, let's say I want to surround each chunk of input with square brackets. When I run the script like this:</p>
<pre><code>$ ( echo -n foo ; sleep 5 ; echo -n bar ; sleep 5; echo baz) | my_script.pl
</code></pre>
<p>I'd like the output to be this, with each line appearing five seconds after the previous one:</p>
<pre><code>[foo]
[bar]
[baz]
</code></pre>
<p>How do I do that?</p>
<p>This works, but is really ugly:</p>
<pre><code>#! /usr/bin/perl -w
use strict;
use Fcntl;
my $flags = '';
fcntl(STDIN, F_GETFL, $flags);
$flags |= O_NONBLOCK;
fcntl(STDIN, F_SETFL, $flags);
my $rin = '';
vec($rin,fileno(STDIN),1) = 1;
my $rout;
while (1) {
select($rout=$rin, undef, undef, undef);
last if eof();
my $buffer = '';
while (my $c = getc()) {
$buffer .= $c;
}
print "[$buffer]\n";
}
</code></pre>
<p>Is there a more elegant way to do it?</p>
|
<p>From perlfaq5: <a href="http://perldoc.perl.org/perlfaq5.html#How-can-I-read-a-single-character-from-a-file%3f--From-the-keyboard%3f" rel="nofollow noreferrer">How can I read a single character from a file? From the keyboard?</a>. You probably also want to read <a href="http://perldoc.perl.org/perlfaq5.html#How-can-I-tell-whether-there's-a-character-waiting-on-a-filehandle%3f" rel="nofollow noreferrer">How can I tell whether there's a character waiting on a filehandle?</a>. Poll the filehandle. If there is a character there, read it and reset a timer. If there is not character there, try again. If you've retried and passed a certain time, process the input.</p>
<p>After you read the characters, it's up to you to decide what to do with them. With all the flexibility of reading single characters comes the extra work of handling them.</p>
|
<p>You didn't mention how you are reading input in your Perl script, but you might want to look at the <a href="http://perldoc.perl.org/functions/getc.html" rel="nofollow noreferrer"><code>getc</code></a> function:</p>
<pre><code>$|++; # set autoflush on output
while ($c = getc(STDIN)) {
print $c;
}
</code></pre>
| 26,295
|
<p>I want to install a "pastie" in our local intranet. What are the alternatives to <strong><a href="http://p.ramaze.net" rel="nofollow noreferrer">RaPaste</a></strong> and <a href="http://pastie.org" rel="nofollow noreferrer">pastie.org</a>? (the latter can't even be installed locally b/c it doesn't seem to be open source?)</p>
<p><strong>Edit</strong>: Doesn't have to be Ruby btw.</p>
<p><strong>Edit</strong>: What I mean with pastie is an app where you can share source code pastes instead of pasting it in an irc chat.</p>
|
<p>There is for instance <a href="http://dev.pocoo.org/projects/lodgeit/" rel="nofollow noreferrer">LodgeIt</a> by the Pocoo guys.</p>
|
<p>Your request isn't very clear. Starting by defining what are "pasties" in your mind might help (I knew pasties from deviantART, which are very different beasts...). I had to go to the indicated sites to have an idea.<br>
It isn't clear either if it must be Ruby only or not (I see only a tag, no clear requirement).</p>
<p>I know the old and reputed pastebin.org, <a href="http://blog.dixo.net/downloads/" rel="nofollow noreferrer" title="pastebin.org source">its (PHP) source</a> is available.</p>
| 26,852
|
<p>Ignoring the IE case, are there any other browsers that can't understand the application/xhtml+xml content type? And what about the search engine spiders?</p>
<p>I could not find any answers on the web that would not be a few years old and thus possibly inaccurate.</p>
<p><strong>Edit:</strong>
Somehow related question: <a href="https://stackoverflow.com/questions/278746/what-problem-does-xhtml-strict-solve">What problem does XHTML strict solve?</a></p>
|
<p>If you ignore 80% of the market (yes, IE) then XHTML is very well supported, and search engines have no problem with it whatsoever (after all, XHTML is a lot simpler to process).</p>
<p>Overall, XHTML support isn't really a problem. IE doesn't support it, but as long as it's served as a contenttype it does understand, will render it okay anyway, and everyone else support it properly.</p>
<p>Do you have more specific use cases in mind?</p>
|
<p>Since new browsers are invented at a steady pace, there's no definite value for "any" in "any other browsers".</p>
<p>You have to (1) pick some browsers you think you'd like to support, (2) check those specific browsers.</p>
<p>Look at a page like <a href="http://browsershots.org/" rel="nofollow noreferrer">BrowserShots</a> to see a list of browsers you might be interested in supporting.</p>
<p>Look at <a href="http://www.thefreecountry.com/webmaster/htmlvalidators.shtml" rel="nofollow noreferrer">Free HTML Validators</a> for XHTML compatibility.</p>
| 35,490
|
<p>Given a string like this:</p>
<blockquote>
<p>a,"string, with",various,"values, and some",quoted</p>
</blockquote>
<p>What is a good algorithm to split this based on commas while ignoring the commas inside the quoted sections?</p>
<p>The output should be an array:</p>
<blockquote>
<p>[ "a", "string, with", "various", "values, and some", "quoted" ]</p>
</blockquote>
|
<p>Looks like you've got some good answers here.</p>
<p>For those of you looking to handle your own CSV file parsing, heed the advice from the experts and <a href="http://secretgeek.net/csv_trouble.asp" rel="noreferrer">Don't roll your own CSV parser</a>.</p>
<p>Your first thought is, <em>"I need to handle commas inside of quotes."</em></p>
<p>Your next thought will be, <em>"Oh, crap, I need to handle quotes inside of quotes. Escaped quotes. Double quotes. Single quotes..."</em></p>
<p>It's a road to madness. Don't write your own. Find a library with an extensive unit test coverage that hits all the hard parts and has gone through hell for you. For .NET, use the free <a href="http://www.filehelpers.com/" rel="noreferrer">FileHelpers</a> library.</p>
|
<p>I use this to parse strings, not sure if it helps here; but with some minor modifications perhaps?</p>
<pre><code>function getstringbetween($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "this is my [tag]dog[/tag]";
$parsed = getstringbetween($fullstring, "[tag]", "[/tag]");
echo $parsed; // (result = dog)
</code></pre>
<p>/mp</p>
| 2,802
|
<p>Can someone point me a good step-by-step tutorial to consuming an already running web service in java?</p>
<p>PS: I tried creating the classes with <code>wsconsume</code>, but it cries with<br>
<code>[ERROR] rpc/encoded wsdls are not supported in JAXWS 2.0.</code> (my web service is rpc/encoded)</p>
<p>If I can consume web services entirely by hand (using no wizards), and understand how is it working, then I'll be happy.</p>
<p>Thanks!</p>
<p><strong>Update</strong>: I have found out that rpc web services are not consumed using <code>jbossws</code>, but <code>jboss-jaxrpc</code>, which implements the JAX-RPC specification. I've found a guide for JAX-RPC <a href="http://www.ibm.com/developerworks/library/ws-jaxrpc1/" rel="nofollow noreferrer">here</a>, but I'm still looking for other guides that could help.</p>
|
<p><a href="http://cxf.apache.org/" rel="nofollow noreferrer">Apache CXF</a> is the easiest way to get webservices running. Specifically look at the <a href="http://cwiki.apache.org/CXF20DOC/simple-frontend.html" rel="nofollow noreferrer">Simple Frontend</a>. The simple front end uses reflection to convert the method/data types to a webservice. It doesn't get much easier than that. </p>
<p>CXF is pretty stable, but does not include all the WS specifications (WS-Eventing for example).</p>
|
<p>If you have the WSDL and XSD files, you can use the <a href="http://ws.apache.org/axis/" rel="nofollow noreferrer">Axis</a> web-services library to create Java classes that will interact with the services they describe. From the stand-point of this library, you are creating a client application.</p>
| 23,415
|
<p>What's the best way to load HTML markup for a custom jQuery UI widget?</p>
<p>So far, I've seen elements simply created using strings (i.e. <code>$(...).wrap('<div></div>')</code>) which is fine for something simple. However, this makes it extremely difficult to modify later for more complex elements.</p>
<p>This seems like a fairly common problem, but I also know that the jQuery UI library is new enough that there may not be a widely accepted solution for this. Any ideas?</p>
|
<p>Something which is quite neat to do is this:</p>
<pre><code>var newDiv = $("<div></div>"); //Create a new element and save a reference
newDiv.attr("id","someid").appendTo("body");
</code></pre>
<p>That way, you are creating an element, and storing its reference in a variable, for later use.</p>
|
<p>A popular, efficient method is to output all of your additional markup (whatever you may need later) to the bottom of your page in script tags, so that the markup is not rendered by the browser.</p>
<pre><code><script type="text/template" id="template-example">
<!-- All of your markup here -->
<% // do some JavaScript in here... %>
<%= echo_this_variable %>
</script>
</code></pre>
<p>You can then grab your markup using jQuery...</p>
<pre><code>var markup = $('#template-example').html();
</code></pre>
<p>And parse those JS examples I threw in there using a templating engine, such as the one in <a href="http://underscorejs.org/#template" rel="nofollow noreferrer">Underscore.js</a> (which I recommend), or one of the jQuery ones in this answer: <a href="https://stackoverflow.com/questions/170168/jquery-templating-engines">jQuery templating engines</a></p>
<p>Have fun!</p>
| 46,180
|
<p>Has anyone out there got a good set of instructions for building/compiling Ruby from source of windows XP ?</p>
|
<p><a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/184380" rel="nofollow noreferrer">http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/184380</a></p>
<p>I normally get a binary installable for windows.. much faster if you just need Ruby installed. But you may be modifying ruby source.. anyways.. </p>
<p><strong>Update:</strong> I ended up compiling Ruby from source today... here is what worked for me
<a href="http://madcoderspeak.blogspot.com/2009/06/how-to-compile-ruby-from-source-on.html" rel="nofollow noreferrer">http://madcoderspeak.blogspot.com/2009/06/how-to-compile-ruby-from-source-on.html</a></p>
|
<p>I would agree that the binary distrubtion is your best bet for Ruby on Windows, however, like Gishu mentioned, you may be modifying it a bit. If that's the case I would build it from source with <a href="http://www.cygwin.com/" rel="nofollow noreferrer">Cygwin</a>. This will give you the familiar tool set for building software from source.</p>
<p>However <a href="http://www.ruby-forum.com/topic/58141" rel="nofollow noreferrer">the following thread at Ruby Forum</a> seems to have a very active discussion on building Ruby in Windows using Microsoft's Visual C++ toolkit with some other .NET additions. </p>
<p>Good luck!</p>
| 13,273
|
<p>I have a small form inside a table. POSTing that form creates a new entity. I then want users to see that new entity, but it should open in a new window so that the original view isn't lost.</p>
<p>(How) can I open the result of the form submission in a new window?</p>
|
<pre><code><form ... target="windowName">
</code></pre>
<p>or</p>
<pre><code><form ... target="windowName" onsubmit="window.open(this.action, this.target, '...attributes...');return true;">
</code></pre>
<p>...attributes... can consist of the stuff documented at the <a href="https://developer.mozilla.org/en/DOM/window.open#Position_and_size_features" rel="nofollow noreferrer">mozilla developer center</a> or <a href="http://msdn.microsoft.com/en-us/library/ms536651.aspx" rel="nofollow noreferrer">MSDN</a></p>
|
<p>One request, one response. That is the way of the web. </p>
<p>If you want a new window after a post, you either need to post the request from the new window in the first place- perhaps opened via javascript- or post your data from that page to the <em>same</em> page and save a token so that when the page re-loads is can open a new windows -again, likely with javascript- and that new window's request already knows about the previous post.</p>
| 46,521
|
<p>I have a Website that is really slow and "feels" really bad when using it. The server is fine, it's a clientside issue, I assume because too much JavaScript or Image Requests, but since it's not my own Website, I wonder if there is a way to show and profile the Page from within IE.</p>
<p>In Firefox, I would use Firebug, Y!Slow and the Web Developer extention to see all JavaScript, CSS, Images and other Requests, AJAX Requests etc., but on IE I did not see any problem. I know I could use Firefox, but the page works better in FF than in IE, so i wonder if there is some Development Addon specifically in IE.</p>
<p><strong>Edit:</strong> Thanks for the many suggestions! Too many good answers to pick one as "accepted", but i'll have a look at the various tools suggested.</p>
|
<p>There is the <a href="http://www.microsoft.com/en-us/download/details.aspx?id=18359" rel="nofollow noreferrer">Internet Explorer Web Developer Toolbar</a>. It isn't as good as Firebug IMHO, but it works.</p>
<p>IE8 will ship with one built-in, too.</p>
|
<p>There's a JS library called firebug light, you need to include it in your site. What it does for you is it enables you to pop up a div in which you can spit text, like in firebug, with the same statements you do it in firebug. MochiKit has something like this too.</p>
| 14,200
|
<p>I'm writing a php program that pulls from a database source. Some of the varchars have quotes that are displaying as black diamonds with a question mark in them (�, <a href="http://www.fileformat.info/info/unicode/char/fffd/index.htm" rel="noreferrer">REPLACEMENT CHARACTER</a>, I assume from Microsoft Word text).</p>
<p>How can I use php to strip these characters out?</p>
|
<p>If you see that character (� U+FFFD "REPLACEMENT CHARACTER") it usually means that the text itself is encoded in some form of single byte encoding but interpreted in one of the unicode encodings (UTF8 or UTF16).</p>
<p>If it were the other way around it would (usually) look something like this: ä.</p>
<p>Probably the original encoding is ISO-8859-1, also known as Latin-1. You can check this without having to change your script: Browsers give you the option to re-interpret a page in a different encoding -- in Firefox use "View" -> "Character Encoding". </p>
<p>To make the browser use the correct encoding, add an HTTP header like this:</p>
<pre><code>header("Content-Type: text/html; charset=ISO-8859-1");
</code></pre>
<p>or put the encoding in a meta tag:</p>
<pre><code><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</code></pre>
<p>Alternatively you could try to read from the database in another encoding (UTF-8, preferably) or convert the text with <a href="http://php.net/manual/function.iconv.php" rel="noreferrer"><code>iconv()</code></a>.</p>
|
<p>Go to your phpmyadmin and select your database and just increase the length/value of that table's field to 500 or 1000 it will solve your problem.</p>
| 34,708
|
<p>So i have this local SVN repo that i am using for my dev work on a particular project, and i also have a SVN repo setup on the customers media temple account for a more secure backup. </p>
<p>I do all of my development on my laptop so i don't always have an internet connection (hence the local SVN), so i was wondering if there is an easy way to push the changes i commit to my local repo onto the server repo?</p>
|
<p>You will probably want to <code>svn merge</code> versions between repositories. </p>
<p>There are some good tutorials around how you can do that. Give a look at <a href="http://blog.red-bean.com/sussman/?p=92" rel="nofollow noreferrer">http://blog.red-bean.com/sussman/?p=92</a> or <a href="http://subversion.tigris.org/faq.html#multi-merge" rel="nofollow noreferrer">http://subversion.tigris.org/faq.html#multi-merge</a> for a good introduction on that topic</p>
|
<p>So the solution i came up with is the use the svnadmin dump/load functions. I am mainly using this with a Ruby on Rails project that i am deploying to a media temple account. The idea is that when a new version of the site is ready to be deployed, the code that is checked into my local repository will be dumped to a file, that file will then be copied to the server via ssh. Once on the server i will use ssh to execute a shell script that does the load into the server SVN. i will then check out that server code, copy it to the rails app directory, run the migrations, and then restart the server. </p>
<p>The thought is that by using this method i can ensure that the code that is currently in production is reflective of the most recent revision in the servers SVN repo. </p>
<p>Thanks for Fernando for providing the link to the dump/load functions.</p>
<p>For the record i did evaluate the Git solution before i posted this question, and due to the fact that i am using NetBeans as my IDE for this project (NetBeans has a really great Ruby/RoR plugin) the Git plugin for NB appears to be kinda buggy and didn't work quite right, whereas the SVN plugin is rock solid. </p>
| 21,134
|
<p>How do I set the symbol for the <em>angle</em> or <em>annuity</em> operation in LaTeX? Specifically, this is the actuarial <em>a</em> angle <em>s</em> = (1-v<sup>s</sup>)/i.</p>
|
<p>For a <em>very</em> comprehensive list of LaTeX symbols, see <a href="http://www.ctan.org/tex-archive/info/symbols/comprehensive/symbols-a4.pdf" rel="nofollow noreferrer">The Comprehensive LaTeX Symbol List</a>. Worth printing out and keeping under your pillow. Page 95 has some code that may do what you want.</p>
|
<p>\annu<br>
A good list of latex symbols can be found here <a href="http://www.ctan.org/tex-archive/info/symbols/comprehensive/symbols-a4.pdf" rel="nofollow noreferrer">http://www.ctan.org/tex-archive/info/symbols/comprehensive/symbols-a4.pdf</a> </p>
| 11,502
|
<p>At the moment I am working on a project admin application in C# 3.5 on ASP.net. In order to reduce hits to the database, I'm caching a lot of information using static variables. For example, a list of users is kept in memory in a static class. The class reads in all the information from the database on startup, and will update the database whenever changes are made, but it never needs to read from the datebase.</p>
<p>The class pings other webservers (if they exist) with updated information at the same time as a write to the database. The pinging mechanism is a Windows service to which the cache object registers using a random available port. It is used for other things as well.</p>
<p>The amount of data isn't all that great. At the moment I'm using it just to cache the users (password hashes, permissions, name, email etc.) It just saves a pile of calls being made to the database.</p>
<p>I was wondering if there are any pitfalls to this method and/or if there are better ways to cache the data?</p>
|
<p>A pitfall: A static field is scoped per app domain, and increased load will make the server generate more app domains in the pool. This is not necessarily a problem if you only read from the statics, but you will get duplicate data in memory, and you will get a hit every time an app domain is created or recycled.</p>
<p>Better to use the Cache object - it's intended for things like this.</p>
<p>Edit: Turns out I was wrong about AppDomains (as pointed out in comments) - more instances of the <em>Application</em> will be generated under load, but they will all run in the same AppDomain. (But you should still use the Cache object!)</p>
|
<p>Hmmm... The "classic" method would be the application cache, but provided you never update the static variables, or understand the locking issues if you do, and you understand that they can disappear at anytime with an appdomain restart then I don't really see the harm in using a static.</p>
| 18,206
|
<p>I have designed a xml schema to parse an incoming xml document. The receive location gets xml documents from 2 feeds, one of them has misspelled a node in the document, "Roookie" instead of "Rookie", Is there a way to have my existing xsd parse this document?</p>
|
<p>You could probably preprocess the wrong XML file, like with this simple XSL stylesheet:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no"/>
<xsl:template match="Roookie">
<Rookie>
<xsl:apply-templates select="@*|node()" />
</Rookie>
</xsl:template>
<xsl:template match="@*|node()" name="defaultRule">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
</code></pre>
|
<p>You would need to replace the elements in the document or modify the xsd to work with the new document format.</p>
| 38,979
|
<p>We recently discovered that the Google Maps API does not play nicely with SSL. Fair enough, but what are some options for overcoming this that others have used effectively?</p>
<blockquote>
<p><a href="http://code.google.com/support/bin/answer.py?answer=65301&topic=10945" rel="noreferrer">Will the Maps API work over SSL (HTTPS)?</a></p>
<p>At this time, the Maps API is not
available over a secure (SSL)
connection. If you are running the
Maps API on a secure site, the browser
may warn the user about non-secure
objects on the screen.</p>
</blockquote>
<p>We have considered the following options</p>
<ol>
<li>Splitting the page so that credit card collection (the requirement for SSL) is not on the same page as the Google Map.</li>
<li>Switching to another map provider, such as Virtual Earth. Rumor has it that they support SSL.</li>
<li>Playing tricks with IFRAMEs. Sounds kludgy.</li>
<li>Proxying the calls to Google. Sounds like a lot of overhead.</li>
</ol>
<p>Are there other options, or does anyone have insight into the options that we have considered?</p>
|
<p>I'd agree with the previous two answers that in this instance it may be better from a usability perspective to split the two functions into separate screens. You really want your users to be focussed on entering complete and accurate credit card information, and having a map on the same screen may be distracting.</p>
<p>For the record though, Virtual Earth certainly does fully support SSL. To enable it you simple need to change the script reference from http:// to https:// and append &s=1 to the URL, e.g.</p>
<pre><code><script src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1" type="text/javascript"></script>
</code></pre>
<p>becomes</p>
<pre><code><script src="https://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1&s=1" type="text/javascript"></script>
</code></pre>
|
<p>I 've just removed the http protocol and it worked!</p>
<p>From this:</p>
<pre><code><script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>
</code></pre>
<p>To this:</p>
<pre><code><script src="//maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>
</code></pre>
| 2,556
|
<p>For a while the proactive caching process successfully sync the OLAP databse and then is starts giving the following error 'Errors in the OLAP storage engine: The attribute key cannot be found:' followed by spesific data related information. I do not however have a problem if I manually process the databse with the 'Transactional Deployement' option set to True. I have set the data source isolation mode to snapshot and MARS connection setting to True on the connection string plus on the database side we have set the database property ALLOW SNAPSHOT_ISOLATION to ON and verified it. Can anyone help or give some suggestions</p>
|
<p>Your measure is being rebuilt and there is a key value not found in your dimension table (this is basically a race condition).</p>
<p>If data integrity is paramount, then you will need to do a full process of the cube.</p>
<p>If you can get away with some aggregates being off temporarily (or assigned to "Unknown" in the Dimension) then you can customize the Error Configuration to ignore errors or assign unknown keys to Unknown. It should work itself out the next time the measure is rebuilt.</p>
|
<p>It sounds like a new dimension key was added - and used by your fact table. The dimension key isn't in the cube yet, so it's not found when referenced by the fact...</p>
<p>This can happen quite easily, and is only fixed by a full reprocess (or if you're lucky, good timing of proactive caching on dimensions and facts).</p>
| 22,827
|
<p><a href="http://www.codinghorror.com/blog/archives/001187.html" rel="nofollow noreferrer">Jeff's recent article</a> linked to a <a href="http://www.ams.org/featurecolumn/archive/bins1.html" rel="nofollow noreferrer">time management example</a> of the <a href="http://en.wikipedia.org/wiki/Bin_packing_problem#Analysis_of_heuristic_algorithms" rel="nofollow noreferrer">First Fit Decreasing</a> algorithm, which talked about the <a href="http://en.wikipedia.org/wiki/Pareto_principle" rel="nofollow noreferrer">Pareto principle</a> (or, the 80/20 rule) of time management, that is, that 80% of the work we produce in 20% of our time.</p>
<p>Now we've all heard the programmer <a href="https://stackoverflow.com/questions/58640/great-programming-quotes#58854">quote</a>:</p>
<blockquote>
<p>The first 90% of the code accounts for
the first 90% of the development time.
The remaining 10% of the code accounts
for the other 90% of the development
time.</p>
</blockquote>
<p>But all jokes aside, it is often as if 20% of your code is to do what you want, and the other 80% is to handle exceptions... so does the 80/20 rule really apply to developers?</p>
<p>Does anyone have any examples of why it does / does not apply to us?</p>
|
<p>I think Hofstadter's Law applies.</p>
<blockquote>
<p>It always takes longer than you expect, even when you take Hofstadter's Law into account.</p>
<p>--Douglas Hofstadter</p>
</blockquote>
<p>On a more serious note, take a look at <a href="http://en.wikipedia.org/wiki/Critical_chain" rel="noreferrer">Critical Chain Project Management</a>. It recommends that you give two estimates for each step in your project. One is an optimistic estimate that you're about 50% sure you can meet if everything goes right. The other is a more realistic estimate that takes lost time and mistakes into account (my paraphrasing, don't blame the author). Over time and several projects you'll learn which estimate is more accurate, and by how much. It varies by developer, so you need to keep track.</p>
|
<p>I am with Bill the Lizard. It ALWAYS takes longer than expected due to very unexpected things or probably things that weren't taken into account.</p>
| 37,641
|
<p>I've seen a couple of web pages say that <code>a = b || 'blah'</code> should assign <code>'blah'</code> to <code>a</code> if <code>b</code> is <code>undefined</code> or <code>null</code>. But if I type that into Firebug or use it in code, it complains that <code>b</code> is not defined, at the list on FF3/win. Any hints?</p>
<p>Edit: I'm looking for the case where <code>b</code> may not exist at all. For example, a DOM node without an <code>id</code>.</p>
|
<p>If b existed, and was false, null, etc, then it works in the way that you would expect. All you'll need to do is on the line above that, put <code>var b = null</code>;</p>
<p>This makes sense if you think about it. It basically does something like this...</p>
<pre><code>a = function(){ if(b){return b;} else{ return 'blah' } }();
</code></pre>
<p>Note it is checking that the value of b is truthy... if b doesn't exist, you get an exception.</p>
<h3>Regarding Undefined variables</h3>
<p>"Undefined" in javascript doesn't mean 'variable doesn't exist'. It means "the value of the variable is the special value of <code>undefined</code>". Example:</p>
<pre><code>alert(nosuchvariable);
=> throws exception
var somevariable; // note it's never assigned
alert(somevariable);
=> This alerts with 'undefined'
</code></pre>
<h3>Regarding Checking if variables exist.</h3>
<p>So if we try to read <code>b</code> and there is no such variable as b, we get an exception. If we're trying to find out if b is defined, then this isn't helpful.</p>
<p>You can see if global variables exist by checking the top-level <code>window</code> object. All global variables are actually just fields in the <code>window</code> object. Example:</p>
<pre><code>foo = 'Hello';
alert( window.foo );
=> alerts 'Hello'
</code></pre>
<p>Because you know the window object already exists, you can check it's fields.<br>
Checking for fields that don't exist in javascript will give you <code>undefined</code> and won't crash, so you can then do the coalesce, or put the <code>undefined</code> in a variable or whatever</p>
<p>For <strong>local</strong> variables (things declared with <code>var</code>), <s>you can't check for their existence.</s> they don't "live" anywhere in the way that global variables "live" in the window object, and any normal attempt to reference one will cause an exception: eg:</p>
<pre><code>alert(a);
=> exception because a is meaningless
alert(d45pwiu4309m9rv43);
=> exception because that is equally meaningless
</code></pre>
<p>There is however one exception (that I know of, thanks J c in the comments), the <code>typeof</code> operator. If you try and get the type of something that doesn't exist, it <em>won't</em> crash, it will return <em>the string</em> <code>"undefined"</code>.<br>
This gives you a way of checking for non-existent local variables. eg:</p>
<pre><code>if( typeof(djfsd) === "undefined" )
alert('no such variable');
</code></pre>
<h3>Regarding DOM elements that don't exist</h3>
<p>There have been several comments mentioning DOM elements without ID's and so forth...</p>
<p>The fact that it's a DOM element isn't really relevant. Think of the DOM as a database or a file, and an element as a row in that database or word in that file. In order to <em>do</em> anything with it, you have to go searching through the database, find the right row, and pull it's data out. The data gets put into a javascript object. You then access it by manipulating that object, and maybe putting the object in a variable if you like. Example:</p>
<pre><code>document.getElementById('foo');
</code></pre>
<p>this goes into the dom and looks for an element with an ID of 'foo'. If it finds one, it puts some information about that element into a javascript object, and then hands that object back to you. If it can't find the element, it will hand you back <code>null</code>, but all the normal rules still apply (you can stick the <code>null</code> in a variable, or whatever).</p>
<p>It doesn't affect the coalesce at all.</p>
|
<p><code>||</code> is the short-circuited logical OR operator in JavaScript, much like it is in C, C++, Java, C#, Perl, PHP, etc.</p>
<p><a href="http://en.wikipedia.org/wiki/%3F%3F_Operator#JavaScript_implementation" rel="nofollow noreferrer">According to Wikipedia</a>, if you put parentheses around <code>b</code>, it will work as you expect.</p>
<pre><code>var a = (b) || 'blah';
</code></pre>
| 38,922
|
<p>In WindowsForms world you can get a list of available image encoders/decoders with</p>
<pre><code>System.Drawing.ImageCodecInfo.GetImageDecoders() / GetImageEncoders()
</code></pre>
<p>My question is, is there a way to do something analogous for the WPF world that would allow me to get a list of available </p>
<pre><code>System.Windows.Media.Imaging.BitmapDecoder / BitmapEncoder
</code></pre>
|
<p>You've got to love .NET reflection. I worked on the WPF team and can't quite think of anything better off the top of my head. The following code produces this list on my machine:</p>
<pre><code>Bitmap Encoders:
System.Windows.Media.Imaging.BmpBitmapEncoder
System.Windows.Media.Imaging.GifBitmapEncoder
System.Windows.Media.Imaging.JpegBitmapEncoder
System.Windows.Media.Imaging.PngBitmapEncoder
System.Windows.Media.Imaging.TiffBitmapEncoder
System.Windows.Media.Imaging.WmpBitmapEncoder
Bitmap Decoders:
System.Windows.Media.Imaging.BmpBitmapDecoder
System.Windows.Media.Imaging.GifBitmapDecoder
System.Windows.Media.Imaging.IconBitmapDecoder
System.Windows.Media.Imaging.LateBoundBitmapDecoder
System.Windows.Media.Imaging.JpegBitmapDecoder
System.Windows.Media.Imaging.PngBitmapDecoder
System.Windows.Media.Imaging.TiffBitmapDecoder
System.Windows.Media.Imaging.WmpBitmapDecoder
</code></pre>
<p>There is a comment in the code where to add additional assemblies (if you support plugins for example). Also, you will want to filter the decoder list to remove:</p>
<pre><code>System.Windows.Media.Imaging.LateBoundBitmapDecoder
</code></pre>
<p>More sophisticated filtering using constructor pattern matching is possible, but I don't feel like writing it. :-)</p>
<p>All you need to do now is instantiate the encoders and decoders to use them. Also, you can get better names by retrieving the <code>CodecInfo</code> property of the encoder decoders. This class will give you human readable names among other factoids.</p>
<pre><code>using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Windows.Media.Imaging;
namespace Codecs {
class Program {
static void Main(string[] args) {
Console.WriteLine("Bitmap Encoders:");
AllEncoderTypes.ToList().ForEach(t => Console.WriteLine(t.FullName));
Console.WriteLine("\nBitmap Decoders:");
AllDecoderTypes.ToList().ForEach(t => Console.WriteLine(t.FullName));
Console.ReadKey();
}
static IEnumerable<Type> AllEncoderTypes {
get {
return AllSubclassesOf(typeof(BitmapEncoder));
}
}
static IEnumerable<Type> AllDecoderTypes {
get {
return AllSubclassesOf(typeof(BitmapDecoder));
}
}
static IEnumerable<Type> AllSubclassesOf(Type type) {
var r = new Reflector();
// Add additional assemblies here
return r.AllSubclassesOf(type);
}
}
class Reflector {
List<Assembly> assemblies = new List<Assembly> {
typeof(BitmapDecoder).Assembly
};
public IEnumerable<Type> AllSubclassesOf(Type super) {
foreach (var a in assemblies) {
foreach (var t in a.GetExportedTypes()) {
if (t.IsSubclassOf(super)) {
yield return t;
}
}
}
}
}
}
</code></pre>
|
<p>Hopefully someone will correct me if I'm wrong, but I don't think there's anything like that in WPF. But hopefully this is one of the many cases where advances in the technology have rendered obsolete the way we're used to doing things. Like "how do I wind my digital watch?"</p>
<p>To my understanding, the reason why ImageCodecInfo.GetImageDecoders() is necessary in System.Drawing has to do with the kludgy nature of System.Drawing itself: System.Drawing is a managed wrapper around GDI+, which is an unmanaged wrapper around a portion of the Win32 API. So there might be a reason why a new codec would be installed in Windows without .NET inherently knowing about it. And what's returned from GetImageDecoders() is just a bunch of strings that are typically passed back into System.Drawing/GDI+, and used to find and configure the appropriate DLL for reading/saving your image.</p>
<p>On the other hand, in WPF, the standard encoders and decoders are built into the framework, and, if I'm not mistaken, don't depend on anything that that isn't guaranteed to be installed as part of the framework. The following classes inherit from BitmapEncoder and are available out-of-the-box with WPF: BmpBitmapEncoder, GifBitmapEncoder, JpegBitmapEncoder, PngBitmapEncoder, TiffBitmapEncoder, WmpBitmapEncoder. There are BitmapDecoders for all the same formats, plus IconBitmapDecoder and LateBoundBitmapDecoder.</p>
<p>You may be dealing with a case I'm not imagining, but it seems to me that if you're having to use a class that inherits from BitmapEncoder but wasn't included with WPF, it's probably your own custom class that you would install with your application.</p>
<p>Hope this helps. If I'm missing a necessary part of the picture, please let me know.</p>
| 3,578
|
<p>Where would you write an error log file, say <code>ErrorLog.txt</code>, in Windows? Keep in mind the path would need to be open to basic users for file write permissions.</p>
<p>I know the eventlog is a possible location for writing errors, but does it work for "user" level permissions?</p>
<p>EDIT: I am targeting Windows 2003, but I was posing the question in such a way as to have a "General Guideline" for where to write error logs.<br>
As for the EventLog, I have had issues before in an ASP.NET application where I wanted to log to the Windows event log, but I had security issues causing me heartache. (I do not recall the issues I had, but remember having them.)</p>
|
<p>Have you considered logging the event viewer instead? If you want to write your own log, I suggest the users local app setting directory. Make a product directory under there. It's different on different version of Windows.</p>
<p>On Vista, you cannot put files like this under c:\program files. You will run into a lot of problems with it. </p>
<p>In .NET, you can find out this folder with this:</p>
<pre><code>Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
</code></pre>
<p>And the Event Log is fairly simple to use too:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx</a></p>
|
<p>Put it in the directory of the application. The users will need access to the folder to run and execute the application, and you can check write access on application startup.</p>
<p>The event log is a pain to use for troubleshooting, but you should still post significant errors there.</p>
<p>EDIT - You should look into the MS Application Blocks for logging if you are using .NET. They really make life easy.</p>
<p>Jeez Karma-killers. Next time I won't even offer a suggestion when the poster puts up an incomplete post.</p>
| 23,268
|
<p>I have the following problem in my <i>Data Structures and Problem Solving using Java</i> book:</p>
<blockquote>
<p>Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator.</p>
</blockquote>
<p>I'm not putting it up here because I want somebody to do my homework, I just can't seem to understand exactly what it is asking for me to code!</p>
<p>When it asks me to write a 'routine', is it looking for a single method? I don't really understand how I can make a single method work for all of the various types of Collections (linked list, queue, stack).</p>
<p>If anybody could guide me in the right direction, I would greatly appreciate it.</p>
|
<p>Regardless from the question not making much sense as half of the collections have no gstable ordering of have fixed-ordering (i.e. TreeSet or PriorityQueue), you can use the following statement for printing the contents of a collection in reverse-natural order:</p>
<pre><code>List temp = new ArrayList(src);
Collections.reverse(temp);
System.out.println(temp);
</code></pre>
<p>I essence you create an array list as lists are the only structure that can be arbitrarily reordered. You pass the <em>src</em> collection to the constructor which initializes the list withj the contents of the <em>src</em> in the collection natural order. Then you pass the list to the <em>Collections.reverse()</em> method which reverses the list and finally you print it.</p>
|
<p>Well you could have a routine that delegates to other routines based on the input type, however I'm not sure there is a generic enough collection type that can be encompassed into one argument. I guess you could just use method overloading (having multiple methods with the same name, but accept different args).</p>
<p>That could technically count as 1 routine (all have the same name).</p>
| 23,887
|
<p>Using <a href="http://en.wikipedia.org/wiki/Apache_Ant" rel="nofollow noreferrer">Ant</a> I could unzip an archive before proceeding with the build per-se ... Is this possible using nmake? Could I call an external application? Or even a batch script?</p>
|
<p>Any variant on make has the ability to perform any task that can be done from the command line. Indeed, most of the build functionality of any makefile is going to depend upon the onvocation of external processes such as the compiler, linker, librarian, etc. The only downside to make is that there are so many variations of syntax (nmake, borland make, GNU make, etc.) that make it practically impossible to write a single cross-platform makefile.</p>
<p>In answer to your particular question consider the following:</p>
<blockquote>
<pre>
main.cpp: archive.zip
unzip archive.zip
</pre>
</blockquote>
<p>This basically states that main.cpp depends upon archive.zip and states that this dependency can be satisfied by invoking the "unzip" command. </p>
|
<p>You can call an external application from nmake Makefiles, just as from any other Makefile.</p>
<p>However, what to call? You'll need to have WinZip command line tools or something installed, right?</p>
<p>I'd recommend looking at <a href="http://www.scons.org/" rel="nofollow noreferrer">SCons</a>. It is a wonderful build engine, fully supports Windows and MSVC++, and has unzipping built in.</p>
| 17,892
|
<p>So far I've figured out how to pass Unicode strings, bSTRs, to and from a Euphoria DLL using a Typelib. What I can't figure out, thus far, is how to create and pass back an array of BSTRs.</p>
<p>The code I have thus far (along with <code>include</code>s for EuCOM itself and parts of Win32lib):</p>
<pre><code>global function REALARR()
sequence seq
atom psa
atom var
seq = { "cat","cow","wolverine" }
psa = create_safearray( seq, VT_BSTR )
make_variant( var, VT_ARRAY + VT_BSTR, psa )
return var
end function
</code></pre>
<p>Part of the typelib is:</p>
<pre><code> [
helpstring("get an array of strings"),
entry("REALARR")
]
void __stdcall REALARR( [out,retval] VARIANT* res );
</code></pre>
<p>And the test code, in VB6 is:</p>
<pre><code>...
Dim v() as String
V = REALARR()
...
</code></pre>
<p>So far all I've managed to get is an error '0' from the DLL. Any ideas? Anyone?</p>
|
<p>You should use the <code>create_safearray()</code> function. It's documented (hidden?) under Utilities. Basically, put your BSTR pointers into a sequence and pass it to <code>create_safearray()</code>:</p>
<pre><code>sequence s, bstrs
s = {"A", "B"}
bstrs = {}
for i = 1 to length(s) do
bstrs &= alloc_bstr( s[i] )
end for
atom array
array = create_safearray( bstrs, VT_BSTR )
...
destroy_safearray( array )
</code></pre>
|
<p>I've been in touch with the Euphoria people via their <a href="http://openeuphoria.org/EUforum/index.cgi?module=forum&action=flat&id=102589#unread" rel="nofollow noreferrer">forum</a>, and have gotten this far. The routine is failing on the the make_variant line. I haven't figured it out any further than that and neither have they.</p>
<pre><code>global function REALARR()
atom psa
atom var
atom bounds_ptr
atom dim
atom bstr
object void
dim = 1
bounds_ptr = allocate( 8 * dim ) -- now figure out which part is Extent and which is LBound
poke4( bounds_ptr, { 3, 0 } ) -- assuming Extent and LBound in that order
psa = c_func( SafeArrayCreate, { VT_BSTR, 1, bounds_ptr } )
bstr = alloc_bstr( "cat" )
poke4( bounds_ptr, 0 )
void = c_func( SafeArrayPutElement, {psa, bounds_ptr, bstr})
free_bstr( bstr )
bstr = alloc_bstr( "cow" )
poke4( bounds_ptr, 1 )
void = c_func( SafeArrayPutElement, {psa, bounds_ptr, bstr})
free_bstr( bstr )
bstr = alloc_bstr( "wolverine" )
poke4( bounds_ptr, 2 )
void = c_func( SafeArrayPutElement, {psa, bounds_ptr, bstr})
free_bstr( bstr )
make_variant( var, VT_ARRAY + VT_BSTR, psa )
return var
end function
</code></pre>
| 24,334
|
<p>I'm having difficulty parsing some JSON data returned from my server using jQuery.ajax()</p>
<p>To perform the AJAX I'm using:</p>
<pre><code>$.ajax({
url: myUrl,
cache: false,
dataType: "json",
success: function(data){
...
},
error: function(e, xhr){
...
}
});
</code></pre>
<p>And if I return an array of items then it works fine:</p>
<pre><code>[ { title: "One", key: "1" }, { title: "Two", key: "2" } ]
</code></pre>
<p>The success function is called and receives the correct object.</p>
<p>However, when I'm trying to return a single object:</p>
<pre><code>{ title: "One", key: "1" }
</code></pre>
<p>The error function is called and xhr contains 'parsererror'. I've tried wrapping the JSON in parenthesis on the server before sending it down the wire, but it makes no difference. Yet if I paste the content into a string in Javascript and then use the eval() function, it evaluates it perfectly.</p>
<p>Any ideas what I'm doing wrong?</p>
<p>Anthony</p>
|
<p>Is your server sending data as Content-Type <code>"*/json"</code>? If not, modify the response headers accordingly. Sending <code>"application/json"</code> would be fine, for example.</p>
|
<p>use</p>
<pre><code>$data = yourarray();
json_encode($data)
</code></pre>
<p>on server side.
On client side
use ajax with Datatype JSON and be sure your document encoding is not UTF-8 with BOM it has to be UTF-8.</p>
| 31,048
|
<p>We are building an enterprise application in which we will incorporate multiple platforms for user interfaces (i.e. ASP.net webapp, Windows Application, and someday, Mobile Apps) and multiple platforms for back-end databases (i.e. SQL Server, XML, Oracle). An additional neccesity is that these back-end DBs either be centralized and accessed via the web or localized on the client computer and occasionally synchronized to the central server.</p>
<p>Can anyone give advice on how we can abstract the user-interface layer & the data layer so that we can more simply create plug-and-play adaptability between the various UIs and the various choices for DBs? For example: in one case, we may have a web-app running on a centralized server via the internet, and we may have remote machines running localized copies via a windows app. At scheduled intervals, we'd want all machines synchronized so that they can all have near-real-time data.</p>
<p>We also need advice on handling the various connection strings involved so that the only setting that would need changing on any one app would be "local" or "remote", which would then determine the necessary connection string.</p>
|
<p>Abstracting the presentation layer is a fairly easy concept once you have the hang of n-tier architecture. Just focus on differentiating "domain logic" from "application logic". Domain logic is common across your different platforms, and application logic is platform-specific. For example, data validation is domain logic (though it's nice when you can do it on the front-end, which makes things more complex, but work with me here...) and deciding what URL to redirect to after some action is application logic. Make sure you put your domain logic at a level that is useable by any platform, and make sure not to put any application logic in your domain layer.</p>
<p>The other half of your question seems like your larger focus, but I would ask for some clarification here, as I can discern two different essential questions.</p>
<ol>
<li><p>I hope you aren't going for the "holy grail" of database independence. This is always a lofty goal trumpted during the design phase, that almost always, pretty much every time, isn't needed.</p>
<p>If that isn't what you're going for, then I would suggest that you should know which objects are stored in which persistence medium, and you should avoid the complexity of flexibility and just code your vertical paths in as straight-forward a manner as possible. IE don't code extra stuff into some business class that stores its data in Oracle to enable you to put it into SQL Server "at some point in the future". (I came round-robin back to database independence, didn't I?)</p>
</li>
<li><p>The question of caching data locally to improve performance for certain platforms is specific to those platforms and I would suggest you look into Smart Clients and the Caching framework/guidance the MS P&P team has. I've been working pretty exclusively on web stuff for the last couple years, but in 05/06 it was pretty good, and they've been doing lots of work on their Smart Client stuff in the meantime.</p>
</li>
</ol>
|
<p>I would look at using the provider model to establish the database connections in your application.</p>
<p>I would start by looking at the examples and detail provided in the Microsoft Data Application Block, I think it will help get you part of the way there.</p>
| 29,071
|
<p>So I am currently learning C++ and decided to make a program that tests my skills I have learned so far. Now in my code I want to check if the value that the user enters is a double, if it is not a double I will put a if loop and ask them to reenter it. The problem I have is how do I go about checking what type of variable the user enters, ex- if a user enters a char or string, I can output an error message. Here is my code:</p>
<pre><code>//cubes a user entered number
#include <iostream>
using namespace std;
double cube(double n); //function prototype
int main()
{
cout << "Enter the number you want to cube: "; //ask user to input number
double user;
cin >> user; //user entering the number
cout << "The cube of " << user << " is " << cube(user) << "." << endl; //displaying the cubed number
return 0;
}
double cube (double n) //function that cubes the number
{
return n*n*n; // cubing the number and returning it
}
</code></pre>
<p>Edit: I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.</p>
|
<h2>Safe C++ Way</h2>
<p>You can define a function for this using <code>std::istringstream</code>:</p>
<pre><code>#include <sstream>
bool is_double(std::string const& str) {
std::istringstream ss(str);
// always keep the scope of variables as close as possible. we see
// 'd' only within the following block.
{
double d;
ss >> d;
}
/* eat up trailing whitespace if there was a double read, and ensure
* there is no character left. the eof bit is set in the case that
* `std::ws` tried to read beyond the stream. */
return (ss && (ss >> std::ws).eof());
}
</code></pre>
<p>To assist you in figuring out what it does (some points are simplified):</p>
<ul>
<li>Creation of a input-stringstream initialized with the string given</li>
<li>Reading a double value out of it using <code>operator>></code>. This means skipping whitespace and trying to read a double.</li>
<li>If no double could be read, as in <code>abc</code> the stream sets the <em>fail</em>-bit. Note that cases like <code>3abc</code> will succeed and will <em>not</em> set the fail-bit.</li>
<li>If the fail-bit is set, <code>ss</code> evaluates to a zero value, which means <em>false</em>. </li>
<li>If an double was read, we skip trailing whitespace. If we then are at the end of the stream (note that <code>eof()</code> will return <em>true</em> if we tried to read past the end. <code>std::ws</code> does exactly that), <code>eof</code> will return true. Note this check makes sure that <code>3abc</code> will not pass our check.</li>
<li>If both cases, right and left of the <code>&&</code> evaluate to <em>true</em>, we return true to the caller, signaling the given string is a double.</li>
</ul>
<p>Similar, you check for <code>int</code> and other types. If you know how to work with templates, you know how to generalize this for other types as well. Incidentally, this is exactly what <code>boost::lexical_cast</code> provides to you. Check it out: <a href="http://www.boost.org/doc/libs/1_37_0/libs/conversion/lexical_cast.htm" rel="nofollow noreferrer">http://www.boost.org/doc/libs/1_37_0/libs/conversion/lexical_cast.htm</a>.</p>
<h2>C Way One</h2>
<p>This way has advantages (being fast) but also major disadvantages (can't generalized using a template, need to work with raw pointers):</p>
<pre><code>#include <cstdlib>
#include <cctype>
bool is_double(std::string const& s) {
char * endptr;
std::strtod(s.c_str(), &endptr);
if(endptr != s.c_str()) // skip trailing whitespace
while(std::isspace(*endptr)) endptr++;
return (endptr != s.c_str() && *endptr == '\0');
}
</code></pre>
<p><code>strtod</code> will set <code>endptr</code> to the last character processed. Which is in our case the terminating null character. If no conversion was performed, endptr is set to the value of the string given to <code>strtod</code>.</p>
<h2>C Way Two</h2>
<p>One might thing that <code>std::sscanf</code> does the trick. But it's easy to oversee something. Here is the correct way to do it:</p>
<pre><code>#include <cstdio>
bool is_double(std::string const& s) {
int n;
double d;
return (std::sscanf(s.c_str(), "%lf %n", &d, &n) >= 1 &&
n == static_cast<int>(s.size()));
}
</code></pre>
<p><code>std::sscanf</code> will return the items converted. Although the Standard specifies that <code>%n</code> is not included in that count, several sources contradict each other. It's the best to compare <code>>=</code> to get it right (see the manpage of <code>sscanf</code>). <code>n</code> will be set to the amount of the processed characters. It is compared to the size of the string. The space between the two format specifiers accounts for optional trailing whitespace. </p>
<h2>Conclusion</h2>
<p>If you are a beginner, read into <code>std::stringstream</code> and do it the C++ way. Best not mess with pointers until you feel good with the general concept of C++.</p>
|
<p>I would have to say I just started and don't have the slightest of clue about your code, but I will check out your link. By the way, I haven't learned how to work with templates yet,I am learning about dealing with data, only Chapter 3 in my C++ Primer Plus 5th edition.</p>
| 43,139
|
<p>One thing I really miss about Java is the tool support. FindBugs, Checkstyle and PMD made for a holy trinity of code quality metrics and automatic bug checking. </p>
<p>Is there anything that will check for simple bugs and / or style violations of Ruby code? Bonus points if I can adapt it for frameworks such as Rails so that Rails idioms are adhered to.</p>
|
<p>I've recently started looking for something like this for Ruby. What I've run across so far:</p>
<ul>
<li><a href="http://saikuro.rubyforge.org/" rel="noreferrer">Saikuro</a></li>
<li><a href="http://www.martyandrews.net/blog/2008/09/first_official_release_of_rood.html" rel="noreferrer">Roodi</a></li>
<li><a href="http://ruby.sadi.st/Flog.html" rel="noreferrer">Flog</a></li>
</ul>
<p>These might be places to start. Unfortunately I haven't used any of the three enough yet to offer a good opinion.</p>
|
<p>There is also <a href="https://github.com/simplabs/excellent" rel="nofollow">excellent</a>. I haven't tried it yet, but it too looks promising. </p>
| 7,902
|
<p>Is it a good idea to have a factory class using generics to instantiate objects?</p>
<p>Let's say I have a class Animal and some subclasses (Cat, Dog, etc):</p>
<pre><code>abstract class Animal
{
public abstract void MakeSound();
}
class Cat : Animal
{
public override void MakeSound()
{
Console.Write("Mew mew");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.Write("Woof woof");
}
}
static class AnimalFactory
{
public static T Create<T>() where T : Animal, new()
{
return new T();
}
}
</code></pre>
<p>Then in my code I would use AnimalFactory like this:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Dog d = AnimalFactory.Create<Dog>();
d.MakeSound();
}
}
</code></pre>
|
<p>Depends on what you want to do with it. The example you gave is not that helpful, as all it does is simply call new() which is something you can do in your code as well. A factory is more useful if you want to place logic which has to be ran during the object creation process somewhere outside the object to create but also away from the code which instantiates the objects. </p>
<p>In that light, it depends on what logic you want to run in your factory and if that logic is also writable using the same generic constraints as the factory. If not, you'll likely need a pattern called Abstract factory, which uses a general factory to instantiate the right specific factory behind the scenes for the type to create the object at hand. </p>
|
<p>using generics for your constructor is called the abstract factory pattern. </p>
<p>Its good but only if you're using it, in this example you've got some of the defaults in the factory at least.</p>
<pre><code>static class AnimalFactory
{
public static Animal Create<T>() where T : Animal
{
return Create<T>("blue");
}
public static Animal Create<T>(string colour) where T : Animal, new()
{
return new T() {Colour = colour};
}
}
</code></pre>
| 47,376
|
<p>In Visual Studio you can create a template XML document from an existing schema. The new <a href="http://msdn.microsoft.com/en-us/library/cc716766.aspx" rel="noreferrer">XML Schema Explorer</a> in VS2008 SP1 takes this a stage further and can create a sample XML document complete with data.
Is there a class library in .NET to do this automatically without having to use Visual Studio? I found the <a href="http://msdn.microsoft.com/en-us/library/aa302296.aspx" rel="noreferrer">XmlSampleGenerator</a> article on MSDN but it was written in 2004 so maybe there is something already included in .NET to do this now?</p>
|
<p>some footwork is involved, but you could load the xsd into a DataSet object, iterate over the Tables and add a few rows in each by calling calling NewRow() on each and then adding those rows back into their respective tables.. then save the DataSet out to a file:</p>
<pre><code>DataSet ds = new DataSet();
ds.ReadXmlSchema("c:/xsdfile.xsd");
foreach(DataTable t in ds.Tables)
{
var row = t.NewRow();
t.Rows.Add(row);
}
ds.WriteXml("c:/example.xml");
</code></pre>
<p>P.S. A little extra work, but instead of just iterating over each table type and adding empty rows, you could build a nice winform that would allow you to drop in some data for each of the rows. I built something like this in about an hour a few weeks ago.</p>
|
<p>Directly, none that I can think of, other than third party add-ons. You could utilize the <a href="http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.80).aspx" rel="nofollow noreferrer">xsd schema definition tool</a> to take your XSD and create a .NET object/class, once you have that, you could, to quote the linked page: </p>
<blockquote>
<p>XSD to Classes: Generates runtime classes from an XSD schema file. The generated classes can be used in conjunction with <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(VS.80).aspx" rel="nofollow noreferrer">System.Xml.Serialization.XmlSerializer</a> to read and write XML code that follows the schema.</p>
</blockquote>
| 6,304
|
<p>Can somebody remember what was the command to create an empty file in MSDOS using BAT file?</p>
|
<pre><code>echo. 2>EmptyFile.txt
</code></pre>
|
<p>The easiest way is:</p>
<p><code>echo. > Filename.txt</code></p>
| 25,797
|
<p>The TextWrapping property of the TextBox has three possible values:</p>
<ul>
<li>Wrap</li>
<li>NoWrap</li>
<li>WrapWithOverflow</li>
</ul>
<p>I would like to bind to the IsChecked property of a MenuItem. If the MenuItem is checked, I want to set the TextWrapping property of a TextBox to Wrap. If the MenuItem is not checked, I want to set the TextWrapping property of the TextBox to NoWrap.</p>
<p>To sum up, I am trying to bind a control that has two states to two values of an enumeration that has more than two values.</p>
<p><strong>[edit]</strong> I would like to accomplish this in XAML, if possible.</p>
<p><strong>[edit]</strong> I figured out how to do this using an IValueConverter. Perhaps there is a better way to do this? Here is what I did:</p>
<hr>
<p>In Window.Resources, I declared a reference to my ValueConverter.</p>
<pre><code><local:Boolean2TextWrapping x:Key="Boolean2TextWrapping" />
</code></pre>
<p>In my TextBox, I created the binding to a MenuItem and included the Converter in the binding statement.</p>
<pre><code>TextWrapping="{Binding ElementName=MenuItemWordWrap, Path=IsChecked, Converter={StaticResource Boolean2TextWrapping}}"
</code></pre>
<p>and the ValueConverter looks like this:</p>
<pre><code>public class Boolean2TextWrapping : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo)
{
if (((bool)value) == false)
{
return TextWrapping.NoWrap;
}
return TextWrapping.Wrap;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
</code></pre>
|
<p>If you want to do this all in xaml you need to use a <a href="http://msdn.microsoft.com/en-us/library/system.windows.style.aspx" rel="noreferrer">Style</a> and a <a href="http://msdn.microsoft.com/en-us/library/system.windows.datatrigger.aspx" rel="noreferrer">DataTrigger</a>.</p>
<pre><code><StackPanel>
<CheckBox x:Name="WordWrap">Word Wrap</CheckBox>
<TextBlock Width="50">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin lacinia nibh non augue. Pellentesque pretium neque et neque auctor adipiscing.
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsChecked, ElementName=WordWrap}" Value="True">
<Setter Property="TextWrapping" Value="Wrap" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</StackPanel>
</code></pre>
|
<p>I assume you are talking about .NET. I don't think databinding will work here because the values are not of the same type (boolean vs enum). The easiest solution would be to handle the CheckedChanged event of that menu item and adjust the wrap mode of the textbox accordingly.</p>
| 31,222
|
<p>In data processing, I frequently need to create a lookup data structure to map one identifier to another. As a concrete example, let's take a structure which holds a 1-to-1 mapping between a country's 2 character code and its full name. In it we would have</p>
<pre><code>AD -> Andorra
AE -> United Arab Emirates
AF -> Afghanistan
</code></pre>
<p>What's a good name for the variable that would hold this map? Some ideas (I'll use camel-case names):</p>
<pre><code>countryNameByCode
nameByCodeLookup
nameCodeLookup
codeToName
</code></pre>
|
<p>My vote would be for <code>codeToName</code> in this particular case, and I guess that generalizes. That's not to say that it's the name I would have chosen myself in all cases; that depends a lot on scope, further encapsulation, and so on. But it feels like a good name, that should help make your code readable:</p>
<pre><code>String country = codeToName["SV"];
</code></pre>
<p>Looks fairly nice, should be easily understandable by anyone. Possibly change the word "code" to something more precise ("countrycode" would be my next choice).</p>
|
<p>Another vote for just pluralizing what you're mapping to.</p>
<p>eg. <code>country = countries[code]</code></p>
| 26,744
|
<p>Is it possible to automount a TrueCrypt volume when logging in to Ubuntu 8.04? It's already storing the wireless network keys using the Seahorse password manager. Could TrueCrypt be made to fetch its volume password from the same keyring? Currently this would seem like the most convenient way to store my source code on the USB stick I carry around to boot from.</p>
|
<p>I can't really remember where I found this solution, but it was working for me on Ubuntu Karmic with gdm.
You have to edit the <code>/etc/gdm/Init</code> file and add the following:</p>
<pre><code>if !(echo `mount` | grep -q "/home/your_username type")
then
truecrypt /dev/sdaxxx /home/your_username
fi
</code></pre>
<p>Unfortunately it doesn't work in the new Precious Penguin Ubuntu release, since it doesn't come with the gmd package. Does anybody know how to init truecrypt for this Ubuntu release?</p>
|
<p>Apparently one solution will be to update to Ubuntu 8.10 which by default supports an encrypted directory for each user, mounted at login. It's not the same as TrueCrypt but has other strengths and weaknesses.</p>
<p>There's also a way to <a href="http://blog.littleimpact.de/index.php/2008/07/12/automatic-encryption-of-home-directories-using-truecrypt/" rel="nofollow noreferrer">get TrueCrypt working with the login password</a>.</p>
| 13,896
|
<p>I am looking for a free tool to load Excel data sheet into an Oracle database. I tried the Oracle SQL developer, but it keeps throwing a NullPointerException. Any ideas?</p>
|
<p>Excel -> CSV -> Oracle</p>
<p>Save the Excel spreadsheet as file type 'CSV' (Comma-Separated Values).</p>
<p>Transfer the .csv file to the Oracle server.</p>
<p>Create the Oracle table, using the SQL <code>CREATE TABLE</code> statement to define the table's column lengths and types. </p>
<p>Use sqlload to load the .csv file into the Oracle table. Create a sqlload control file like this:</p>
<pre><code>load data
infile theFile.csv
replace
into table theTable
fields terminated by ','
(x,y,z)
</code></pre>
<p>Invoke sqlload to read the .csv file into the new table, creating one row in the table for each line in the .csv file. This is done as a Unix command:</p>
<pre><code>% sqlload userid=username/password control=<filename.ctl> log=<filename>.log
</code></pre>
<p><strong>OR</strong></p>
<p>If you just want a tool, use <a href="http://sourceforge.net/projects/quickload" rel="noreferrer">QuickLoad</a></p>
|
<p>As you mention you are looking for a tool - you might like to check out this Oracle specific video - you can load data from any source - </p>
<p><a href="http://youtu.be/shYiN2pnPbA" rel="nofollow">http://youtu.be/shYiN2pnPbA</a></p>
| 14,594
|
<p>We just shifted from VB to C# and I am having some troubles..!</p>
<p>Why can't I create a private static const void?? </p>
<p>why is it not working?</p>
<pre><code> private static const void MyVoid(void void)
{
try
{
this.void void = new void(void + void);
return this.void;
}
catch (void)
{
Response.Write(void);
}
}
</code></pre>
|
<p>C# doesn't let you declare a method to be <code>const</code> whatever its return type is, so your method declaration is incorrect.</p>
<p>You can't catch <code>void</code> either - you can only catch exception types.</p>
<p>Ditto void parameters etc.</p>
<p>Why do you think you need this?</p>
|
<p>it's because void is actually nothingness :) If you want to send nothing to methods. Do it
MyVoid()</p>
<p>The same is for other lines in your method</p>
| 35,950
|
<p>What are the implications of running a Microsoft Access Database in both 2003 and 2007? </p>
<p>Is there some class I forgot to take?</p>
<p>The program was originally built in office 2003, and then run in 2007. Issues seem to happen when the machine it is being run on has both 2003 and 2007 on it. The issue would also appear to stem from reference from the "Microsoft Access 12.0 Object Library" (or the "Microsoft Access 11.0 Object Library" in 2003). To see this, just look at the Tools: Refrences menu on the VBA screen. </p>
<p>The error's symptom is basically the code not be recognized (almost like it doesn’t recognize the programming language I’m using). It usually follows this with a box that says "The expression On Load you entered as the event property settings produced the following error: Object or class does not support the set of events". You can also replace “On Load” with “On Click” for buttons or “On Change” for text boxes.</p>
<p>I personally suspect that the computer is taking parts of the Microsoft Access 11.0/12.0 Object Library and then mixes the two into a useless VBA reference. What further confirms my suspicion is the box that pops up when going between the two that says "Configuring Microsoft Access" Another issue that further confirms my suspicion is it will run on whichever one it is opened on first (2007, for example) and then not run on the other (2003 continuing the example)</p>
<p>The only other issue is I have had to fix was changing the last part of the DoCmd.OpenForm ,,,,, acFormReadOnly (or acReadOnly, depending on how the machine seems to feel on that particular day - yes it would work with one, one day and then want me to switch it another) to simply locking the individual text boxes</p>
<p>Maybe it’s not quite coding, but I think it might be able to be fixed by coding.</p>
<p>Hopefully that’s enough for someone to come up with something.</p>
|
<p>Microsoft's official position is that installing multiple office versions on the same pc is not supported and not recommended, and Access 2007 seems to be designed to prove that to us!</p>
<p>That said, you can avoid most issues by doing the following:</p>
<p>1 - Splitting the db into a back end and front end. Place the back end (tables and relationships) in a network folder, and place a copy of the front end (all other objects) on each user's desktop.</p>
<p>2 - It's best to make the front end an mde to avoid the references shuffle every time you open the db in the other version of Access.</p>
<p>3 - Create a shortcut to open the front end with the desired version of Access so it's <em>always</em> opened with that version. (And remember to use the shortcut!) In the shortcut's target:</p>
<p>"path to Access 12 msaccess.exe" "path to db.mdb"</p>
|
<p>We have an MS-Acces application, developped with Access 2003 and used on either full or runtime version of Access 2003 and Access 2007 (Access 2007 Runtime being free, we are making a great use of it!). There is no particular issue except the references management. Our code analyses the Office version installed on the computer and automatically updates corresponding references (not only Access but also Excel, Outlook, Word, etc.: code is very tricky but of great interest!)</p>
<p>To my own knowledge, no major objects, properties or methods available in Office 2003/VBA were deprecated in Office 2007. Office 2003 code will then run with Access 2007 once these references issues solved. Some new objects were introduced in Office 2007 so I would not advise any developer to use it to develop code to be further used with Access 2003.</p>
<p>But the main & real issue of your question is: why should one run both Access versions on the same computer? This is what I'd do if I want to make sure to crash my apps. I think that if your objectives were to develop software, you should definitely find a better configuration for your machine!</p>
| 10,087
|
<p>I was developing a web page, where I was laying out a board for a Chess-like game, along with a couple of piece trays. It's all done using HTML (with jQuery for dynamic updating as the game is played). Somewhere I'd got the notion that using absolute positioning of elements within a page was considered a bad practice, and that it was preferable to use relative positioning.</p>
<p>After struggling with relative positioning for too long, I realized that absolute positioning of the board elements would be much, much easier to get right... and it was.</p>
<p>Is anyone aware of a reason that relative positioning is preferable over absolute? Are there any guidelines or rules of thumb that you apply when deciding which approach to take?</p>
|
<p>For a chess like game such as you are developing, there is nothing inherently wrong with using absolute positioning. As you said, relative positioning and normal flow layout make this sort of task quite difficult. </p>
<p>Of course, if you were developing a more standard website, such as a site providing some public service, absolute positioning overrides the default flow layout of browsers and so will reduce accessibility for many users. In this case I would avoid it.</p>
<p>Having said that, a lesser known benefit of absolute positioning is that it allows localized absolute positioning <em>within</em> the nearest "positioned" parent element.</p>
<p><em>Note:</em> A "positioned" element can be any of the following: relative, fixed, absolute, or sticky.</p>
<p>To explain:</p>
<pre><code><div id="parentDIV" style="position:relative">
<div id="childDIV" style="position:absolute;left:20px;top:20px;">
I'm absolutely positioned within parentDIV.
</div>
</div>
</code></pre>
<p>Here, <code>childDIV</code> is actually positioned 20px from the left and 20px from the top of <code>parentDIV</code>, <em>NOT</em> the overall document. This gives a nice precise control over nested elements on a page, without sacrificing the overall page flow-layout.</p>
<p>So to answer your question (relative positioning being preferred over absolute): I don't believe there is a correct answer, it depends on what you are needing to build. However in general positioning (absolute or relative) versus default flow layout, my approach is as described above.</p>
|
<p>IMO, not a bad thing at all. I have recently completed an assignment with AA standards compliance and support for FF2, IE7, IE6 (yes, a pain I know). There were certain layouts which were only achievable because of absolutely positioning! Even certain components like buttons where layering was needed (transparencies) were possible only because of absolute positioning. If someone has a better way, please refer me to that.</p>
<p>Absolute positioning breaks the flow, if we know how to restrict the flow (change parent's coords to relative/absolute) it is fun. I don't know about older browsers (IE6 itself is a dinosaur) but one painful thing I found was, writing to PDF (Cute PDF) or opening with WINWORD (sue me) gives a shabby result.</p>
| 22,508
|
<p>How do you go about finding unused icons, images, strings in .resx files that may have become 'orphaned' and are no longer required?</p>
|
<p>Recently <a href="https://github.com/tom-englert/ResXResourceManager" rel="noreferrer">ResXManager 1.0.0.41</a> added a feature to show the number of references to a string resource.</p>
<p><img src="https://i.stack.imgur.com/X3fwm.png" alt="Screenshot showing the new reference column"></p>
|
<p>I've been considering this myself and I believe I have two options. Both of these rely on the fact that I use a helper method to extract the required resource from the resource files. </p>
<ol>
<li><p><strong>Logging</strong><br>
Add some code to the "getresource" method or methods so that every time a resource is accessed, the resource key is written to a log. Then try to access every part of the site (a testing script might be helpful here). The resultant log entries should give a list of all the active resource keys, the rest can be junked.</p></li>
<li><p><strong>Code Analysis</strong><br>
I am looking at whether <a href="http://msdn.microsoft.com/en-us/library/bb126445.aspx" rel="nofollow noreferrer" title="T4">T4</a> is capable of working through the solution and creating a list of all references to the "getresource" helper method. The resultant list of keys will be active, the rest can be deleted.</p></li>
</ol>
<p>There are limitations of both methods. The logging method is only as good as the code covered by the test and the code analysis might not always find keys rather than strings containg the keys so there will be some extra manual work required there.</p>
<p>I think I'll try both. I'll let you know how it goes.</p>
| 30,514
|
<p>I've recently initialized OctoPi onto my Raspberry Pi, proceeded to connect it to my local internet, and then connected it to my FlashForge Creator Pro (2014 edition)</p>
<p>Everything seemed to be going smoothly until I tried to connect to the printer; the Pi didn't seem to be able to pick up a usable Baudrate (after being trying out all of the usable ones).</p>
<p>For example, when trying out 9600, I would get:</p>
<blockquote>
<p>Trying baudrate: 9600</p>
<p>Send: N0 M110 N0*125</p>
<p>Recv: ��r># ���& �</p>
</blockquote>
<p>What should I do to fix the problem?</p>
<hr />
<p><em>Note that I got the same types of messages back (with garbled 'special' characters) when trying using the "<strong>auto connect</strong>" feature.</em></p>
|
<p>I got the same problem.<br>
Auto-detect baud rate was not working too.<br>
So I manually tried every baud-rate and finally found one working, for me it was 115200.<br>
Good luck!</p>
|
<p>Install GPX via command line. To do this, type</p>
<p><code>/home/pi/oprint/bin/pip install "https://markwal.github.io/octoprint-download/OctoPrint-GPX.tgz"</code>
then go ahead and restart octoprint and try connecting again.</p>
| 522
|
<p>I am currently working on an asp.net application in Visual Studio 2005. I would like to upgrade to 2008 to take advantage of some of the new features, but my remote team won't be able to upgrade to it for a while.</p>
<p>Is it possible for only a few people on my team to upgrade to Visual Studio 2008, while the rest of the team continues to use 2005? </p>
<p>At this point, I don't plan on using any of the 3.0+ foundation stuff yet, so that isn't a concern.</p>
|
<p>Yes, the project files between 2005 and 2008 are compatible. The solutions are not, but those are easy to remake or copy. There is one gotcha with the project files, if you're using Web Applications projects. The two versions reference different MSBuild target files. Steven Harman has <a href="http://stevenharman.net/blog/archive/2007/09/28/multi-targeting-vs2005-and-vs2008-web-application-projects-a-gotcha.aspx" rel="nofollow noreferrer">a blog with a fix to add to the project file</a>.</p>
<p>So long as you aren't using anything new from the 3.5 compiler, you should be good. Note that even if you are targeting the 2.0 Framework, the compiler will still accept 3.5 syntax (var, object initializers, etc.) so you'll still need to be aware of those.</p>
|
<p>Make copies of your project files and rename the physical copies to "Name2005.proj". Then upgrade the solution you are working on which will upgrade the project and solution files. Finally go back in VS2005 and create a new 2005 solution and stitch up the 2005 projects into it. </p>
<p>This gives you two parrallel sets of project files that you can use for the code in each visual studio revision. Make sure you keep the VS2008 target .net version at .net2.0 and you can't share MS-Test files. You will also have to manually keep the project files in synch. </p>
<p>It's a bit of a pain but it works.</p>
| 19,660
|
<p>I've run across the following line in a VB6 application.</p>
<pre><code>mobjParentWrkBk.ExcelWorkBook.Application.Selection.Insert Shift:=xlToRight
</code></pre>
<p>Unfortunately Google and other search engines have not been very useful as they seem to omit the := part. </p>
<p>What would be a C# equivalent?</p>
|
<p>This is Visual Basic syntax for optional named parameters. The <code>Insert</code> function has a parameter named <code>Shift</code>, which is being specified.</p>
<p>C#, as far as I know, doesn't have an equivalent for optional named parameters. Instead, you'd need to call the <code>Insert</code> method, specifying <code>Type.Missing</code> for all parameters other than <code>Shift</code>.</p>
<p>See also the following StackOverflow question: <a href="https://stackoverflow.com/questions/204877/vbnet-operator">VB.NET := Operator</a></p>
<p>UPDATE (2008-10-29):</p>
<p>C# 4.0 is set to introduce optional and named parameters. See this <a href="http://codebetter.com/blogs/matthew.podwysocki/archive/2008/10/28/named-and-optional-arguments-in-c-4-0.aspx" rel="nofollow noreferrer">blog entry on codebetter.com</a>.</p>
|
<p>It's really all about Excel and how it handles inserts. If you select a range of cells and right-click Insert you will be asked which direction to shift the cells. This is from the Excel Help:</p>
<p>=======</p>
<p>Insert Method on Range Object</p>
<p>Inserts a cell or a range of cells into the worksheet or macro sheet and shifts other cells away to make space.</p>
<p>expression.Insert(Shift, CopyOrigin)</p>
<p>expression Required. An expression that returns a Range object.</p>
<p>Shift Optional Variant. Specifies which way to shift the cells. Can be one of the following XlInsertShiftDirection constants: xlShiftToRight or xlShiftDown. If this argument is omitted, Microsoft Excel decides based on the shape of the range.</p>
<p>CopyOrigin Optional Variant. The copy origin.</p>
<p>===========</p>
<p>If you don't have the constants defined you can subsitute the following numbers</p>
<p>xlShiftDown: -4121
xlShiftToLeft: -4159
xlShiftToRight: -4161
xlShiftUp: -4162</p>
| 28,137
|
<p>I am currently working on a C++/COM project using ArcEngine(From ESRI). Aside from the fact that there is little to no support in terms of documentation (SDK is there.) Anyways, i am wondering if anyone here has had any experience in making the initialization process of ArcEngine faster. Right now it takes 30-35 seconds just to initialize the engine. Now we are going to be running several of these applications. Does anyone have any experience, with this? </p>
<p>Its a very werid and odd task, but ESRI's developer forums are no help. and i couldnt find anything on google.</p>
<p>Any ideas?</p>
|
<p>It's been almost a decade since I last played with ESRI stuff, so I can't help you with anything specific to ArcEngine.</p>
<p>Maybe you can pool instances? In the best case scenario you would be able to reuse ArcEngine instances, and could return an instance back to pool after you're done with it.
If that's not possible, you could at least try to have a number of instances ready to roll, although whether that is possible and/or useful depends a lot on the specifics of your app.</p>
|
<p>Well from my understanding ArcEngine initialization, initializes a special COM environment.</p>
<p>You don't ever get any sort of real handle over the initialized environment. Can you somehow store a COM Enviroment and pass it to other programs. My current idea is:</p>
<p>Windows Service Running in Background with initialized ArcEngine. Program somehow queries the service, the service returns the COM Enviroment. Is this even possible?</p>
| 36,955
|
<p><a href="http://www.stackoverflow.com/questions/61088/hidden-features-of-javascript#61118">Alan Storm's comments</a> in response to my answer regarding the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with" rel="noreferrer"><code>with</code> statement</a> got me thinking. I've seldom found a reason to use this particular language feature, and had never given much thought to how it might cause trouble. Now, I'm curious as to how I might make effective use of <code>with</code>, while avoiding its pitfalls.</p>
<p>Where have you found the <code>with</code> statement useful?</p>
|
<p>Another use occurred to me today, so I searched the web excitedly and found an existing mention of it: <a href="http://web.archive.org/web/20090111183416/http://www.hedgerwow.com/360/dhtml/js_block_scope.html" rel="noreferrer">Defining Variables inside Block Scope</a>.</p>
<h3>Background</h3>
<p>JavaScript, in spite of its superficial resemblance to C and C++, does not scope variables to the block they are defined in:</p>
<pre><code>var name = "Joe";
if ( true )
{
var name = "Jack";
}
// name now contains "Jack"
</code></pre>
<p>Declaring a closure in a loop is a common task where this can lead to errors:</p>
<pre><code>for (var i=0; i<3; ++i)
{
var num = i;
setTimeout(function() { alert(num); }, 10);
}
</code></pre>
<p>Because the for loop does not introduce a new scope, the same <code>num</code> - with a value of <code>2</code> - will be shared by all three functions.</p>
<h3>A new scope: <code>let</code> and <code>with</code></h3>
<p>With the introduction of the <code>let</code> statement in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let" rel="noreferrer">ES6</a>, it becomes easy to introduce a new scope when necessary to avoid these problems:</p>
<pre><code>// variables introduced in this statement
// are scoped to each iteration of the loop
for (let i=0; i<3; ++i)
{
setTimeout(function() { alert(i); }, 10);
}
</code></pre>
<p>Or even:</p>
<pre><code>for (var i=0; i<3; ++i)
{
// variables introduced in this statement
// are scoped to the block containing it.
let num = i;
setTimeout(function() { alert(num); }, 10);
}
</code></pre>
<p>Until ES6 is universally available, this use remains limited to the newest browsers and developers willing to use transpilers. However, we can easily simulate this behavior using <code>with</code>:</p>
<pre><code>for (var i=0; i<3; ++i)
{
// object members introduced in this statement
// are scoped to the block following it.
with ({num: i})
{
setTimeout(function() { alert(num); }, 10);
}
}
</code></pre>
<p>The loop now works as intended, creating three separate variables with values from 0 to 2. Note that variables declared <em>within</em> the block are not scoped to it, unlike the behavior of blocks in C++ (in C, variables must be declared at the start of a block, so in a way it is similar). This behavior is actually quite similar to a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#let_blocks" rel="noreferrer"><code>let</code> block syntax</a> introduced in earlier versions of Mozilla browsers, but not widely adopted elsewhere.</p>
|
<p>Just wanted to add you can get "with()" functionality with pretty syntax and no ambiguity with your own clever method...</p>
<pre><code> //utility function
function _with(context){
var ctx=context;
this.set=function(obj){
for(x in obj){
//should add hasOwnProperty(x) here
ctx[x]=obj[x];
}
}
return this.set;
}
//how calling it would look in code...
_with(Hemisphere.Continent.Nation.Language.Dialect.Alphabet)({
a:"letter a",
b:"letter b",
c:"letter c",
d:"letter a",
e:"letter b",
f:"letter c",
// continue through whole alphabet...
});//look how readable I am!!!!
</code></pre>
<p>..or if you <em>really</em> want to use "with()" without ambiguity and no custom method, wrap it in an anonymous function and use .call </p>
<pre><code>//imagine a deeply nested object
//Hemisphere.Continent.Nation.Language.Dialect.Alphabet
(function(){
with(Hemisphere.Continent.Nation.Language.Dialect.Alphabet){
this.a="letter a";
this.b="letter b";
this.c="letter c";
this.d="letter a";
this.e="letter b";
this.f="letter c";
// continue through whole alphabet...
}
}).call(Hemisphere.Continent.Nation.Language.Dialect.Alphabet)
</code></pre>
<p>However as others have pointed out, its somewhat pointless since you can do...</p>
<pre><code> //imagine a deeply nested object Hemisphere.Continent.Nation.Language.Dialect.Alphabet
var ltr=Hemisphere.Continent.Nation.Language.Dialect.Alphabet
ltr.a="letter a";
ltr.b="letter b";
ltr.c="letter c";
ltr.d="letter a";
ltr.e="letter b";
ltr.f="letter c";
// continue through whole alphabet...
</code></pre>
| 8,679
|
<p>If the Mono project is successful it will pave the way for commercial software on non-Windows platforms.</p>
<p>I am interested in the prospect of writing and selling commercial software for the Mono platform along the lines of our existing Smoke Vector Graphics (OCaml) and F# for Visualization (.NET) products. Are any commercial library developers already building upon Mono and, if so, are they turning a profit from it?</p>
<p>Also, will it be feasible to write the software in Microsoft's F# language or will Mono have trouble with ILX?</p>
|
<p>My figures speak against it, we developed Qide 10 years ago and got 4 or so buys. We got at least a few hundred time more on Windows. The state of tools on Linux can just be named bad. Agreed you have wonderful things there but if you use GPLd software you will drown in their license stuff. There does exist one debugger really and one C compiler it gdb and gcc, despite the efforts of Intel and if you come along into some less well known language you got nothing. Ever tried ProjectCenter (Objective C development environment)? , the debuggers are mostly clis and you have to type info reg to get info about registers. DDD works very funny, it's one tools that while scrolling did not get that right, you scroll up you have to scroll the mouse wheel down. It's also unbelievable slow to scroll it's just as if the BOFH wants to make a joke of you.</p>
<p>Well I could argue about the even sader state on IBM AIX. What you have to pay to IBM is way beyond any reason...</p>
<p>So maybe you're luckier than we are. But I'm mostly fed up with trying to earn money with "application" development on Linux. The best I can say is that Linux works well for setting up net infrastructure, there you got decent payments, but with programming tools, forget it.</p>
<p>Regards</p>
|
<p>Linux people are notoriously thrifty, so I'd consider the ROI.</p>
<p>Do you really want to spend your resources to target a group that has less than 10% market adoption, and out of that 10%, only 1% would be interested in your product, and only %0.01 percent would pay for it?</p>
| 34,668
|
<p>I'm storing many files of various lengths into a block-oriented medium (fixed-size e.g. 1024 bytes). When reading back the file, each block will either be missing or correct (no bit errors or the like). The missing blocks are random, and there's not necessarily any sequence to the missing blocks. I'd like to be able to reassemble the entire file, as long as the number of missing blocks is below some threshold, which probably varies with the encoding scheme.</p>
<p>Most of the literature I've seen deals with sequences of bit errors in a stream of data, so that wouldn't seem to apply.</p>
<p>A simple approach is to take N blocks at a time, then store a block containing the XOR of the N blocks. If one of the N blocks is missing but the check block is not, then the missing block can be reconstructed.</p>
<p>Are there error-correcting schemes which are well suited to this problem? Links to literature or code are appreciated.</p>
|
<p>Look into Reed-Solomon codes:</p>
<p><a href="http://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction</a></p>
|
<p>Check out Raptor codes (<a href="https://en.wikipedia.org/wiki/Raptor_code" rel="nofollow">https://en.wikipedia.org/wiki/Raptor_code</a>) they're the most advanced fountain codes out there at the moment</p>
| 38,017
|
<p>I've long had a desire for an STLish container that I could place into a shared memory segment or a memory mapped file.</p>
<p>I've considered the use of a custom allocator and placement new to place a regular STL container into a shared memory segment. (like this ddj <a href="http://www.ddj.com/cpp/184401639;jsessionid=XH553SW4YIE42QSNDLPSKHSCJUNN2JVN?_requestid=537362" rel="noreferrer">article</a>). The problem is that STL containers will internally have pointers to the memory they own. Therefore, if the shared memory segment or memory mapped file loads at a different base address (perhaps on a subsequent run, or in a second process), then the internal pointers are suddenly invalid. As far as I can figure out, the custom allocator approach only works if you can always map the memory segment into your process at the same address. At least with memory mapped files, I have lots of experience of that NOT being the case if you just let the system map it where ever it feels like.</p>
<p>I've had some thoughts on how to do this, but I'd like to avoid it if someone else has already done the work (that's me, being lazy).</p>
<p>I'm currently leaving locking out of the discussion, as the best locking strategy is highly application dependent.</p>
|
<p>The best starting point for this is probably the boost Interprocess libraries. They have a good example of a map in shared memory here:
<A href="http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess/quick_guide.html#interprocess.quick_guide.qg_interprocess_map" rel="nofollow noreferrer">interprocess map</A></p>
<p>You will probably also want to read the section on offset smart pointers, which solves the internal pointer problem you were referring to.
<A href="http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess/quick_guide.html#interprocess.quick_guide.qg_offset_ptr" rel="nofollow noreferrer">Offset Pointer</A></p>
|
<p>Try using Qt's QSharedMemory Implementation.</p>
| 32,889
|
<p>I have built a simple WCF Service and deployed it to IIS6, and I'm noticing that it works in my Dev and Staging environments, but not Production. Every time I try to hit the service metadata link, I get a 404 page.</p>
<p>I've checked IIS config everywhere I can think of and they're identical, so the only difference I can think of is that the Production environment is load balanced.</p>
<p>Does anyone know of any issues with running a WCF service behind a load balancer, and how can I get around that? Am I on the wrong track, is there another common problem I should look into? </p>
|
<p>You need to setup wild card mapping on IIS6. This <a href="http://peterkellner.net/2008/08/24/urlrewrite-with-aspnet-urlrewriter-wildcard-mapping-iis6-iis7/" rel="noreferrer">link</a> seems like a good step by step guide.</p>
<p>Try reading up on the differences between the integrated pipeline vs classic pipeline on IIS7</p>
|
<p>For me .svc was already mapped to the aspnet_isapi.dll as per AnthonyWJones answer:</p>
<p><a href="https://i.stack.imgur.com/ZmEB6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZmEB6.jpg" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/oYSBk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oYSBk.jpg" alt="enter image description here"></a></p>
<p>I kept getting 404's and nothing in the logs (C:\WINDOWS\system32\LogFiles\W3SVC1) helped, all my WCF settings and web.config were textbook examples. I triple checked all the permissions...</p>
<p>What my problem turned out to be was that I had built my WCF service in .Net 4.0, after I installed ASP.net 4.0 using <code>aspnet_regiis -i -enable</code> it worked straight away:</p>
<p><a href="https://i.stack.imgur.com/6zvBs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6zvBs.png" alt="enter image description here"></a></p>
| 44,381
|
<p>I'm using ASP.NET MVC Preview 4 and would like to know how to use the routing engine for form submissions.</p>
<p>For example, I have a route like this:</p>
<pre><code>routes.MapRoute(
"TestController-TestAction",
"TestController.mvc/TestAction/{paramName}",
new { controller = "TestController", action = "TestAction", id = "TestTopic" }
);
</code></pre>
<p>And a form declaration that looks like this:</p>
<pre><code><% using (Html.Form("TestController", "TestAction", FormMethod.Get))
{ %>
<input type="text" name="paramName" />
<input type="submit" />
<% } %>
</code></pre>
<p>which renders to:</p>
<pre><code><form method="get" action="/TestController.mvc/TestAction">
<input type="text" name="paramName" />
<input type="submit" />
</form>
</code></pre>
<p>The resulting URL of a form submission is:</p>
<pre><code>localhost/TestController.mvc/TestAction?paramName=value
</code></pre>
<p>Is there any way to have this form submission route to the desired URL of:</p>
<pre><code>localhost/TestController.mvc/TestAction/value
</code></pre>
<p>The only solutions I can think of are to create a separate action that just checks the request parameters, or to use Javascript.</p>
|
<p>Solution:</p>
<pre><code>public ActionResult TestAction(string paramName)
{
if (!String.IsNullOrEmpty(Request["paramName"]))
{
return RedirectToAction("TestAction", new { paramName = Request["paramName"]});
}
/* ... */
}
</code></pre>
|
<p>In your route, get rid of the {paramName} part of the URL. It should be:</p>
<p>TestController.mvc/TestAction</p>
<p>As that is the URL you want the request to route to. Your form will then post to that URL.
Posted form values are mapped to parameters of an action method automatically, so don't worry about not having that data passed to your action method.</p>
| 2,992
|
<p>What is a good C/C++ CSS parser? All that I can find is <a href="http://csstidy.sourceforge.net/" rel="noreferrer">CSSTidy</a>, and it seems to be more of an application than a parsing library.</p>
|
<p>libcss seems also a common google hit and it looks good</p>
<p><a href="http://www.netsurf-browser.org/projects/libcss/" rel="nofollow">http://www.netsurf-browser.org/projects/libcss/</a></p>
|
<p>A pretty good bet would be to read through the Mozilla or Safari code-base. If you need something a little more accessible for another program, there's an ANTLR grammar (which you can use to create C++ code) at <a href="http://www.antlr3.org/grammar/1214945003224/csst3.g" rel="nofollow noreferrer">http://www.antlr3.org/grammar/1214945003224/csst3.g</a>. The W3 validator is located at <a href="http://dev.w3.org/cvsweb/2002/css-validator/" rel="nofollow noreferrer">http://dev.w3.org/cvsweb/2002/css-validator/</a>, but it is Java. </p>
| 47,778
|
<p>I'm working on a project where I need the following.</p>
<ul>
<li>WCF service on the server side (.NET 3.5)</li>
<li>WPF client for the client side (.NET 3.0)</li>
</ul>
<p>I have an existing application that I have to use the authentication and authorization from (on the server side). I also need to store some metadata about the user in the WCF Service's Thread Principal (a site object). I do this so that I can get at it in the WCF service if I absolutely have to; some business logic may require it. So my plan was to do the following...</p>
<p>Create a custom ServiceAuthorizationManager for the server and in there I will log in the user and get the roles from the existing application. I will cache the "Site" object, and upon further reqests pull from the cache. I'll also need a CustomPrincipal object to hold my custom data. I want to impersonate the user so that I can use the builtin roles filtering in WCF like this:</p>
<pre><code>[PrincipalPermission(SecurityAction.Demand, Role = "Role1")]
public string[] RolesForUser(string username){}
</code></pre>
<p>I attempted to use the ASP.NET authorization with a custom roles provider, but I wasn't able to set anything on the Current Principal. I also attempted to use a custom IAuthorizationPolicy, but problems arose. These problems dealt with being able to use the WCFClient.exe application, when it was discovering (using the mex endpoing) it wouldn't give any credentials, so the login would fail. I eventually decided that a ServiceAuthorizationManager was the right way to go, but I'm open to other suggestions.</p>
<p>On the client I will gather the credentials and put them into the WCF proxy class, as follows.</p>
<pre><code>proxy.ChannelFactory.Credentials.UserName.UserName = userName;
proxy.ChannelFactory.Credentials.UserName.Password = password;
</code></pre>
<p>As I started to go down this route, I noticed that I wasn't able to get the username/password in the CheckAccessCore method of my manager class. Further investigation showed that I should really be authenticating in a custom UserNamePasswordValidator. So I created one of those. The problem is that the validate method never got called.</p>
<p>Further investigation showed that in order for the validate method to be called my WCF service has to have either message or transport level security. The problem with that is that I can't figure out how to have a message or transport level security without an <a href="https://en.wikipedia.org/wiki/X.509" rel="nofollow noreferrer">X.509</a> certificate. This product is going into several hundred incredibly locked down machines, and installing a certificate is not possible.</p>
<p>Is there a way to do what I'm asking without installing a certificate?</p>
|
<p>Actually it's possible, but you will need to implement your own binding.</p>
<p>Yaron Naveh developed a WCF binding that enables clear text username/password over HTTP. His <a href="http://webservices20.blogspot.com/2008/11/introducing-wcf-clearusernamebinding.html" rel="noreferrer">article</a> includes the code for the binding.</p>
|
<p>I don't know the details of your network infrastructure, but if you are in a Windows domain, you should consider using Windows credentials.</p>
<p>It is possible to use a Message security without certificates if you use Windows credentials. This is the default behavior of the wsHttpBinding (out of the box).</p>
<p>Using the out-of-the-box solutions (without implementing your own binding) WCF encourage (requires) you to use a secure channel whenever authentication credentials are included in the messages.</p>
<p>Using a custom binding that allows you to specify credentials in clear text is surely a solution, but I would think twice before using it.</p>
| 49,721
|
<p>Does anybody know any fine open source cube browser?</p>
<p>Ideally, it would be something built with plain javascript.</p>
<p>Does it even exists?</p>
<p>I'm planing to use it with classic asp agains a SQL database.</p>
|
<p>You can look at <a href="http://mondrian.pentaho.org/" rel="noreferrer">Pentaho Mondrian</a> (including <a href="http://jpivot.sourceforge.net" rel="noreferrer">JPivot</a>), or at <a href="http://eclipse.org/birt" rel="noreferrer">Eclipse BIRT</a></p>
<p>With these, you get some kind of flexible reporting tools on the most popular databases, and it includes functionality to browse OLAP cubes too.</p>
|
<p>if you can, find the sql server 2000 Resource Kit, inside there is a project that is a javascript cube browser. i am not sure of the licensing of this, but it is located at TOOLSANDSAMPLES\ANALYSISSERVICESTHINWEBCLIENT inside the Resource Kit. This resource kit should be available in msdn subscription downloads.</p>
| 49,795
|
<p>Is there a one line function call that quits the program and displays a message? I know in Perl it's as simple as:</p>
<pre><code>die("Message goes here")
</code></pre>
<p>I'm tired of typing this:</p>
<pre><code>puts "Message goes here"
exit
</code></pre>
|
<p>The <code>abort</code> function does this. For example:</p>
<pre><code>abort("Message goes here")
</code></pre>
<p>Note: the <code>abort</code> message will be written to <code>STDERR</code> as opposed to <code>puts</code> which will write to <code>STDOUT</code>.</p>
|
<p>I've never heard of such a function, but it would be trivial enough to implement...</p>
<pre><code>def die(msg)
puts msg
exit
end
</code></pre>
<p>Then, if this is defined in some .rb file that you include in all your scripts, you are golden.... just because it's not built in doesn't mean you can't do it yourself ;-)</p>
| 4,920
|
<p>OK. This problem is doing my head in. And I don't know if there even IS a definitive answer.</p>
<p>We have a website, lets call it <em>mycompany.com</em>. It's a UK-based site, with UK based content. Google knows about it, and we have done a load of SEO on it. All is well.</p>
<p><strong>Except</strong>, we are about to relaunch <strong>my company, the GLOBAL brand</strong>, so we now need mycompany.com/uk, mycompany.com/us, and mycompany.com/au, for the various countries local content. We are using GEOIP, so if someone from the US loads mycompany.com, they get redirected to mycompany.com/us etc. </p>
<p>If someone isn't in one of those three countries (US, Australia, or UK) they get the UK site.</p>
<p>This is all well and good, but we dont want to lose the rather large amount of Google juice we have on mycompany.com! And worse, the Google bot appears to be 100% based in the US, so the US site (which is pretty much out LEAST important one of the three) will appear to be the main one.</p>
<p><strong>We have thought about detecting the bot</strong>, and serving UK content, but it appears Google may smack us for that.</p>
<p>Has anyone else come across this situation, and have a solution?</p>
|
<p>As long as Google can find mycompany.com/uk and mycompany.com/au, it'll index all three versions of the site. Your domain's Google juice should apply to all three URLs just fine if they're on the same domain.</p>
|
<p>@ross: yes, we have links between the sites. It' just the home page, and which one comes up when someone searches for "my company" in google.</p>
<p>Thanks!</p>
| 5,218
|
<p>I have some C# code in an ASP.Net application that does this:</p>
<p>Bitmap bmp = new Bitmap(1184, 1900);</p>
<p>And occasionally it throws an exception "Parameter is not valid". Now i've been googling around and apparently GDI+ is infamous for throwing random exceptions, and lots of people have had this problem, but nobody has a solution to it! I've checked the system and it has plenty of both RAM and swap space.
Now in the past if i do an 'iisreset' then the problem goes away, but it comes back in a few days. But i'm not convinced i've caused a memory leak, because as i say above there is plenty of ram+swap free.</p>
<p>Anyone have any solutions?</p>
|
<p>Stop using GDI+ and start using the WPF Imaging classes (.NET 3.0). These are a major cleanup of the GDI+ classes and tuned for performance. Additionally, it sets up a "bitmap chain" that allows you to easily perform multiple actions on the bitmap in an efficient manner.</p>
<p>Find more by reading about <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx" rel="nofollow noreferrer">BitmapSource</a></p>
<p>Here's an example of starting with a blank bitmap just waiting to receive some pixels:</p>
<pre><code>using System.Windows.Media.Imaging;
class Program {
public static void Main(string[] args) {
var bmp = new WriteableBitmap(1184, 1900, 96.0, 96.0, PixelFormat.Bgr32, null);
}
}
</code></pre>
|
<p>I just got a reply from microsoft support. Apparently if you look here:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.drawing.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.drawing.aspx</a></p>
<p>You can see it says "Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions."
So they're basically washing their hands of the issue.
It appears that they're admitting that this section of the .Net framework is unreliable. I'm a bit disappointed.</p>
<p>Next up - can anyone recommend a similar library to open a gif file, superimpose some text, and save it again?</p>
| 15,885
|
<p>I am looking for reference documentation for designMode in Firefox 2/3 and IE 6/7/8. Does anyone have links to good references?</p>
|
<p>Try <a href="https://developer.mozilla.org/En/Rich-Text_Editing_in_Mozilla" rel="nofollow noreferrer">Mozilla's developer reference</a>. (Also indicates IE inconsistencies and omitted commands.)</p>
|
<p>Try <a href="https://developer.mozilla.org/En/Rich-Text_Editing_in_Mozilla" rel="nofollow noreferrer">Mozilla's developer reference</a>. (Also indicates IE inconsistencies and omitted commands.)</p>
| 29,024
|
<p>I have a dict, which I need to pass key/values as keyword arguments.. For example..</p>
<pre><code>d_args = {'kw1': 'value1', 'kw2': 'value2'}
example(**d_args)
</code></pre>
<p>This works fine, <em>but</em> if there are values in the d_args dict that are not accepted by the <code>example</code> function, it obviously dies.. Say, if the example function is defined as <code>def example(kw2):</code></p>
<p>This is a problem since I don't control either the generation of the <code>d_args</code>, or the <code>example</code> function.. They both come from external modules, and <code>example</code> only accepts some of the keyword-arguments from the dict..</p>
<p>Ideally I would just do</p>
<pre><code>parsed_kwargs = feedparser.parse(the_url)
valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2)
PyRSS2Gen.RSS2(**valid_kwargs)
</code></pre>
<p>I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: <strong>Is there a way to programatically list the keyword arguments the a specific function takes?</strong></p>
|
<p>A little nicer than inspecting the code object directly and working out the variables is to use the inspect module.</p>
<pre><code>>>> import inspect
>>> def func(a,b,c=42, *args, **kwargs): pass
>>> inspect.getargspec(func)
(['a', 'b', 'c'], 'args', 'kwargs', (42,))
</code></pre>
<p>If you want to know if its callable with a particular set of args, you need the args without a default already specified. These can be got by:</p>
<pre><code>def get_required_args(func):
args, varargs, varkw, defaults = inspect.getargspec(func)
if defaults:
args = args[:-len(defaults)]
return args # *args and **kwargs are not required, so ignore them.
</code></pre>
<p>Then a function to tell what you are missing from your particular dict is:</p>
<pre><code>def missing_args(func, argdict):
return set(get_required_args(func)).difference(argdict)
</code></pre>
<p>Similarly, to check for invalid args, use:</p>
<pre><code>def invalid_args(func, argdict):
args, varargs, varkw, defaults = inspect.getargspec(func)
if varkw: return set() # All accepted
return set(argdict) - set(args)
</code></pre>
<p>And so a full test if it is callable is :</p>
<pre><code>def is_callable_with_args(func, argdict):
return not missing_args(func, argdict) and not invalid_args(func, argdict)
</code></pre>
<p>(This is good only as far as python's arg parsing. Any runtime checks for invalid values in <code>kwargs</code> obviously can't be detected.)</p>
|
<p>Extending DzinX's answer:</p>
<pre><code>argnames = example.func_code.co_varnames[:func.func_code.co_argcount]
args = dict((key, val) for key,val in d_args.iteritems() if key in argnames)
example(**args)
</code></pre>
| 23,939
|
<p>I just spent half an one our to find out what caused the Error-Message "Ci is not defined" in my JavaScript code. I finally found the reason:</p>
<p>It should be (jQuery):</p>
<pre><code>$("asd").bla();
</code></pre>
<p>It was:</p>
<pre><code>("asd").bla();
</code></pre>
<p>(Dollar sign gone missing)</p>
<p>Now after having fixed the problem I'd like to understand the message itself: What does Firefox mean when it tells me that "Ci" is not defined. What's "Ci"?</p>
<hr>
<p>Update:
I'm using the current version of Firefox (3.0.3).</p>
<p>To reproduce, just use this HTML code:</p>
<pre><code><html><head><title>test</title>
<script>
("asd").bla();
</script>
</head><body></body></html>
</code></pre>
<p>To make it clear: I know what caused the error message. I'd just like to know what Firefox tries to tell me with "Ci"...</p>
|
<p>I don't know which version of FF you are using, but regardless, the message is probably referring to the fact that <code>bla()</code> is not a function available on the String object. Since you were missing the <code>$</code>, which means you were missing a function, <code>("asd")</code> would evaluate to a string, and then the JavaScript interpreter would try to call <code>bla()</code> on that object. So, if you had the following code in your project:</p>
<pre><code>String.prototype.bla = function() {};
// now this next line will execute without any problems:
("asd").bla();
</code></pre>
<p>So, it is possible that <code>Ci</code> is some internal Firefox symbol that simply refers to the idea of a function. That is my guess, I imagine you are going to need someone that knows something about Firefox's internals to get a better answer to this question...</p>
<hr>
<p>UPDATE: I am running your example code in the <em>exact</em> same version of FF as you are, but it reports the error as:</p>
<blockquote>
<p>Error: "asd".bla is not a function<br>
Source File: file:///C:/test.html<br>
Line: 3</p>
</blockquote>
<p>Perhaps you have an extension/plug-in running that does something with this? Maybe some Greasemonkey script or something?</p>
|
<p>Assuming it's CodeIngiter, it can't find the js file.</p>
| 33,868
|
<p>I'm implementing a simple service using datagrams over unix local sockets (AF_UNIX address family, i.e. <strong>not UDP</strong>). The server is bound to a public address, and it receives requests just fine. Unfortunately, when it comes to answering back, <code>sendto</code> fails unless the client is bound too. (the common error is <code>Transport endpoint is not connected</code>).</p>
<p>Binding to some random name (filesystem-based or abstract) works. But I'd like to avoid that: who am I to guarantee the names I picked won't collide?</p>
<p>The unix sockets' stream mode documentation tell us that an abstract name will be assigned to them at <code>connect</code> time if they don't have one already. Is such a feature available for datagram oriented sockets?</p>
|
<p>I assume that you are running Linux; I don't know if this advice applies to SunOS or any UNIX. </p>
<p>First, the answer: after the socket() and before the connect() or first sendto(), try adding this code:</p>
<pre><code>struct sockaddr_un me;
me.sun_family = AF_UNIX;
int result = bind(fd, (void*)&me, sizeof(short));
</code></pre>
<p>Now, the explanation: the the <a href="http://www.linuxmanpages.com/man7/unix.7.php" rel="nofollow noreferrer">unix(7)</a> man page says this:</p>
<blockquote>
<p>When a socket is connected and it
doesn’t already have a local address a
unique address in the abstract
namespace will be generated
automatically.</p>
</blockquote>
<p>Sadly, the man page lies. </p>
<p>Examining the <a href="http://lxr.linux.no/linux+v2.6.26.5/net/unix/af_unix.c#L925" rel="nofollow noreferrer">Linux source code</a>, we see that unix_dgram_connect() only calls unix_autobind() if SOCK_PASSCRED is set in the socket flags. Since I don't know what SOCK_PASSCRED is, and it is now 1:00AM, I need to look for another solution. </p>
<p>Examining <a href="http://lxr.linux.no/linux+v2.6.26.5/net/unix/af_unix.c#L765" rel="nofollow noreferrer">unix_bind</a>, I notice that unix_bind calls unix_autobind if the passed-in size is equal to "sizeof(short)". Thus, the solution above.</p>
<p>Good luck, and good morning.</p>
<p>Rob</p>
|
<p>I'm not so sure I understand your question completely, but here is a datagram implementation of an echo server I just wrote. You can see the server is responding to the client on the same IP/PORT it was sent from.</p>
<p>Here's the code</p>
<p>First, the server (listener)</p>
<pre><code>from socket import *
import time
class Listener:
def __init__(self, port):
self.port = port
self.buffer = 102400
def listen(self):
sock = socket(AF_INET, SOCK_DGRAM)
sock.bind(('', self.port))
while 1:
data, addr = sock.recvfrom(self.buffer)
print "Received: " + data
print "sending to %s" % addr[0]
print "sending data %s" % data
time.sleep(0.25)
#print addr # will tell you what IP address the request came from and port
sock.sendto(data, (addr[0], addr[1]))
print "sent"
sock.close()
if __name__ == "__main__":
l = Listener(1975)
l.listen()
</code></pre>
<p>And now, the Client (sender) which receives the response from the Listener</p>
<pre><code>from socket import *
from time import sleep
class Sender:
def __init__(self, server):
self.port = 1975
self.server = server
self.buffer = 102400
def sendPacket(self, packet):
sock = socket(AF_INET, SOCK_DGRAM)
sock.settimeout(10.75)
sock.sendto(packet, (self.server, int(self.port)))
while 1:
print "waiting for response"
data, addr = sock.recvfrom(self.buffer)
sock.close()
return data
if __name__ == "__main__":
s = Sender("127.0.0.1")
response = s.sendPacket("Hello, world!")
print response
</code></pre>
| 12,019
|
<p>I'm playing with the routing.rb code in Rails 2.1, and trying to to get it to the point where I can do something useful with the RoutingError exception that is thrown when it can't find the appropriate path.</p>
<p>This is a somewhat tricky problem, because there are some class of URLs which are just plain BAD: the /azenv.php bot attacks, the people typing /bar/foo/baz into the URL, etc... we don't want that.</p>
<p>Then there's subtle routing problems, where we do want to be notified: /artists/ for example, or ///. In these situations, we may want an error being thrown, or not... or we get Google sending us URLs which used to be valid but are no longer because people deleted them.</p>
<p>In each of these situations, I want a way to contain, analyze and filter the path that we get back, or at least some Railsy way to manage routing past the normal 'fallback catchall' url. Does this exist?</p>
<p>EDIT:</p>
<p>So the code here is: </p>
<pre><code># File vendor/rails/actionpack/lib/action_controller/rescue.rb, line 141
def rescue_action_without_handler(exception)
log_error(exception) if logger
erase_results if performed?
# Let the exception alter the response if it wants.
# For example, MethodNotAllowed sets the Allow header.
if exception.respond_to?(:handle_response!)
exception.handle_response!(response)
end
if consider_all_requests_local || local_request?
rescue_action_locally(exception)
else
rescue_action_in_public(exception)
end
end
</code></pre>
<p>So our best option is to override log_error(exception) so that we can filter down the exceptions according to the exception. So in ApplicationController</p>
<pre><code>def log_error(exception)
message = '...'
if should_log_exception_as_debug?(exception)
logger.debug(message)
else
logger.error(message)
end
end
def should_log_exception_as_debug?(exception)
return (ActionController::RoutingError === exception)
end
</code></pre>
<p>Salt for additional logic where we want different controller logic, routes, etc.</p>
|
<p>Nooooo!!! Don't implement method_missing on your controller! And please try to avoid action_missing as well.</p>
<p>The frequently touted pattern is to add a route:</p>
<pre><code>map.connect '*', :controller => 'error', :action => 'not_found'
</code></pre>
<p>Where you can show an appropriate error.</p>
<p>Rails also has a mechanism called rescue_action_in_public where you can write your own error handling logic -- we really should clean it up and encourage people to use it. PDI! :-)</p>
|
<p>There's the method_missing method. You could implement that in your Application Controller and catch all missing actions, maybe logging those and redirecting to the index action of the relevant controller. This approach would ignore everything that can't be routed to a controller, which is pretty close to what you want. </p>
<p>Alternatively, I'd just log all errors, extract the URL and sort it by # of times it occured.</p>
| 7,419
|
<p>I'm using MS SQL Server 2005. Is there a difference, to the SQL engine, between</p>
<pre><code>SELECT * FROM MyTable;
</code></pre>
<p>and</p>
<pre><code>SELECT ColA, ColB, ColC FROM MyTable;
</code></pre>
<p>When ColA, ColB, and ColC represent every column in the table?</p>
<p>If they are the same, is there a reason why you should use the 2nd one anyway? I have a project that's heavy on LINQ, and I'm not sure if the standard SELECT * it generates is a bad practice, or if I should always be a .Select() on it to specify which cols I want.</p>
<p>EDIT: Changed "When ColA, ColB, and ColC are all the columns to the table?" to "When ColA, ColB, and ColC represent every column in the table?" for clarity.</p>
|
<p>Generally, it's better to be explicit, so <code>Select col1, col2 from Table</code> is better. The reason being that at some point, an extra column may be added to that table, and would cause unneeded data to be brought back from the query.</p>
<p>This isn't a hard and fast rule though. </p>
|
<p>selecting each column is better than just * because in case you add or delete a new row you HAVE to look at the code and take a look what you were doing with the retrieved data.<br>
Also, it helps you understand your code better and allows you to use aliases as column names (in case you're performing a join of tables with a column sharing the name)</p>
| 25,633
|
<p>I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using <code>File.Delete()</code>.</p>
|
<p>Killing other processes is not a healthy thing to do. If your scenario involves something like uninstallation, you could use the <a href="https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexa" rel="nofollow noreferrer"><strong><code>MoveFileEx</code></strong> API function</a> to mark the file for deletion upon next reboot.</p>
<p>If it appears that you really need to delete a file in use by another process, I'd recommend re-considering the actual problem before considering any solutions.</p>
|
<p>Oh, one big hack I employed years ago, is that Windows won't let you <em>delete</em> files, but it does let you <em>move</em> them.</p>
<p>Pseudo-sort-of-code:</p>
<pre><code>mv %WINDIR%\System32\mfc42.dll %WINDIR\System32\mfc42.dll.old
Install new mfc42.dll
Tell user to save work and restart applications
</code></pre>
<p>When the applications restarted (note we didn't need to reboot the machine), they loaded the new <code>mfc42.dll</code>, and all was well. That, coupled with <code>PendingFileOperations</code> to delete the old one the next time the whole system restarted, worked pretty well.</p>
| 2,345
|
<p>I want to make a deep copy of a LINQ to XML XElement. The reason I want to do this is there are some nodes in the document that I want to create modified copies of (in the same document). I don't see a method to do this.</p>
<p>I could convert the element to an XML string and then reparse it, but I'm wondering if there's a better way.</p>
|
<p>There is no need to reparse. One of the constructors of XElement takes another XElement and makes a deep copy of it:</p>
<pre><code>XElement original = new XElement("original");
XElement deepCopy = new XElement(original);
</code></pre>
<p>Here are a couple of unit tests to demonstrate:</p>
<pre><code>[TestMethod]
public void XElementShallowCopyShouldOnlyCopyReference()
{
XElement original = new XElement("original");
XElement shallowCopy = original;
shallowCopy.Name = "copy";
Assert.AreEqual("copy", original.Name);
}
[TestMethod]
public void ShouldGetXElementDeepCopyUsingConstructorArgument()
{
XElement original = new XElement("original");
XElement deepCopy = new XElement(original);
deepCopy.Name = "copy";
Assert.AreEqual("original", original.Name);
Assert.AreEqual("copy", deepCopy.Name);
}
</code></pre>
|
<p>I do not believe there is an existing mechanism that allows you to perform a deep copy of an XNode style tree. I think you are left with two options.</p>
<ol>
<li>Do as you suggested an convert to a string and then back into a tree</li>
<li>Write on yourself with a visitor pattern</li>
</ol>
<p>The visitor pattern is certainly possible but it will take a good deal of work an testing. I think your best option is #1.</p>
| 25,723
|
<p>In tomcat 6 i have a servlet running openbluedragon, everything compiles and servers up quik, with the exception of images, they really lag significantly. Any suggestions optimization for image serving?</p>
<p>Here is my server.xml:</p>
<pre><code> <Service name="Catalina">
<Connector port="8009" protocol="AJP/1.3" />
<Connector port="8080" maxThreads="100" protocol="HTTP/1.1" connectionTimeout="20000" />
<Engine name="Standalone" defaultHost="hostname.whatever" jvmRoute="ajp13">
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
<Host name="hostname.whatever" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
...context
</Host>
</Engine>
</Service>
</code></pre>
|
<p>Another option is to use apache as a frontend, connecting tomcat with mod_jk. This way you can let apache serve static content (e.g. images, css, javascript) and let tomcat generate the dynamic content. Might leave a bit of work to separate the static content from the dynamic ones, but works great for me.</p>
<p>On Unix, having an apache as frontend is a nice option because being bound to port 80 you're often forced to run as root. Apache knows how to drop root permissions after binding a port, Tomcat doesn't. You don't want a server faced to the public to run as root.</p>
<p>(This is similar to the reverse proxy answer, but doesn't involve a proxy but mod_jk)</p>
|
<p>If you have the option, you could add a reverse proxy in advance of your application. At work I have an Apache web server that receives all inbound HTTP connections. Based on the URL, it either forwards the request to another server or serves up the content itself. I've used this approach to accelerate serving up static content for a Trac site. The ProxyPass and ProxyPassReverse directives are a good place to start looking if you want to go this route.</p>
<p>As a simple example, if you have a virtual directory called /images, Apache could serve up any request for something in that directory and forward everything else to your Tomcat instance. The syntax is pretty comprehensive. If there is any method at all to the way your static content is identified this is an approach that will work.</p>
<p>Apache isn't the only choice here. I think all modern web servers include similar functionality. If I was starting today I'd probably look at LigHTTPd instead, just because it does less.</p>
<p>There may even be caching reverse proxies that figure this out for you automatically. I'm not familiar with any of them though.</p>
| 13,482
|
<p>How do you unit test a large MFC UI application?</p>
<p>We have a few large MFC applications that have been in development for many years, we use some standard automated QA tools to run basic scripts to check fundamentals, file open etc. These are run by the QA group post the daily build.</p>
<p>But we would like to introduce procedures such that individual developers can build and run tests against dialogs, menus, and other visual elements of the application before submitting code to the daily build.</p>
<p>I have heard of such techniques as hidden test buttons on dialogs that only appear in debug builds, are there any standard toolkits for this.</p>
<p>Environment is C++/C/FORTRAN, MSVC 2005, Intel FORTRAN 9.1, Windows XP/Vista x86 & x64. </p>
|
<p>It depends on how the App is structured. If logic and GUI code is separated (MVC) then testing the logic is easy. Take a look at Michael Feathers <a href="https://web.archive.org/web/20080509080327/http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf" rel="nofollow noreferrer" title="Humble Dialog Box">"Humble Dialog Box"</a> (PDF).</p>
<p>EDIT: If you think about it: You should very carefully refactor if the App is not structured that way. There is no other technique for testing the logic. Scripts which simulate clicks are just scratching the surface. </p>
<p>It is actually pretty easy: </p>
<p>Assume your control/window/whatever changes the contents of a listbox when the user clicks a button and you want to make sure the listbox contains the right stuff after the click.</p>
<ol>
<li>Refactor so that there is a separate list with the items for the listbox to show. The items are stored in the list and are not extracted from whereever your data comes from. The code that makes the listbox list things knows only about the new list. </li>
<li>Then you create a new controller object which will contain the logic code. The method that handles the button click only calls mycontroller->ButtonWasClicked(). It does not know about the listbox or anythings else. </li>
<li>MyController::ButtonWasClicked() does whats need to be done for the intended logic, prepares the item list and tells the control to update. For that to work you need to decouple the controller and the control by creating a interface (pure virtual class) for the control. The controller knows only an object of that type, not the control. </li>
</ol>
<p>Thats it. The controller contains the logic code and knows the control only via the interface. Now you can write regular unit test for MyController::ButtonWasClicked() by mocking the control. If you have no idea what I am talking about, read Michaels article. Twice. And again after that.<br>
(Note to self: must learn not to blather that much)</p>
|
<p>Actually we have been using Rational Team Test, then Robot, but in recent discussions with Rational we discovered they have no plans to support Native x64 applications focusing more on .NET, so we decided to switch Automated QA tools. This is great but licensing costs don't allow us to enable it for all developers.</p>
<p>All our applications support a COM API for scripting, which we regression test via VB, but this tests the API no the application as such.</p>
<p>Ideally I would be interested on how people integrate cppunit and similar unit testing frameworks into the application at a developer level.</p>
| 13,302
|
<p>I am invoking a C library via JNI that prints to stdout. How can I redirect this output to System.out?</p>
|
<p><code>System.out</code> <strong>is</strong> <code>stdout</code>. Is there some more fundamental problem you're having (mixed up output, perhaps?).</p>
<p>Since another member has also mentioned that last point - I should explain further:</p>
<p><code>System.out</code> and <code>stdout</code> both correspond to file descriptor #1.</p>
<p>However both Java's <code>OutputStream</code> (and derived classes) and C's <code>stdio</code> library have their own (independent) buffering mechanisms so as to reduce the number of calls to the underlying <code>write</code> system call. Just because you've called <code>printf</code> or similar, it's not guaranteed that your output will appear straightaway.</p>
<p>Because these buffering methods are independent, output from within Java code could (in theory) get mixed up or otherwise appear out-of-order relative to output from the C code.</p>
<p>If that's a concern, you should arrange to call <code>System.out.flush()</code> before calling your JNI function, and in your C function (if it's using <code>stdio</code> rather than the low-level <code>write</code> call) you should call <code>fflush(stdout)</code> before returning.</p>
|
<p>As Alnitak wrote, you should print to stdout. You should note that it can take a while for the message to appear on the screen. In case the timing is important, you should print a timestamp with the message when you print to stdout.</p>
| 37,073
|
<p>Is a string literal in C++ created in static memory and destroyed only when the program exits?</p>
|
<p>Where it's created is an implementation decision by the compiler writer, really. Most likely, string literals will be stored in read-only segments of memory since they never change.</p>
<p>In the old compiler days, you used to have static data like these literals, and global but changeable data. These were stored in the TEXT (code) segment and DATA (initialised data) segment.</p>
<p>Even when you have code like <code>char *x = "hello";</code>, the <code>hello</code> string itself is stored in read-only memory while the variable <code>x</code> is on the stack (or elsewhere in writeable memory if it's a global). <code>x</code> just gets set to the address of the <code>hello</code> string. This allows all sorts of tricky things like string folding, so that "invalid option" (0x1000) and "valid option" (0x1002) can use the same memory block as follows:</p>
<pre><code>+-> plus:0 1 2 3 4 5 6 7 8 9 A B C D E
| +---+---+---+---+---+---+---+---+---+---+---+---+---+---+----+
0x1000 | i | n | v | a | l | i | d | | o | p | t | i | o | n | \0 |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+----+
</code></pre>
<p>Keep in mind I don't mean read-only memory in terms of ROM, just memory that's dedicated to storing unchangeable stuff (which may be marked really read-only by the OS).</p>
<p>They're also never destroyed until <code>main()</code> exits.</p>
|
<p>String literals are stored in read-only segments of memory </p>
| 45,416
|
<p>In a silverlight application, I want to access the page the silverlight .xap file from an HTTP subdomain, but have the web services access a different subdomain for sensitive information over HTTPS.</p>
<p>I set up clientaccesspolicy.xml at the root of the subdomain and it lets the silverlight app access its services over http, but not over https. It gives the cross domain access error that it would give normally without a clientaccesspolicy in place.</p>
<p>I know that browsers themselves have a lot of restrictions about mixing http and https. Am I trying to do something that is not allowed? </p>
|
<p>Check out:<a href="http://silverlight.net/forums/t/12741.aspx" rel="nofollow noreferrer">http://silverlight.net/forums/t/12741.aspx</a></p>
<blockquote>
<p>You can either make https calls to the
same domain or http cross-domain
calls, but not https cross-domain
calls.</p>
<p>This is described in
<a href="http://msdn2.microsoft.com/en-us/library/cc189008(VS.95).aspx" rel="nofollow noreferrer">http://msdn2.microsoft.com/en-us/library/cc189008(VS.95).aspx</a></p>
<p>(see "If not HTTPS" in the matrix)
By JohnSpurlock</p>
</blockquote>
|
<p>The important thing to note here that is not in the above information clearly is you must have access to the "ROOT" level of the domain request, and the clientaccesspolicy.xml must reside at that level.</p>
<p>If for example you have a production environment that your application is behind a load balancer that directs traffic as most large companies do to your application via the URI, you then have a little bit of a problem.</p>
<p>Example: <a href="http://mydomain.com/MyApplication/" rel="nofollow noreferrer">http://mydomain.com/MyApplication/</a>* goes to your server, where your app resides.
<a href="http://mydomain.com/clientaccesspolicy.xml" rel="nofollow noreferrer">http://mydomain.com/clientaccesspolicy.xml</a> is where the policy exists.</p>
| 9,922
|
<p>I'm trying to catch a ClassCastException when deserializing an object from xml.</p>
<p>So,</p>
<pre><code>try {
restoredItem = (T) decoder.readObject();
} catch (ClassCastException e){
//don't need to crash at this point,
//just let the user know that a wrong file has been passed.
}
</code></pre>
<p>And yet this won't as the exception doesn't get caught. What would you suggest?</p>
|
<p>The code in the question should give you an unchecked cast warning. Listen to -Xlint.</p>
<p>All the compiler knows about T is its bounds, which it probably doesn't have (other than explicitly extending Object and a super of the null type). So effectively the cast at runtime is (Object) - not very useful.</p>
<p>What you can do is pass in an instance of the Class of the parameterised type (assuming it isn't generic).</p>
<pre><code>class MyReader<T> {
private final Class<T> clazz;
MyReader(Class<T> clazz) {
if (clazz == null) {
throw new NullPointerException();
}
this.clazz = clazz;
}
public T restore(String from) {
...
try {
restoredItem = clazz.cast(decoder.readObject());
...
return restoredItem;
} catch (ClassCastException exc) {
...
}
}
}
</code></pre>
<p>Or as a generic method:</p>
<pre><code> public <T> T restore(Class<T> clazz, String from) {
...
try {
restoredItem = clazz.cast(decoder.readObject());
...
</code></pre>
|
<p>Well, I can't use <code>instanceof</code> operator as the method is a parametrized one:</p>
<pre><code>public T restore(String from){
...
restoredItem = (T) decoder.readObject();
...
}
</code></pre>
<p>And generics in Java are compile-time only.</p>
| 22,626
|
<p>I know that JavaScript doesn't support macros (Lisp-style ones) but I was wondering if anyone had a solution to maybe simulate macros? I Googled it, and one of the solutions suggested using <code>eval()</code>, but as he said, would be quite costly.</p>
<p>They don't really have to be very fancy. I just want to do simple stuff with them. And it shouldn't make debugging significantly harder :)</p>
|
<p>You could use <a href="http://common-lisp.net/project/parenscript/" rel="noreferrer">parenscript</a>. That'll give you macros for Javascript.</p>
|
<p>Javascript is interpreted. Eval isn't any more costly that anything else in Javascript.</p>
| 23,521
|
<p>Recently I've been experimenting with TDD while developing a GUI application in Python. I find it very reassuring to have tests that verify the functionality of my code, but it's been tricky to follow some of the recommened practices of TDD. Namely, writing tests first has been hard. And I'm finding it difficult to make my tests readable (due to extensive use of a mocking library).</p>
<p>I chose a mocking library called <a href="http://labix.org/mocker" rel="noreferrer">mocker</a>. I use it a lot since much of the code I'm testing makes calls to (a) other methods in my application that depend on system state or (b) ObjC/Cocoa objects that cannot exist without an event loop, etc.</p>
<p>Anyway, I've got a lot of tests that look like this:</p>
<pre><code>def test_current_window_controller():
def test(config):
ac = AppController()
m = Mocker()
ac.iter_window_controllers = iwc = m.replace(ac.iter_window_controllers)
expect(iwc()).result(iter(config))
with m:
result = ac.current_window_controller()
assert result == (config[0] if config else None)
yield test, []
yield test, [0]
yield test, [1, 0]
</code></pre>
<p>Notice that this is actually three tests; all use the same parameterized test function. Here's the code that is being tested:</p>
<pre><code>def current_window_controller(self):
try:
# iter_window_controllers() iterates in z-order starting
# with the controller of the top-most window
# assumption: the top-most window is the "current" one
wc = self.iter_window_controllers().next()
except StopIteration:
return None
return wc
</code></pre>
<p>One of the things I've noticed with using mocker is that it's easier to write the application code first and then go back and write the tests second, since most of the time I'm mocking many method calls and the syntax to write the mocked calls is much more verbose (thus harder to write) than the application code. It's easier to write the app code and then model the test code off of that.</p>
<p>I find that with this testing method (and a bit of discipline) I can easily write code with 100% test coverage.</p>
<p>I'm wondering if these tests are good tests? Will I regret doing it this way down the road when I finally discover the secret to writing good tests?</p>
<p>Am I violating the core principles of TDD so much that my testing is in vain?</p>
|
<p><strong>If you are writing your tests after you've written your code and making them pass, you are not doing TDD</strong> (nor are you getting any benefits of Test-First or Test-Driven development.. check out SO questions for definitive books on TDD)</p>
<blockquote>
<p>One of the things I've noticed with
using mocker is that it's easier to
write the application code first and
then go back and write the tests
second, since most of the time I'm
mocking many method calls and the
syntax to write the mocked calls is
much more verbose (thus harder to
write) than the application code. It's
easier to write the app code and then
model the test code off of that.</p>
</blockquote>
<p>Of course, its easier because you are just testing that the sky is orange after you made it orange by painting it with a specific kind of brush.
This is retrofitting tests (for self-assurance). Mocks are good but you should know how and when to use them - Like the saying goes 'When you have a hammer everything looks like a nail' It's also easy to write a whole load of unreadable and not-as-helpful-as-can-be tests. The time spent understanding what the test is about is time lost that can be used to fix broken ones. </p>
<p>And the point is: </p>
<ul>
<li>Read <a href="http://martinfowler.com/articles/mocksArentStubs.html#ClassicalAndMockistTesting" rel="nofollow noreferrer">Mocks aren't stubs - Martin Fowler</a> if you haven't already. Google out some documented instances of good <a href="http://martinfowler.com/eaaDev/ModelViewPresenter.html" rel="nofollow noreferrer">ModelViewPresenter</a> patterned GUIs (Fake/Mock out the UIs if necessary). </li>
<li>Study your options and choose wisely. I'll play the guy with the halo on your left shoulder in white saying 'Don't do it.' Read this question as to <a href="https://stackoverflow.com/questions/59195/how-are-mocks-meant-to-be-used">my reasons</a> - St. Justin is on your right shoulder. I believe he has also something to say:) </li>
</ul>
|
<p>Unit tests are really useful when you refactor your code (ie. completely rewrite or move a module). As long as you have unit tests before you do the big changes, you'll have confidence that you havent forgotten to move or include something when you finish.</p>
| 10,480
|
<p>I am using a codebehind page in ASP.NET to perform a SQL query. The query is loaded into a string, the connection is established (To Oracle), and we get it started by having the connection perform .ExecuteReader into a OleDBDataReader (We'll call it DataRead). I'll try to hammer out an example below. (Consider Drop as an ASP DropDownList control)</p>
<pre><code>Dim LookFor as String = "Fuzzy Bunnies"
While DataRead.Read
If LookFor = DataRead.Item("Kinds of Bunnies") Then
'Meets special critera, do secondary function'
Drop.Items.Add(DataRead.Item("Subgroup of Bunnies"))
...
End if
...
End While
</code></pre>
<p>This is the only way I know of doing a dynamic add to a DropDownList. However, each item in a DropDownList has a .text property and a .value property. How can we define the .value as being different from the .text in code?</p>
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitemcollection.add.aspx" rel="nofollow noreferrer">Add</a> function can take a <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitem.aspx" rel="nofollow noreferrer">ListItem</a>, so you can do</p>
<pre><code>Dim li as new ListItem(DataRead.Item("Subgroup of Bunnies"), "myValue")
Drop.Items.Add(li)
</code></pre>
|
<p>you'd select a second column into your datareader (such as an IDENTITY field) and then assign do your Item generation like this:</p>
<pre><code>Dim item as new listitem
item.text = DataRead.Item("SubGroup Of Bunnies")
item.value = DataRead.Item("ID")
Drop.Items.Add(item)
</code></pre>
<p>You may also want to look into the DATABIND functionality, and filtering out "FUZZY BUNNIES" in the SQL statement itself.</p>
| 18,572
|
<p>I have an object instance which I access with the ME as it accesses the instantiated object. I have a method that gets a collection of these objects and I wish to assign the first one to the instantiated object. </p>
<p>This is some of the code</p>
<pre><code>Dim Books As New BookCollection(True)
Books.ListByThemeFeatured(ThemeID, 1) ' Fills the collection
If Books.Count > 0 Then
Me = Books(0) ' Should set the first item to the current object
End If
</code></pre>
<p>Is this possible?</p>
<p>EDIT: Me refers to the class that was instantiated. In this case it is a BookEntity Class. THis method would have been called using the following code</p>
<pre><code> Dim Book As New BookEntity
Book.FeaturedBook() ' Should fill the book entity with a featured book
</code></pre>
|
<p>As stated in this <a href="https://stackoverflow.com/questions/176745/circular-references-in-java">SO question</a>, circular reference is well managed.</p>
<p>Java does not do reference counting, it does uses <a href="https://en.wikipedia.org/wiki/Tracing_garbage_collection" rel="nofollow noreferrer">tracing garbage collection</a> (for example mark-and-sweep, copying collection or a some combination thereof). If follows all the active references to find out what objects are "reachable" and then it cleans up everything else.</p>
<p>References in objects not themselves reachable don't affect reachability so it doesn't matter if they are null or not.</p>
<p>About the only case in which setting a reference to null might, conceivably, have a significant effect is in discarding a very large object in the middle of a long running method. </p>
<p>In that case, setting null to the reference of the graph will help making an <strong>island of isolation</strong> (even for internal circular references) as described in this <a href="http://detailfocused.blogspot.com/2008/03/garbage-collection.html" rel="nofollow noreferrer">article</a>.</p>
<p>You will find more details about the unreachable state in <a href="http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html" rel="nofollow noreferrer">The Truth About Garbage Collection</a>:</p>
<p><strong>Unreachable</strong></p>
<p>An object enters an unreachable state when no more strong references to it exist.<br>
When an object is unreachable, it is a candidate for collection. </p>
<p>Note the wording:<br>
Just because an object is a candidate for collection doesn’t mean it will be immediately
collected. The JVM is free to delay collection until there is an immediate need for thememory being consumed by the object.</p>
<p>It’s important to note that not just any strong reference will hold an object in memory. These must be references that chain from a garbage collection root. GC roots are a special class of variable that includes:</p>
<ul>
<li>Temporary variables on the stack (of any thread)</li>
<li>Static variables (from any class)</li>
<li>Special references from JNI native code</li>
</ul>
<p><strong>Circular strong references don’t necessarily cause memory leaks</strong>.
Consider a code creating two objects, and assigns them references to each other.</p>
<pre><code>public void buidDog() {
Dog newDog = new Dog();
Tail newTail = new Tail();
newDog.tail = newTail;
newTail.dog = newDog;
}
</code></pre>
<p>Before the method returns, there are strong references from the temporary stack variables in the <code>buildDog</code> method pointing to both the <code>Dog</code> and the <code>Tail</code>.</p>
<p>After the <code>buildDog</code> method returns, the <code>Dog</code> and <code>Tail</code> both become unreachable from a root and are candidates for collection (although the VM might not actually collect these objects for an indefinite amount of time).</p>
|
<p>The JVM operates on the notion of "islands of unreachability". If there is an unreachable 'island' of interconnected objects then that set of objects is eligible for garbage collection in its entirety.</p>
| 34,151
|
<p>I am currently calling the following line of code:</p>
<pre><code>java.net.URL connection_url = new java.net.URL("http://<ip address>:<port>/path");
</code></pre>
<p>and I get the exception above when it executes. Any ideas as to why this is happening?</p>
|
<p>Your code works perfectly fine for me:</p>
<pre><code>public static void main(String[] args) {
try {
java.net.URL connection_url = new java.net.URL("http://:/path");
System.out.println("Instantiated new URL: " + connection_url);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
</code></pre>
<blockquote>
<p>Instantiated new URL: <a href="http://:/path" rel="nofollow noreferrer">http://:/path</a></p>
</blockquote>
<p>Sure you have the right line of code?</p>
|
<p>I have also had the same exception, but in my case the URL which I was trying to execute had a space appended. After removing the space it worked fine for me. Check that the URL does not have any trailing spaces in your case.</p>
| 8,457
|
<p>I'm writing some documentation in Markdown, and creating a separate file for each section of the doc. I would like to be able to convert all the files to HTML in one go, but I can't find anyone else who has tried the same thing. I'm on a Mac, so I would think a simple bash script should be able to handle it, but I've never done anything in bash and haven't had any luck. It seems like it should be simple to write something so I could just run:</p>
<pre><code>markdown-batch ./*.markdown
</code></pre>
<p>Any ideas?</p>
|
<p>This is how you would do it in Bash. </p>
<pre><code>for i in ./*.markdown; do perl markdown.pl --html4tags $i > $i.html; done;
</code></pre>
<p>Of course, you need the <a href="http://daringfireball.net/projects/markdown/" rel="noreferrer">Markdown script</a>.</p>
|
<p>I use this in a .bat file:</p>
<pre><code>@echo off
for %i in (*.txt) python markdown.py "%i"
</code></pre>
| 3,928
|
<p>Most sites are either fully released, or in beta.</p>
<p>But what happens if you have a large site, and some of the parts are still in Beta, and other parts aren't. </p>
<p>How do you effectively communicate this to the customer?</p>
|
<p>Maybe take a look at how Facebook, Bloglines, Gmail did it?</p>
<p>Like "We have this beta thing going on, come on over and see the same site with new stuff, but if it doesnt work, use the old parts"</p>
<p>Maybe gmail labs where you can sign up for "beta features"</p>
|
<p>If there's a certain way you enter the part of the beta site, maybe you can have a modal that pops up that they have to agree to every time. I wouldn't have it on every page since it gets annoying, so I would only use this approach if there is a definitive way to get into that part of the site (e.g. people won't be coming to random parts of the beta section through Google or something).</p>
| 7,459
|
<p>I have a winforms app and i want to keep track of every time a user clicks certain buttons, etc as well as other actions. What is the best way for me to keep track of this information and then put it together so i can run metrics on most used features, etc.</p>
<p>This is a winforms app and I have users around the world.</p>
|
<p>There are 2 big issues your design has to be sure to address</p>
<ol>
<li><p>Privacy (what Don alluded to) - You must be crystal clear what information you are collecting and sending up to your central server, ideally the users should be able to inspect the exact data you are sending back to the central server (if they wish to) - For any public software there should be a very easy way to opt out. </p></li>
<li><p>Performance and Scalability - You have to estimate how much data you really need on the server side and look at all sort of tricks that aggregate and compress the data client side (as well as have hard limits on the amount of traffic you will be sending and how often you will be sending it) </p></li>
</ol>
<p>As to the client side implementation, I would recommend investigating <a href="http://sqlite.phxsoftware.com/" rel="nofollow noreferrer">Sqlite.net</a> or another embedded DB. Using an embedded DB to store this information on the client will give you lots of flexibility with aggregations and will have the advantage of being transactional, fast and simple to implement. Sqlite has a very generous public domain license so from a legal perspective its really easy to use in public apps. </p>
|
<p>I'd try something like this:</p>
<pre><code> // execute this method once all forms have been created
public static void HookButtons()
{
foreach( Form f in Application.OpenForms )
{
EnumerateControls( f.Controls );
}
}
public static void EnumerateControls( ICollection controls )
{
foreach( Control ctrl in controls )
{
if( ctrl.Controls.Count > 0 )
{
EnumerateControls( ctrl.Controls );
}
if( ctrl is ButtonBase )
{
ctrl.MouseClick +=new MouseEventHandler( ctrl_MouseClick );
}
}
}
static void ctrl_MouseClick( object sender, MouseEventArgs e )
{
ButtonBase clicked = ((ButtonBase)sender);
// do something with the click information here
}
</code></pre>
| 37,656
|
<p>I'm trying to find the best way to speed up the delivery of the static images that compose the design of an mvc site. The images are not gzipped, nor cached in the server or on the client (with content expire). Options are:</p>
<ol>
<li>Find why images are not cached and gzipped direcly from IIS6</li>
<li>Write a specialized http handler</li>
<li>Register a special route for static images and write a bynary actionresult method</li>
</ol>
<p>What could be the best solution in terms of performance?</p>
|
<p>Best solution is to let IIS do it.</p>
<p><a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/502ef631-3695-4616-b268-cbe7cf1351ce.mspx?mfr=true" rel="nofollow noreferrer">IIS6 Compression</a> - most likely you need to <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/502ef631-3695-4616-b268-cbe7cf1351ce.mspx?mfr=true" rel="nofollow noreferrer">specify file types to be compressed</a> like .jpg, .png, .gif types, etc.</p>
<p>Caching will come from making sure that the correct headers are being sent to the client from code, and i believe there is a setting you can set in IIS that enables it for static content, but i'm not sure on that one.</p>
|
<p>There's a nice library up on the MSDN Code Gallery that does this. It's called <a href="http://code.msdn.microsoft.com/fastmvc" rel="nofollow noreferrer">FastMVC</a>.</p>
| 3,777
|
<p>Sorry if this is a bit long whinded... consider this:</p>
<p>I have a COM+ application in a namespace called <strong>Company</strong> that exposes an object called <strong>Server</strong> which has the following methods:</p>
<pre><code>bool Server.Execute(IOptions options)
IOptions Server.CreateOptions()
</code></pre>
<p>IOptions simply has a couple of boolean read/write properties as follows:</p>
<pre><code>IOptions.Option1 (bool)
IOptions.Option2 (bool)
</code></pre>
<p>I create a client application with the following code:</p>
<pre><code>Company.Server s = new Company.Server();
Company.IOptions serverOptions = s.CreateOptions();
serverOptions.Option1 = false;
serverOptions.Option2 = true;
s.Execute(serverOptions);
</code></pre>
<p>I install the COM+ application on machine A and then execute the client on machine A and all is well.</p>
<p>I then modify the client application so that it creates its own implementation of IOptions as follows:</p>
<pre><code>public class ClientOptions : Company.IOptions
{
public bool Option1 { get; set; }
public bool Option2 { get; set; }
}
Company.Server s = new Company.Server();
ClientOptions clientOptions = new ClientOptions();
clientOptions.Option1 = false;
clientOptions.Option2 = true;
s.Execute(clientOptions);
</code></pre>
<p>Again, I execute the client application on machine A and all is well. </p>
<p>If I install the COM+ application on machine B as a proxy to machine A and then execute the client, I get an E_ACCESSDENIED error on the call to:</p>
<pre><code>s.Execute(clientOptions);
</code></pre>
<p>Here's a summary of the code executing on machine B accessing machine A</p>
<pre><code>Company.Server s = new Company.Server();
Company.Options serverOptions = s.CreateOptions()
serverOptions.Option1 = false;
serverOptions.Option2 = true;
s.Execute(serverOptions); // this is fine
ClientOptions clientOptions = new ClientOptions();
clientOptions.Option1 = false;
clientOptions.Option2 = true;
s.Execute(clientOptions); // this causes the error
</code></pre>
<p>To summarise, why can I implement my own IOptions and use it in the COM+ application when the client is on the same machine as the COM+ application but not when the client is accessing the COM+ application via a proxy on another machine?</p>
<p>It seems that if the IOptions was created by the server then it's fine, but if it's created by the client then it's not.</p>
<p>Any help would be greatly appreciated.</p>
<p>Thanks,</p>
<p>Carl.</p>
|
<p>I going to extrapolate some older experience with DCOM which may or may not be helpful. When you get access denied, you have to look at the DCOM configuration parameters on machine B.</p>
<p>On older OS's (Windows 2000) you would run <strong>dcomcnfg</strong>. But in XP, you run Component Services from the Control Panel -- Administrative Tools. Under Vista, apparently, you have to run windows\System32\comexp.msc.</p>
<p>When you are in the Component Services administration, highlight My Computer and choose properties. The first thing you have to do is on the <strong>Defaults Properties</strong> Tab, click <strong>Enable Distributed COM on this Computer</strong>. Additionally, you may need to specify <strong>Launch and Activate</strong> and <strong>Access</strong> permissions in the <strong>COM Security</strong> tab. When doing so you may have to deal with both Edit Limits and Edit Defaults?</p>
<p>Please note, that I believe that these are DEFAULT permissions and that you may want to find your registered COM+ application in the application list and set application-specific access rights rather than machine-wide defaults. But I know you have to check that <strong>Enable Distributed COM on this Computer</strong> checkbox.</p>
<p>I hope this helps.</p>
|
<p>Try looking at the COM server's remote activation permissions on the remote machine via dcomcnfg.exe (should open up MMC snapin).</p>
<p>-Oisin</p>
| 42,490
|
<p>The Date object in JavaScript performs differently machine to machine and browser to browser in respect to the function's resolution in milliseconds. I've found most machines have a resolution of about 16 ms on IE, where Chrome or Firefox may have a resolution as good as 1ms.</p>
<p>Is there another function available to JavaScript in general or IE specifically that will give a better time resolution? I am trying to trap and record <code>keyDown</code> and <code>keyUp</code> times in milliseconds and need it in the +/- 10 ms range or less.</p>
<p>To see an illustration of this, check out the "resolutions of new date()" section of this page. There is a table with a test button that evaluates the current machine/browser's JavaScript time resolution in milliseconds. Interestingly, Chrome regularly gets a resolution of 1ms. </p>
<p><a href="http://www.merlyn.demon.co.uk/js-dates.htm#OV" rel="nofollow noreferrer">http://www.merlyn.demon.co.uk/js-dates.htm#OV</a> </p>
<p>My quest is for a JavaScript date-time method that will give sub 10ms resolution across browsers. something to replace or improve Date().</p>
|
<p>Since you are mentioning Internet Explorer, I assume that you are working on Windows. The 15 ms resolution you are getting may have to do with the Windows system timer resolution.</p>
<p>I've also noticed through running Java programs on Windows, that the resolution of the system timer is around 16 ms or so. (Using the <code>System.currentTimeMillis()</code> method.)</p>
<p>I did a quite search to see if I could find any information on the system timer resolution in Windows, and was able to find a link to <a href="http://technet.microsoft.com/en-us/sysinternals/bb897569.aspx" rel="nofollow noreferrer">Inside Windows NT High Resolution Timers</a> from TechNet. It mentioned a little bit about the resolution of the Windows system timer:</p>
<blockquote>
<p>Windows NT bases all of its timer
support off of one system clock
interrupt, which by default runs at a
10 millisecond granularity. This is
therefore the resolution of standard
Windows timers.</p>
</blockquote>
<p>(I'm assuming that Windows XP and Vista still has the same timer, consider it is a descendent of NT.)</p>
<p>Unless Firefox and Chrome have their own high-resolution timer implemented, I believe that the best resolution you'll be able to get from a browser on the Windows platform is going to be around 10 ms.</p>
<p>Although not relevant to this question, I also did find an article on MSDN on high-resolution timers on Windows: <a href="http://msdn.microsoft.com/en-us/magazine/cc163996.aspx" rel="nofollow noreferrer">mplement a Continuously Updating, High-Resolution Time Provider for Windows</a></p>
|
<p>AFAIK, milliseconds is as good as it gets in JavaScript. Here is the <a href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date" rel="nofollow noreferrer">Mozilla.org documentation for the Date object</a>. Nothing in there indicates anything with finer resolution.</p>
| 15,920
|
<p>I have a large (700kb) Flex .swf file representing the main file of a site. </p>
<p>For performance testing I wanted to try and move it off to Amazon S3 hosting (which i have already done with certain videos and large files). </p>
<p>I went ahead and did that, and updated the html page to reference the remote .swf.</p>
<p>It turns out that Flash will load any resources relative to the .swf file accessing the resource - no matter what the root of the html page is. So my resources are now being loaded from the remote site (where they don't exist).</p>
<p>There are two obvious things I could do :
* copy all my resources remotely (not ready for this since i'm just testing now)
* add in some layer of abstraction to every URL that the .swf accesses to derive a new path.</p>
<p>I really want to flick a switch and say 'load everything relative to [original server]'.</p>
<p>Does such a thing exist or am I stuck loading everythin from the remote machine unless I fully qualify every path?</p>
<p>i want to avoid anything 'hacky' like : subclass Image and hack the path there</p>
|
<p>Append a slash before your urls, this should load relative to the domain instead of the current folder:</p>
<pre><code>foo.load('/like/this/image.jpg')
</code></pre>
<p>This is a bit quick and dirty, feeding a "relative" url via a querystring (<a href="https://stackoverflow.com/questions/219788/loading-flex-resources-relative-to-server-root-as-opposed-to-swf-location#220518">or the base parameter</a>) would be way more flexible.</p>
|
<p>You could try specifying the <code>base</code> parameter of your SWF's embed/object tags. In theory it defines the base path that will be used to resolve relative paths for loading, but I don't know if it will work if the <code>base</code> value points to a different server from where the SWF is.</p>
<p>See the docs on embed/object params <a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_12701&sliceId=1" rel="nofollow noreferrer">here</a>. Scroll down to "<code>base</code>" at the middle.</p>
<p>If that doesn't work, another thing I've seen people do is to pass in a custom base path via <code>flashvars</code>. Then inside your SWF, you check if that base path is defined, and if so prepend it to relative URLs before loading.</p>
| 27,053
|
<p>What is the most efficient way to enumerate every cell in every sheet in a workbook?</p>
<p>The method below seems to work reasonably for a workbook with ~130,000 cells. On my machine it took ~26 seconds to open the file and ~5 seconds to enumerate the cells . However I'm no Excel expert and wanted to validate this code snippet with the wider community.</p>
<pre><code>DateTime timer = DateTime.Now;
Microsoft.Office.Interop.Excel.Application excelApplication = new Microsoft.Office.Interop.Excel.Application();
try
{
exampleFile = new FileInfo(Path.Combine(System.Environment.CurrentDirectory, "Large.xlsx"));
excelApplication.Workbooks.Open(exampleFile.FullName, false, false, missing, missing, missing, true, missing, missing, true, missing, missing, missing, missing, missing);
Console.WriteLine(string.Format("Took {0} seconds to open file", (DateTime.Now - timer).Seconds.ToString()));
timer = DateTime.Now;
foreach(Workbook workbook in excelApplication.Workbooks)
{
foreach(Worksheet sheet in workbook.Sheets)
{
int i = 0, iRowMax, iColMax;
string data = String.Empty;
Object[,] rangeData = (System.Object[,]) sheet.UsedRange.Cells.get_Value(missing);
if (rangeData != null)
{
iRowMax = rangeData.GetUpperBound(0);
iColMax = rangeData.GetUpperBound(1);
for (int iRow = 1; iRow < iRowMax; iRow++)
{
for(int iCol = 1; iCol < iColMax; iCol++)
{
data = rangeData[iRow, iCol] != null ? rangeData[iRow, iCol].ToString() : string.Empty;
if (i % 100 == 0)
{
Console.WriteLine(String.Format("Processed {0} cells.", i));
}
i++;
}
}
}
}
workbook.Close(false, missing, missing);
}
Console.WriteLine(string.Format("Took {0} seconds to parse file", (DateTime.Now - timer).Seconds.ToString()));
}
finally
{
excelApplication.Workbooks.Close();
excelApplication.Quit();
}
</code></pre>
<p><strong>Edit</strong>:</p>
<p>Worth stating that I want to use PIA and interop in order to access properties of excel workbooks that are not exposed by API's that work directly with the Excel file.</p>
|
<p>Excel PIA Interop is really slow when you are doing things cell by cell.</p>
<p>You should select the range you want to extract, like you did with the <code>Worksheet.UsedRange</code> property and then read the value of the whole range in one step, by invoking <code>get_Value()</code> (or just simply by reading the <code>Value</code> or <code>Value2</code> property, I can't remember which one) on it.</p>
<p>This will yield an <code>object[,]</code>, that is, a two dimensional array, which can be easily enumerated and is quick to be read.</p>
<p><strong>EDIT</strong>: I just read your actual code and realized that it actually does what I proposed. Shame on me for not reading the question properly before answering. In that case, you cannot make it much faster. Excel PIA Interop is slow. If you need a quicker solution you will have to either migrate jExcelApi from Java to C# (not a terribly hard thing to do) or use some commercial component. I suggest to avoid the OLEDB interface at all costs, in order to keep your sanity.</p>
<p>Unrelated, but helpful tip: You should use the ?? operator. It is really handy. Instead of</p>
<pre><code>data = rangeData[iRow, iCol] != null ? rangeData[iRow, iCol].ToString() : string.Empty;
</code></pre>
<p>you could just write</p>
<pre><code>data = Convert.ToString(rangeData[iRow, iCol]) ?? string.Empty;
</code></pre>
<p>In that case, even String.Empty is not necessary since <a href="http://msdn.microsoft.com/en-us/library/astxcyeh.aspx" rel="nofollow noreferrer">Convert.ToString(object)</a> converts <code>null</code> to an empty string anyway.</p>
|
<p>I think, this is the most efficient way, how do it with PIA.
Maybe will littlebit faster using "foreach" insted of "for", but it will not dramatic change.</p>
<p>If is efficiency your primary goal, you should work with excel files directly - without excel application.</p>
| 32,675
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.