input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
|---|---|
How can I change the animation style of a modal UIViewController? <p>I'm currently displaying a UIViewController like this:</p>
<pre><code>[[self navigationController] presentModalViewController:modalViewController animated:YES];
</code></pre>
<p>and hiding it like this:</p>
<pre><code>[self.navigationController dismissModalViewControllerAnimated:YES];
</code></pre>
<p>The animation is "slide up from the bottom"... then slide back down. How can I change the animation style? Can I made it fade in/out?</p>
<p>Cheers!</p>
|
<p>For iPhone 3.0+, a basic crossfade is easiest to do like this:</p>
<pre><code>modalViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[[self navigationController] presentModalViewController:modalViewController
animated:YES];
</code></pre>
|
How to solve Var out of scope within setTimeout call <p>I am trying to call a setTimeout from within a setInterval callback:</p>
<pre><code>function callback()
{
//assign myVar
var myVar = document.getElementById("givenID");
//...
//now wait 2 secs then call some code that uses myVAr
setTimeout("myVar.innerHTML = 'TEST'", 2000);
}
setInterval("callback();", 10000);
</code></pre>
<p>setInterval works as expected but setTimeout call is failing. I guess the problem is related to the fact that I am referencing a variable (myVar) that's not in scope.</p>
<p>What's the best way to solve this?</p>
|
<p>This is a perfect candidate for closures:</p>
<pre><code>setInterval(
function ()
{
var myVar = document.getElementById("givenID");
setTimeout(
function()
{
// myVar is available because the inner closure
// gets the outer closures scope
myVar.innerHTML = "Junk";
},2000);
}, 10000);
</code></pre>
<p>Your problem is scope related, and this would work around that.</p>
|
Does "std::size_t" make sense in C++? <p>In some code I've inherited, I see frequent use of <code>size_t</code> with the <code>std</code> namespace qualifier. For example:</p>
<pre><code>std::size_t n = sizeof( long );
</code></pre>
<p>It compiles and runs fine, of course. But it seems like bad practice to me (perhaps carried over from C?).</p>
<p>Isn't it true that <code>size_t</code> is built into C++ and therefore in the global namespace? Is a header file include needed to use <code>size_t</code> in C++?</p>
<p>Another way to ask this question is, would the following program (with <em>no</em> includes) be expected to <em>compile</em> on all C++ compilers?</p>
<pre><code>size_t foo()
{
return sizeof( long );
}
</code></pre>
|
<p>There seems to be confusion among the stackoverflow crowd concerning this</p>
<p><code>::size_t</code> is defined in the backward compatibility header <code>stddef.h</code> . It's been part of <code>ANSI/ISO C</code> and <code>ISO C++</code> since their very beginning. Every C++ implementation has to ship with <code>stddef.h</code> (compatibility) and <code>cstddef</code> where only the latter defines <code>std::size_t</code> and not necessarily <code>::size_t</code>. See Annex D of the C++ Standard.</p>
|
Redirect to controller (but with a different master) using a catchall wildcard <p>I have a problem whereby I want to display a view differently (a different master page), depending on where it came from, but don't know where to start...</p>
<p>I have several routes which catch various different types of urls that contain different structures.</p>
<p>In the code snippet below, I have a product route, and then I have a partner site route which could also go to a product page, but let's say that this partner is Pepsi, and they want their branding on the master page, rather than our own default styling. Lets say I go to <a href="http://mysite.com/products/cola.htm" rel="nofollow">products/cola.htm</a>. This should go to the same url as <a href="http://mysite.com/partners/pepsi/products/cola.htm" rel="nofollow">partners/pepsi/products/cola.htm</a>, and the PartnerRedirect would be able to handle the url based on the wildcard, by translating the url wildcard (in this case, "products/cola.htm") into a controller action, and forward the user on, (but simply change the master page in the view).</p>
<pre><code>routes.MapRoute(
"Product",
"products/{product}.htm",
new { controller = "Product", action = "ShowProduct" }
);
routes.MapRoute(
"ProductReview",
"products/{product}/reviews.htm",
new { controller = "Product", action = "ShowProductReview" }
);
routes.MapRoute(
"Partner",
"partners/{partner}/{*wildcard}",
new { controller = "Partners", action = "PartnerRedirect" }
);
</code></pre>
<p>Is this possible? And if so, how?</p>
<p>Many thanks in advance.</p>
|
<p>In your partners controller why don't you set a cookie that indicates which partner you want to show, and then redirects to the wildcard section of the route. That way you can show the same partner layout for all subsequent page views.</p>
<p>I don't know if this is what you're looking for, but it might be an option.</p>
|
Full-text search relevance is measured in? <p>I am making a quiz system, and when quizmakers insert questions into the Question Bank, I am to check the DB for duplicate / very highly similar questions.</p>
<p>Testing MySQL's <a href="http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html#function_match">MATCH() ... AGAINST()</a>, the highest relevance I get is 30+, when I test against a 100% similar string.</p>
<p>So what exactly is the relevance? To quote the <a href="http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html">manual</a>:</p>
<blockquote>
<p>Relevance values are non-negative floating-point numbers. Zero relevance means no similarity. Relevance is computed based on the number of words in the row, the number of unique words in that row, the total number of words in the collection, and the number of documents (rows) that contain a particular word. </p>
</blockquote>
<p>My problem is how to test the relevance value if a string is a duplicate. If it's 100% duplicate, prevent it from being inserter into Question Bank. But if it is only so similar, prompt the quizmaker to verify, insert or not. So how do I do that? 30+ for 100% identical string is not percentage, so I'm stump.</p>
<p>Thanks in advance.</p>
|
<p>The basic data structure for a text retrieval system is an <a href="http://en.wikipedia.org/wiki/Inverted_index" rel="nofollow">Inverted Index</a>. This is essentially a list of words found in the document collection with a list of the documents they occur in. It can also have metadata about the occurrence for each document, such as the number of times the word appears.</p>
<p>Documents containing the words can be queried by matching on the search terms. To determine relevance, a heuristic known as a <a href="http://www.stanford.edu/class/cs276a/handouts/lecture7.ppt" rel="nofollow">Cosine Ranking</a> is calculated on the hits. This works by constructing n-dimensional vector with one component for each of the n search terms. You can also weight the search terms if desired. This vector gives a point in n-dimensional space that corresponds to your search terms.</p>
<p>A similar vector based on the weighted occurrences in each document can be constructed from the inverted index with each axis in the vector corresponding with the axis for each search term. If you calculate a dot product of these vectors you get the cosine of the angle between them. 1.0 is equivalent to cos (0), which would assume the vectors occupy a common line from the origin. The closer the vectors together, the smaller the angle and the closer the cosine is to 1.0.</p>
<p>If you sort the search results by the cosine (or bung them into a priority queue as <a href="http://www.nzdl.org/html/mg.html" rel="nofollow">mg</a> does) you get the most relevant. Cleverer relevance algorithms tend to fiddle with the weights of the search terms, skewing the dot product in favour of terms with high relevance.</p>
<p>If you want to dig a little, <a href="http://rads.stackoverflow.com/amzn/click/1558605703" rel="nofollow">Managing Gigabytes</a> by <a href="http://www.cosc.canterbury.ac.nz/tim.bell/" rel="nofollow">Bell</a> and <a href="http://www.cs.mu.oz.au/~alistair/" rel="nofollow">Moffet</a> discusses the internal architecture of text retrieval systems.</p>
|
How do I do inline assembly on the IPhone? <p>How is it done? What steps do I need to take and what pitfalls and gotchas are there to consider?</p>
|
<p>I've gotten this to work, thanks to some inside help over at the <a href="https://devforums.apple.com/">Apple Devforums</a>, you should sign up if you're a dedicated IPhone developer.</p>
<p>First thing's first, it's <em>__asm__()</em>, not plain <em>asm()</em>.</p>
<p>Secondly, by default, XCode generates a compilation target that compiles inline assembly against the ARM Thumb instruction set, so <em>usat</em> wasn't recognized as a proper instruction. To fix this, do "Get Info" on the Target. Scroll down to the section "GCC 4.0 - Code Generation" and uncheck "Compile for Thumb". Then this following snippet will compile just fine if you set the Active SDK to "Device"</p>
<pre><code>inline int asm_saturate_to_255 (int a) {
int y;
__asm__("usat %0, #8, %1\n\t" : "=r"(y) : "r"(a));
return y;
}
</code></pre>
<p>Naturally, now it won't work with the IPhone Simulator. But <em>TargetConditionals.h</em> has defines you can #ifdef against. Namely *TARGET_OS_IPHONE* and *TARGET_IPHONE_SIMULATOR*.</p>
|
Using SQL Server 2008 Geography types with nHibernate's CreateSQLQuery <p>I am trying to issue a SQL update statement with nHibernate (2.0.1GA) like this:</p>
<pre><code>sqlstring = string.Format("set nocount on;update myusers set geo=geography::Point({0}, {1}, 4326) where userid={2};", mlat, mlong, userid);
_session.CreateSQLQuery(sqlstring).ExecuteUpdate();
</code></pre>
<p>However I receive the following error: 'geography@p0' is not a recognized built-in function name.</p>
<p>I thought CreateSQLQuery would just pass the SQL I gave it and execute it...guess not. Any ideas on how I can do that within the context of nHibernate?</p>
|
<p>I'm pretty sure I can tell you what is happening, but I don't know if there is a fix for it.</p>
<p>I think the problem is that the ':' character is used by NHibernate to create a named parameter. Your expression is getting changed to:</p>
<pre><code>set nocount on;update myusers set geo=geography@p0({0}, {1}, 4326) where userid={2};
</code></pre>
<p>And @p0 is going to be a SQL variable. Unfortunately I can't find any documentation for escaping colons so they are not treated as a named parameter.</p>
<p>If an escape character exists (my quick skim of the NHibernate source didn't find one; Named parameters are handled in NHibernate.Engine.Query.ParameterParser if you want to spend a little more time searching), then you could use that.</p>
<p>Other solutions:</p>
<ul>
<li>Add an escape character to the source. You can then use a modified version of NHibernate. If you do this, you should submit your patch to the team so it can be included in the real thing and you don't have to maintain a modified version of the source (no fun).</li>
<li>Create a user defined function in your DB that returns a geography::Point, then call your function instead of the standard SQL function. This seems like the quickest/easiest way to get up and running, but also feels a bit like a band-aid.</li>
<li>See if there is something in <a href="http://nhforge.org/wikis/spatial/default.aspx" rel="nofollow">NHibernate Spatial</a> that will let you programmatically add the geography::Point() [or edit the code for that project to add one and submit the patch to that team].</li>
</ul>
|
Anonymous Types in a signature <p>I am trying to get the signature on the method below to work. As this is an Anonymous Type I have some trouble, any help would be great.</p>
<p>When I looked at sortedGameList.ToList() in a QuickWatch window I get the signature </p>
<pre><code>System.Collections.Generic.List<<>f__AnonymousType0<System.DateTime,System.Linq.IGrouping<System.DateTime,DC.FootballLeague.Web.Models.Game>>>
</code></pre>
<p>Many Thanks</p>
<p>Donald</p>
<pre><code> public List<IGrouping<DateTime, Game>> getGamesList(int leagueID)
{
var sortedGameList =
from g in Games
group g by g.Date into s
select new { Date = s.Key, Games = s };
return sortedGameList.ToList();
}
</code></pre>
|
<p><strike> select new { Date = s.Key, Games = s.ToList() }; </strike></p>
<p>Edit: thats wrong! I think this will do.</p>
<pre><code>public List<IGrouping<DateTime, Game>> getGamesList(int leagueID)
{
var sortedGameList =
from g in Games
group g by g.Date;
return sortedGameList.ToList();
}
</code></pre>
<p>And no, you do not need the select!</p>
|
How to calculate the bounding box for a given lat/lng location? <p>I have given a location defined by latitude and longitude.
Now i want to calculate a bounding box within e.g. 10 kilometers of that point.</p>
<p>The bounding box should be defined as latmin, lngmin and latmax, lngmax.</p>
<p>I need this stuff in order to use the <a href="http://www.panoramio.com/api/" rel="nofollow">panoramio API</a>.</p>
<p>Does someone know the formula of how to get thos points?</p>
<p><strong>Edit:</strong> Guys i am looking for a formula/function which takes lat & lng as input and returns a bounding box as latmin & lngmin and latmax & latmin.
Mysql, php, c#, javascript is fine but also pseudocode should be okay.</p>
<p><strong>Edit:</strong> I am not looking for a solution which shows me the distance of 2 points</p>
|
<p>I suggest to approximate locally the Earth surface as a sphere with radius given by the WGS84 ellipsoid at the given latitude. I suspect that the exact computation of latMin and latMax would require elliptic functions and would not yield an appreciable increase in accuracy (WGS84 is itself an approximation).</p>
<p>My implementation follows (It's written in Python; I have not tested it):</p>
<pre class="lang-py prettyprint-override"><code># degrees to radians
def deg2rad(degrees):
return math.pi*degrees/180.0
# radians to degrees
def rad2deg(radians):
return 180.0*radians/math.pi
# Semi-axes of WGS-84 geoidal reference
WGS84_a = 6378137.0 # Major semiaxis [m]
WGS84_b = 6356752.3 # Minor semiaxis [m]
# Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]
def WGS84EarthRadius(lat):
# http://en.wikipedia.org/wiki/Earth_radius
An = WGS84_a*WGS84_a * math.cos(lat)
Bn = WGS84_b*WGS84_b * math.sin(lat)
Ad = WGS84_a * math.cos(lat)
Bd = WGS84_b * math.sin(lat)
return math.sqrt( (An*An + Bn*Bn)/(Ad*Ad + Bd*Bd) )
# Bounding box surrounding the point at given coordinates,
# assuming local approximation of Earth surface as a sphere
# of radius given by WGS84
def boundingBox(latitudeInDegrees, longitudeInDegrees, halfSideInKm):
lat = deg2rad(latitudeInDegrees)
lon = deg2rad(longitudeInDegrees)
halfSide = 1000*halfSideInKm
# Radius of Earth at given latitude
radius = WGS84EarthRadius(lat)
# Radius of the parallel at given latitude
pradius = radius*math.cos(lat)
latMin = lat - halfSide/radius
latMax = lat + halfSide/radius
lonMin = lon - halfSide/pradius
lonMax = lon + halfSide/pradius
return (rad2deg(latMin), rad2deg(lonMin), rad2deg(latMax), rad2deg(lonMax))
</code></pre>
<p>EDIT: The following code converts (degrees, primes, seconds) to degrees + fractions of a degree, and vice versa (not tested):</p>
<pre class="lang-py prettyprint-override"><code>def dps2deg(degrees, primes, seconds):
return degrees + primes/60.0 + seconds/3600.0
def deg2dps(degrees):
intdeg = math.floor(degrees)
primes = (degrees - intdeg)*60.0
intpri = math.floor(primes)
seconds = (primes - intpri)*60.0
intsec = round(seconds)
return (int(intdeg), int(intpri), int(intsec))
</code></pre>
|
Algorithm/pattern for selecting sub-collections using LINQ and C# <p>I have a C# collection of strings. Each string is a sentence that can appear on a page. I also have a collection of page breaks which is a collection of int's. representing the index where the collection of strings are split to a new page.</p>
<p>Example: Each 10 items in the string collection is a page so the collection of page breaks would be a collection of int's with the values of 10, 20, 30. ...</p>
<p>So if there are 2 pages of strings then there will be 1 item in the page break collection and if there is 1 page then the page break collection would have zero items.</p>
<p>I am trying to create the following function:</p>
<pre><code>List<string> GetPage(List<string> docList, List<int> pageBreakList, int pageNum)
{
// This function returns a subset of docList - just the page requested
}
</code></pre>
<p>I've taken a few stabs at writing this function and keep on coming up with complex if and switch statements to take into account single and two page documents and page numbers being requested outside the range (e.g. last page should be returned if page number is greater than number of pages and first page if page number is 0 or less).</p>
<p>My struggle with this problem leads me to ask the question: Is there a well known pattern or algorithm to address this type of subset query?</p>
|
<p>Not sure what the list of page breaks is for. I would think of it this way. A collection of strings, a page number, and the size of the page. Then you could do something like:</p>
<pre><code>List<string> strings = ...
int pageNum = ...
int pageSze = ...
if (pageNum < 1) pageNum = 1;
if (pageSize < 1) pageSize = 1;
List<string> pageOfStrings = strings.Skip( pageSize*(pageNum-1) ).Take( pageSize ).ToList();
</code></pre>
<p>In the case where the number of pages vary per page as per your comment, try something like below. You may need to adjust the edge condition checking...</p>
<pre><code>List<string> strings = ...
List<int> sizes = ...
int pageNum = ...
int itemsToSkip = 0;
int itemsToTake = 1;
if (pageNum > 1)
{
sizes.Take( pageNum - 2).Sum();
if (pageNum <= sizes.Count)
{
itemsToTake = sizes[pageNum-1]
}
{
List<string> pageOfStrings = strings.Skip( itemsToSkip ).Take( itemsToTake );
</code></pre>
|
Updating referenced columns in Postgres <p>When there are one of more columns that reference another, I'm struggling for the best way to update that column while maintaining referential integrity. For example, if I have a table of labels and descriptions and two entries:</p>
<pre><code>Label | Description
------------------------------------
read | This item has been read
READ | You read this thing already
</code></pre>
<p>Now, I don't want these duplicates. I want to add a constraint to the column that doesn't allow values that are case-insensitively duplicates, as in the example. However, I have several rows of several other tables referencing 'READ', the one I want to drop.</p>
<p>I know Postgres knows which fields of other rows are referencing this, because I can't delete it as long as they are there. So, how could I get any field referencing this to update to 'read'? This is just an example, and I actually have a few places I want to do this. Another example is actually an int primary key for a few tables, where I want to add a new table as a sort of 'base table' that the existing ones extend and so they'll all need to have unique IDs now, which means updating the ones they have.</p>
<p>I am open to recipes for functions I can add to do this, tools I can utilize, or anything else.</p>
|
<p>If you have many rows referencing READ, you could alter the foreign key to be on cascade update, update that table set Label = 'read' where Label = 'READ' and everything will get automagically fixed. After that you can alter the constraint again to be as it was before.</p>
<p>To find all the tables referencing the column, you can use</p>
<pre><code>select TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME from
INFORMATION_SCHEMA.KEY_COLUMN_USAGE where
REFERENCED_TABLE_NAME = '<table>' AND REFERENCED_COLUMN_NAME = '<column>'
</code></pre>
|
How do I pass multiple objects to ViewPage in ASP.NET MVC? <p>I think I know the answer, but I would like to bounce around some ideas.</p>
<p>I would like to pass several (in this instance 2) somewhat different pieces of data to a View. My initial thought is simply to wrap-up the various objects into a containing object and pass them along that way. Then from the View, I'd have something like </p>
<pre><code>var objContainer = ViewData.Model;
var thisObject = objContainer.ThisObject;
var thatObject = objContainer.ThatObject;
</code></pre>
<p>and these could be used independently in the Master Page and View Page.</p>
<p>Is that the "best" way?</p>
|
<p>I find it useful to create additional classes dedicated that are to be presented to the Views. I keep them in a separate namespace called 'Core.Presentation' to keep things organized. Here is an example:</p>
<pre><code>namespace Core.Presentation
{
public class SearchPresentation
{
public IList<StateProvince> StateProvinces { get; set; }
public IList<Country> Countries { get; set; }
public IList<Gender> Genders { get; set; }
public IList<AgeRange> AgeRanges { get; set; }
}
}
</code></pre>
<p>Then I make sure that my View is a strongly typed view that uses the generic version of that presentation class:</p>
<pre><code>public partial class Search : ViewPage<SearchPresentation>
</code></pre>
<p>That way in the View, I can use Intellisense and easily navigate through the items.</p>
|
ASP.NET MVC Beta 1: DefaultModelBinder wrongly persists parameter and validation state between unrelated requests <p>When I use the default model binding to bind form parameters to a complex object which is a parameter to an action, the framework remembers the values passed to the first request, meaning that any subsequent request to that action gets the same data as the first. The parameter values and validation state are persisted between unrelated web requests.</p>
<p>Here is my controller code (<code>service</code> represents access to the back end of the app):</p>
<pre><code> [AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create()
{
return View(RunTime.Default);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(RunTime newRunTime)
{
if (ModelState.IsValid)
{
service.CreateNewRun(newRunTime);
TempData["Message"] = "New run created";
return RedirectToAction("index");
}
return View(newRunTime);
}
</code></pre>
<p>My .aspx view (strongly typed as <code>ViewPage<RunTime</code>>) contains directives like: </p>
<pre><code><%= Html.TextBox("newRunTime.Time", ViewData.Model.Time) %>
</code></pre>
<p>This uses the <code>DefaultModelBinder</code> class, which is <a href="http://weblogs.asp.net/scottgu/archive/2008/10/16/asp-net-mvc-beta-released.aspx#three" rel="nofollow">meant to autobind my model's properties</a>.</p>
<p>I hit the page, enter valid data (e.g. time = 1). The app correctly saves the new object with time = 1. I then hit it again, enter different valid data (e.g. time = 2). However the data that gets saved is the original (e.g. time = 1). This also affects validation, so if my original data was invalid, then all data I enter in the future is considered invalid. Restarting IIS or rebuilding my code flushes the persisted state.</p>
<p>I can fix the problem by writing my own hard-coded model binder, a basic naive example of which is shown below. </p>
<pre><code> [AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([ModelBinder(typeof (RunTimeBinder))] RunTime newRunTime)
{
if (ModelState.IsValid)
{
service.CreateNewRun(newRunTime);
TempData["Message"] = "New run created";
return RedirectToAction("index");
}
return View(newRunTime);
}
internal class RunTimeBinder : DefaultModelBinder
{
public override ModelBinderResult BindModel(ModelBindingContext bindingContext)
{
// Without this line, failed validation state persists between requests
bindingContext.ModelState.Clear();
double time = 0;
try
{
time = Convert.ToDouble(bindingContext.HttpContext.Request[bindingContext.ModelName + ".Time"]);
}
catch (FormatException)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName + ".Time", bindingContext.HttpContext.Request[bindingContext.ModelName + ".Time"] + "is not a valid number");
}
var model = new RunTime(time);
return new ModelBinderResult(model);
}
}
</code></pre>
<p>Am I missing something? I don't think it's a browser session problem as I can reproduce the problem if the first data is entered in one browser and the second in another.</p>
|
<p>It turns out that the problem was that my controllers were being reused between calls. One of the details I chose to omit from my original post is that I am using the Castle.Windsor container to create my controllers. I had failed to mark my controller with the Transient lifestyle, so I was getting the same instance back on each request. Thus the context being used by the binder was being re-used and of course it contained stale data. </p>
<p>I discovered the problem while carefully analysing the difference between Eilon's code and mine, eliminating all other possibilities. As the <a href="http://www.castleproject.org/monorail/documentation/trunk/integration/windsor.html">Castle documentation says</a>, this is a "terrible mistake"! Let this be a warning to others!</p>
<p>Thanks for your response Eilon - sorry to take up your time.</p>
|
StackOverflowException caused by a linq query <p><strong>edit #2:</strong> Question solved halfways. Look below</p>
<p>As a follow-up question, does anyone know of a non-intrusive way to solve what i'm trying to do below (namely, linking objects to each other without triggering infinite loops)?</p>
<p><hr /></p>
<p>I try to create a asp.net-mvc web application, and get a StackOverFlowException. A controller triggers the following command:</p>
<pre><code> public ActionResult ShowCountry(int id)
{
Country country = _gameService.GetCountry(id);
return View(country);
}
</code></pre>
<p>The GameService handles it like this (WithCountryId is an extension):</p>
<pre><code> public Country GetCountry(int id)
{
return _gameRepository.GetCountries().WithCountryId(id).SingleOrDefault();
}
</code></pre>
<p>The GameRepository handles it like this:</p>
<pre><code> public IQueryable<Country> GetCountries()
{
var countries = from c in _db.Countries
select new Country
{
Id = c.Id,
Name = c.Name,
ShortDescription = c.ShortDescription,
FlagImage = c.FlagImage,
Game = GetGames().Where(g => g.Id == c.GameId).SingleOrDefault(),
SubRegion = GetSubRegions().Where(sr => sr.Id == c.SubRegionId).SingleOrDefault(),
};
return countries;
}
</code></pre>
<p>The GetGames() method causes the StackOverflowException:</p>
<pre><code> public IQueryable<Game> GetGames()
{
var games = from g in _db.Games
select new Game
{
Id = g.Id,
Name = g.Name
};
return games;
}
</code></pre>
<p>My Business objects are different from the linq2sql classes, that's why I fill them with a select new.</p>
<p>An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll</p>
<p><hr /></p>
<p><strong>edit #1:</strong> I have found the culprit, it's the following method, it triggers the GetCountries() method which in return triggers the GetSubRegions() again, ad nauseam:</p>
<pre><code> public IQueryable<SubRegion> GetSubRegions()
{
return from sr in _db.SubRegions
select new SubRegion
{
Id = sr.Id,
Name = sr.Name,
ShortDescription = sr.ShortDescription,
Game = GetGames().Where(g => g.Id == sr.GameId).SingleOrDefault(),
Region = GetRegions().Where(r => r.Id == sr.RegionId).SingleOrDefault(),
Countries = new LazyList<Country>(GetCountries().Where(c => c.SubRegion.Id == sr.Id))
};
}
</code></pre>
<p>Might have to think of something else here :) That's what happens when you think in an OO mindset because of too much coffee</p>
|
<p>Hai! I think your models are recursively calling a method unintentionally, which results in the stack overflow. Like, for instance, your Subregion object is trying to get Country objects, which in turn have to get Subregions. </p>
<p>Anyhow, it always helps to check the stack in a StackOverflow exception. If you see a property being accessed over and over, its most likely because you're doing something like this:</p>
<p>public object MyProperty { set { MyProperty = value; }}</p>
<p>Its easier to spot situations like yours, where method A calls method B which calls method A, because you can see the same methods showing up two or more times in the call stack.</p>
|
How can I support wildcards in user-defined search strings in Python? <p>Is there a simple way to support wildcards ("*") when searching strings - without using RegEx?</p>
<p>Users are supposed to enter search terms using wildcards, but should not have to deal with the complexity of RegEx:</p>
<pre><code>"foo*" => str.startswith("foo")
"*foo" => str.endswith("foo")
"*foo*" => "foo" in str
</code></pre>
<p>(it gets more complicated when there are multiple search terms though, e.g. "foo*bar*baz")</p>
<p>This seems like a common issue, so I wonder whether there's a ready-made solution for it.</p>
<p>Any help would be greatly appreciated!</p>
|
<p>You could try the <a href="http://www.python.org/doc/2.5.2/lib/module-fnmatch.html"><code>fnmatch</code></a> module, it's got a shell-like wildcard syntax.</p>
|
How do I associate a nib (.xib) file with a UIView? <p>I have a subclass "s" of UIView. I want to put some buttons and labels on s. How do I associate my UIView subclass with a nib file?</p>
|
<ol>
<li>In Interface Builder, create a new
xib with the View template. </li>
<li>Click on the view in the list of
objects in the xib (you should also
see "File's Owner and "First
Responder").</li>
<li>Push Cmd-4 to open the Identity pane
of the inspector.</li>
<li>Type your class's name into the
"Class Name" field and push return.</li>
</ol>
<p>You should be able the drag buttons in. To get at the nib from code, use <code>-[NSBundle loadNibNamed:owner:options:]</code>. Your view should be the first object in the returned array.</p>
|
VB.NET How Do I skin a vb.net app <p>I want to skin a vb.net app I made ive googled some stuff and I've seen skinned vb.net apps. </p>
<p>However it seems like any time i try to find someone explaining it its a link to a pay for product.</p>
<p>Does anyone have anything useful on this?</p>
<hr>
<p>I have seen some free ways to do this programatically I cannot seem to make it translate entirely over to my own unique program.</p>
|
<p>I remember making a "skinnable" vb.net winforms app (a media player) when I was still a student (maybe 6 years ago).</p>
<p>It was ugly, but the way I did it was as follows:</p>
<ol>
<li><p>Select a transparency color. Wherever you use this color the app will be transparent (I used Fuchsia (#FF00FF), which I recall being a standard for video games back in the day.</p></li>
<li><p>Use a naming convention for child controls (particular buttons, sliders, etc).</p></li>
<li><p>Create images for the controls in step 2.</p></li>
<li><p>Set 1 pixel wide color coated place holders for those controls. Eg a blue pixel was my play button, a green pixel was my pause button, etc. The placeholder marked the upper left corner of the control.</p></li>
<li><p>At runtime dynamically generate the controls (really images with onclick events) and place them on top of the place holders.</p></li>
</ol>
<p>I'm sure there is a nicer way to do this, but that was my crude approach.</p>
|
Difference of two 'uint' <p>When you attempt to declare an unsigned variable in C#.NET with a value outside its value range it is flagged as a compiler error, but if you produce a negative value at runtime and assign it to that variable at runtime the value wraps.</p>
<pre><code>uint z = -1; // Will not compile
uint a = 5;
uint b = 6;
uint c = a - b; // Will result in uint.MaxValue
</code></pre>
<p>Is there a good reason why unsigned variables wrap in such a situation instead of throwing an exception?</p>
<p>Thanks.</p>
|
<p>Declaring an unassigned variable in C# isn't flagged with an error - trying to assign an invalid value to a variable is. For instance, here's a variable which isn't definitely assigned (assuming it's local) after declaration:</p>
<pre><code>uint z;
</code></pre>
<p>-1 isn't a valid value for a uint any more than 0.5 is, which is why your example wouldn't compile.</p>
<p>Now, as for the rest: integers types just wrap on overflow - just as adding 1 to <code>int.MaxValue</code> returns <code>int.MinValue</code>. This is a significant performance improvement over having the program check each operation for overflow - at the cost of potentially not spotting an error.</p>
<p>That's only if you're in an unchecked context, mind you - if you perform any of these operations in a checked context, you'll get an exception instead. For instance;</p>
<pre><code>class Test
{
static void Main()
{
checked
{
uint a = 5;
uint b = 6;
uint c = a - b;
}
}
}
</code></pre>
<p>Run that and you'll see an <code>OverflowException</code> get thrown. If that's what you want for your whole project, you can set it in the project properties (or compile with the <code>/checked+</code> command line option to <code>csc</code>.)</p>
<p>EDIT: It's worth noting that the other answers have shown that you could put smaller amounts of code in the checked context - just the declaration and assignment of <code>c</code> or even just the calculation. It's all pretty flexible.</p>
|
What design pattern to use for User Authentication in Java <p>There are certain common components that are used across projects:</p>
<ol>
<li>User Authentication and Authorization</li>
<li>Exception Handling</li>
<li>Logging</li>
<li>E-mail</li>
<li>DataBase Access</li>
<li>Caching etc</li>
</ol>
<p>Is there a consistent design pattern that can be used for each of these common modules? By the way, the framework can vary like JAAS/JNDI for User Authentication and Authorization, log4j/java logging for logging, JavaMail for E-mai, JDBC/Hibernate for DataBase access. </p>
<p>For example there is DAO for database access. Is there any good design pattern that can be used for User Authentication and Authorization no matter what framework is used(JAAS/JNDI/SSO)?</p>
|
<p>Perhaps not a pattern per se, but I've always thought that the spring annotations approach was quite clever. Essentially you annotate the methods that need to be secured. Providing that you have a nice tiered architecture then this should make things pretty straightforward! It does all of the hard work for you. <a href="http://www.acegisecurity.org/" rel="nofollow" title="Acegi web site">Check it out here</a>. The <a href="http://www.acegisecurity.org/faq.html" rel="nofollow" title="FAQ">FAQ is pretty good</a>. </p>
<p>I've only used this in really elementary stuff as part of my spring training with Rod Johnson.</p>
|
Visio & UML - Showing pointers in attributes and return values <p>I have the requirement of generating UML Diagrams for one of my C++ assignments. I'm using Visio 2007 and I'm having trouble representing C++ pointers. I've found a way to add a suffix to Datatypes however it's rather time consuming to do this for every pointer used or returned in my program. </p>
<p>Basically I'm trying to get <code>-object1 : Object* = NULL</code> and <code>+Object() : Object*</code> without digging into the properties and adding <code>*</code> to the suffix field every time. </p>
<p>I'm pretty much stuck with Microsoft software for making diagrams and coding so please don't suggest I use different software. However, if Visual Studio 2003 supports making UML Diagrams in a less painful way than Visio, I wouldn't object to using Visual Studio but please tell me where that option is.</p>
|
<p>You can have Visio save its data files to an XML format. You could then write a script to make the * tweaks wherever you want them. Depending on how big your model is, this may be faster than the tedious manual way that you're using now, especially if you already have some experience in a language like Perl.</p>
|
Problem with updating a MySQL field with PHP <p>I have a query:</p>
<p>UPDATE choices SET votes = votes + 1 WHERE choice_id = '$user_choice'</p>
<p>But when I execute it in my script, the votes field is updated twice, so the votes will go from 4 to 6 instead to 5. It doesn't seem that it is getting called twice because I echo out stuff to test this and only get one echo. Is there a way to have it so PHP will only execute this query once per page "refresh"?</p>
<p><strong>EDIT</strong>: Thanks for the responses, I'm using regular MySQL, no MySQLi or PDO. Another thing I found is that when doing the query, it works when you start out with 0 and update to 1, but then after that it goes 3, 5, 7, ...</p>
|
<p>One other option is, if you are using firefox at all and have firbug installed you need to disable your cache. For some reason firbug results in two calls to the dB. Took weeks to figure this out where I work as QA was getting all kinds of strange results when testing. he was the only one with firebug.</p>
|
Best Way to Replace a Visual Component in Delphi <p>In a Delphi Form, I would like to replace one visual component with another. Example: I want to replace a Panel component with an ElPanel from a 3rd party package. </p>
<p>I would like all identical properties and events of the first component to be transferred to the new one, and all the components that belong to the first component (e.g. Toolbars, memos,status bars, etc.) to end up placed on the new component exactly where they were on the first one.</p>
<p>Is there a best/easiest way to do this other than adding the new component to the form and meticulously transferring every property, event and component to it one-by-one?</p>
|
<p>I do it as following:</p>
<ol>
<li>Right click on the form and choose (View as Text).</li>
<li>Press Ctrl + F to search for the Component class name like TPanel and replace it with TElPanel</li>
<li>Switch back to back to the form (View as form)</li>
<li>In the interface section replace the TPanel with TElPanel.</li>
</ol>
<p>if you have many components using GExperts will be more feasible solutions.</p>
|
How do I calculate the elapsed time of an event in java? <p>What's a simple/easy way to access the system clock using Java, so that I can calculate the elapsed time of an event?</p>
|
<p>I would avoid using System.currentTimeMillis() for measuring elapsed time. currentTimeMillis() returns the 'wall-clock' time, which may change (eg: daylight savings, admin user changing the clock) and skew your interval measurements. </p>
<p>System.nanoTime(), on the other hand, returns the number of nanoseconds since 'some reference point' (eg, JVM start up), and would therefore not be susceptible to system clock changes.</p>
|
How to change the name of an iOS app? <p>I began an iPhone project the other day with a silly development code name, and now I want to change the name of the project since it's nearly finished. </p>
<p>But I'm not sure how to do this with Xcode, trying the obvious of changing the application's name in the info.plist file, causes the signing process to go wrong (I think...) and my app won't launch giving me a Launcher error.</p>
<p>I guess I could make a new project and copy paste everything over, but it seems so primitive that I'm hoping for a more civilized solution.</p>
|
<ol>
<li>Go to <code>Targets</code> in <code>Xcode</code></li>
<li>"<code>Get Info</code>" on your project's target (your current silly development name)</li>
<li>Search for "<code>Product Name</code>" under "<code>Packaging</code>". Change the value of what you want the <code>new program name</code> to be.</li>
</ol>
|
How can I call a DLL from a scripting language? <p>I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth).</p>
<p>I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found.</p>
<p>We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code.</p>
<p>What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution.</p>
|
<p>One way to call C libraries from Python is to use <a href="https://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a>:</p>
<pre><code>>>> from ctypes import *
>>> windll.user32.MessageBoxA(None, "Hello world", "ctypes", 0);
</code></pre>
|
Sync Framework Resources <p>I am looking for resources on Microsoft Sync Framework. Although MSDN and Google Search gave me the brief overview, I want some demos and presentations.</p>
<p>Also, is Live Mesh based on Sync Framework?</p>
|
<p>Maybe those links will be helpful:</p>
<ul>
<li><a href="http://code.msdn.microsoft.com/sync/Release/ProjectReleases.aspx?ReleaseId=615">Sync101 - Getting Started with Sync</a></li>
<li><a href="http://code.msdn.microsoft.com/sync/Release/ProjectReleases.aspx?ReleaseId=949">Tutorial - Microsoft Sync Framework Basics</a></li>
<li>S<a href="http://code.msdn.microsoft.com/sync/Release/ProjectReleases.aspx?ReleaseId=1200">QL Express - Client Synchronization Sample</a></li>
<li><a href="http://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=sync&ReleaseId=1344">Sync Services for ADO.NET v2 - Download Only Sync</a></li>
<li><a href="http://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=sync&ReleaseId=1343">Sync Services for ADO.NET Adapter Builder</a></li>
</ul>
|
Setting a thread priority in a service has no effect <p>Is there some additional configuration needed before I can set thread priorities in a Windows service? </p>
<p>In my service, I have a few threads that each call the <code>CreateProcess()</code> function to launch an external application. I would like to adjust thread (or process) priorities to <code>normal</code> or <code>lower</code>, depending on some other factors.</p>
<p>The problem is that <code>SetThreadPriority()</code> function fails with an error 6 (invalid handle?). I'm passing in a handle obtained from <code>PROCESS_INFORMATION::hThread</code> (after calling the <code>CreateProcess()</code> of course), so I think that the handle <em>should</em> be valid.</p>
<p>I've also tried setting the priority on the processes using the <code>SetPriorityClass()</code> function, which also fails.</p>
<p>The service is logged on as a local user.</p>
|
<p>Maybe you don't have the correct access rights? <a href="http://msdn.microsoft.com/en-us/library/ms686277(VS.85).aspx" rel="nofollow">MSDN on SetThreadPriority</a> says:</p>
<blockquote>
<p>hThread [in] A handle to the thread
whose priority value is to be set.</p>
<p>The handle must have the
THREAD_SET_INFORMATION or
THREAD_SET_LIMITED_INFORMATION access
right. For more information, see
Thread Security and Access Rights.</p>
<p>Windows Server 2003 and Windows
XP/2000: The handle must have the
THREAD_SET_INFORMATION access right.</p>
</blockquote>
|
Which is the best alternative for Java Serialization? <p>I'm currently working on a project which needs to persist any kind of object (of which implementation we don't have any control) so these objects could be recovered afterwards. </p>
<p>We can't implement an ORM because we can't restrict the users of our library at development time.</p>
<p>Our first alternative was to serialize it with the Java default serialization but we had a lot of trouble recovering the objects when the users started to pass different versions of the same object (attributes changed types, names, ...).</p>
<p>We have tried with the XMLEncoder class (transforms an object into a XML), but we have found that there is a lack of functionality (doesn't support Enums for example). </p>
<p>Finally, we also tried JAXB but this impose our users to annotate their classes.</p>
<p>Any good alternative?</p>
|
<p>It's 2011, and in a commercial grade REST web services project we use the following serializers to offer clients a variety of media types:</p>
<ul>
<li><a href="http://x-stream.github.io/" rel="nofollow">XStream</a> (for XML but not for JSON)</li>
<li><a href="https://github.com/FasterXML/jackson" rel="nofollow">Jackson</a> (for JSON)</li>
<li><a href="https://github.com/EsotericSoftware/kryo" rel="nofollow">Kryo</a> (a fast, compact binary serialization format)</li>
<li><a href="https://github.com/FasterXML/jackson-dataformat-smile" rel="nofollow">Smile</a> (a binary format that comes with Jackson 1.6 and later).</li>
<li>Java Object Serialization.</li>
</ul>
<p>We experimented with other serializers recently:</p>
<ul>
<li><a href="http://simple.sourceforge.net/" rel="nofollow">SimpleXML</a> seems solid, runs at 2x the speed of XStream, but requires a bit too much configuration for our situation.</li>
<li><a href="http://code.google.com/p/yamlbeans/" rel="nofollow">YamlBeans</a> had a couple of bugs.</li>
<li><a href="http://code.google.com/p/snakeyaml/" rel="nofollow">SnakeYAML</a> had a minor bug relating to dates.</li>
</ul>
<p>Jackson JSON, Kryo, and Jackson Smile were all significantly faster than good old Java Object Serialization, by about 3x to 4.5x. XStream is on the slow side. But these are all solid choices at this point. We'll keep monitoring the other three.</p>
|
Convert html to pdf with linked documents inline <p>I need to convert a bundle of static HTML documents into a single PDF file programmatically on the server side on a Java/J2EE platform using a batch process preferably. The pdf files would be distributed to site users for offline browsing of the web pages. </p>
<p>The major points of the requirements are:</p>
<ol>
<li>The banner at the top should not be present in the final pdf document.</li>
<li>The navigation bar on the left should be transformed into pdf bookmarks from html hyperlinks.</li>
<li>All hyperlinked contents (html/pdf/doc/docx etc.) present in the web pages should be part of the final pdf document with pdf bookmarks.</li>
</ol>
<p>Is there any standard open source way of doing this?</p>
|
<p>Try <a href="http://xmlgraphics.apache.org/fop/" rel="nofollow">Apache FOP</a>. I just used it to <a href="http://stackoverflow.com/questions/212577/how-do-you-create-a-pdf-from-xml-in-java">convert XML to PDF</a> and I think you can do the same with HTML/DOM. The website has <a href="http://xmlgraphics.apache.org/fop/0.95/embedding.html" rel="nofollow">a whole section</a> on running FOP in a Java application and there's <a href="http://xmlgraphics.apache.org/fop/0.95/embedding.html#ExampleDOM2PDF" rel="nofollow">example code for DOM to PDF</a>.</p>
|
Interesting Master's degree programs? <p>I'm applying for a masters in fall of next year and was wondering if anyone had suggestions for interesting/challenging master's degrees in CS. I think that even though picking the right university is important, it is even more important to pick a master's degree where you'll find talented/creative people to interact and learn from.</p>
<p>background: never taken AI, discrete math, compilers, operating systems, data structures, cryptography or anything involving c/c++ courses</p>
<p>looking for: hci research & applications, the future of mobile tech & social interaction, something tangible and not abstract, somewhere where I can take a minor in music/art/design</p>
<p>inspiration: randy pausch, johnny lee, blaise aguera, jeff han, 42entertainment, and jonathan harris (ted.com)</p>
|
<blockquote>
<p>background: never taken AI, discrete math, compilers, operating systems, data structures, cryptography or anything involving c/c++ courses</p>
</blockquote>
<p>Hmmm ... It would have been OK had you not taken cryptogrophy or AI, but if you dont have an idea of Data Structures, Operating Systems, Compilers etc., I am not sure you have lot of options for good shot at 'hardcore' CS stuff at Master's level.</p>
|
Automatically remove Subversion unversioned files <p>Does anybody know a way to recursively remove all files in a working copy that are not under version control? (I need this to get more reliable results in my automatic build VMware.)</p>
|
<p>this works for me in bash:</p>
<pre><code> svn status | egrep '^\?' | cut -c8- | xargs rm
</code></pre>
<p><a href="http://stackoverflow.com/users/50225/seth-reno">Seth Reno</a>'s is better:</p>
<pre><code>svn status | grep ^\? | cut -c9- | xargs -d \\n rm -r
</code></pre>
<p>It handles unversioned folders and spaces in filenames</p>
<p>As per comments below, this only works on files that subversion doesn't know about (status=?). Anything that subversion <em>does</em> know about (including Ignored files/folders) will not be deleted.</p>
<p>If you are using subversion 1.9 or greater you can simply use the <a href="https://subversion.apache.org/docs/release-notes/1.9.html#svn-cleanup-options">svn cleanup</a> command with --remove-unversioned and --remove-ignored options</p>
|
Very odd bug when using a System.Timers.Timer <p>For some odd reason the Elapsed event is firing twice, where it should definitely be firing once.
And immediately after, the timer ceases to work...
The code structure is somewhat like this:
A certain object is defined to fire a certain event when a value it contains, which is constantly updated in 500-1500ms intervals, increases in over X sum compared to the previous value.</p>
<p>For example, if I define my X as 2, and the values I'm receiving are 1,2,1,2,3,4,8 for example, the event will fire when 8 is entered.
The event handler for that event starts the aforementioned timer, which runs for Y time before it elapses and fires the problematic event.
If the value returns to normal before the timer elapses, the timer is reset.</p>
<p>So, the overall result should be an application that measures a certain dynamic value, and monitors it for large X size exceptions that occur for over Y seconds time.</p>
<p>The overall result in code looks something like</p>
<pre><code>vMonitor.Range=X;
vMonitor.Over+= new EventHandler(StartTimer);
vMonitor.Normal+= new EventHandler(StopTimer);
vTimer.Elapsed+= new EventHandler(RaiseAlert);
source.BeginUpdate(vMonitor.Value);
</code></pre>
<p>The actual problem is that the RaiseAlert is fired twice upon the timers elapsing, and then its as if the Timer stops working completely, not firing at all anymore.
I think its worth mentioning that the full application contains a lot of thread activity, with atleast 2 threads running at a time, updating the vMonitor values.</p>
<p>Any Thoughts?</p>
<h3>Update:</h3>
<p>About the thread matter, its fairly complex to explain the exact structure, but I can say that the vMonitor object is contained in another object, that contains the updating value, which is constantly changed by the various threads, in a monitored manner, of course. Whenever the parent object's value is updated, its compared to vMonitor, and the proper event is fired. The value in vMonitor is subsequently replaced by the parent objects value.</p>
<p>EDIT: I've just verified it again, the vTimer.Elapsed delegate holds only one, correct, event handler.</p>
|
<p>From <a href="http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx" rel="nofollow">MSDN</a>:</p>
<blockquote>
<p>The Elapsed event is raised on a
ThreadPool thread. If processing of
the Elapsed event lasts longer than
Interval, the event might be raised
again on another ThreadPool thread.
Thus, the event handler should be
reentrant.</p>
</blockquote>
|
Can I compare two ms-access files? <p>I want to compare two ms-access .mdb files to check that the data they contain is same in both.</p>
<p>How can I do this?</p>
|
<p>I've done this kind of thing in code many, many times, mostly in cases where a local MDB needed to have updates applied to it drawn from data entered on a website. In one case the website was driven by an MDB, in others, it was a MySQL database. For the MDB, we just downloaded it, for MySQL, we ran scripts on the website to export and FTP text files.</p>
<p>Now, the main point is that we wanted to compare data in the local MDB to the data downloaded from the website and update the local MDB to reflect changes made on the website (no, it wasn't possible to use a single data source -- it was the first thing I suggested, but it wasn't feasible).</p>
<p>Let's call MDB A your local database, and MDB B the one you're downloading for comparison. What you have to check for is:</p>
<ol>
<li><p>records that exist in MDB A but not in MDB B. These may or may not be candidates for deletion (this will depend on your particular data).</p></li>
<li><p>records that exist in MDB B but not in MDB A. These you will append from MDB B to MDB A.</p></li>
<li><p>records that exist in both, which will need to be compared field by field.</p></li>
</ol>
<p>Steps #1 and #2 are fairly easily accomplished with queries that use an outer join to find the missing records. Step 3 requires some code.</p>
<p>The principle behind the code is that the structure of all the tables in both MDBs are identical. So, you use DAO to walk the TableDefs collection, open a recordset, and walk the fields collection to run a SQL statement on each column of each table that either updates the data or outputs a list of the differences. </p>
<p>The basic structure behind the code is:</p>
<pre><code> Set rs = db.OpenRecordset("[SQL statement with the fields you want compared]")
For Each fld In rs.Fields
' Write a SQL string to update all the records in this column
' where the data doesn't match
strSQL = "[constructed SQL here]"
db.Execute strSQL, dbFailOnError
Next fld
</code></pre>
<p>Now, the major complexity here is that your WHERE clause for each field has to be different -- text fields need to be treated differently from numeric and data fields. So you'll probably want a SELECT CASE that writes your WHERE clause based on the field type:</p>
<pre><code> Select Case fld.Type
Case dbText, dbMemo
Case Else
End Select
</code></pre>
<p>You'll want to use Nz() to compare the text fields, but you'd use Nz(TextField,'') for that, while using Nz(NumericField,0) for numeric fields or date fields. </p>
<p>My example code doesn't actually use the structure above to define the WHERE clause because it's limited to fields that work very well comparing concatenated with a ZLS (text fields). What's below is pretty complicated to read through, but it's basically an expansion on the above structure.</p>
<p>It was written for efficiency of updates, since it executes a SQL UPDATE for each field of the table, which is much more efficient than executing a SQL UPDATE for each row. If, on the other hand, you don't want to do an update, but want a list of the differences, you might treat the whole thing differently. But that gets pretty complicated depending on the output, </p>
<p>If all you want to know is if two MDBs are identical, you would first check the number of records in each table first, and if you have one non-match, you quit and tell the user that the MDBs aren't the same. If the recordcounts are the same, then you have to check field by field, which I believe is best accomplished with column-by-column SQL written dynamically -- as soon as one of the resulting SQL SELECTS returns 1 or more records, you abort and tell your user that the MDBs are not identical.</p>
<p>The complicated part is if you want to record the differences and inform the user, but going into that would make this already-interminable post even longer!</p>
<p>What follows is just a portion of code from a larger subroutine which updates the saved query qdfOldMembers (from MDB A) with data from qdfNewMembers (from MDB B). The first argument, strSQL, is a SELECT statement that is limited to the fields you want to compare, while strTmpDB is the path/filename of the other MDB (MDB B in our example). The code assumes that strTmpDB has qdfNewMembers and qdfOldMembers already created (the original code writes the saved QueryDef on the fly). It could just as easily be direct table names (the only reason I use a saved query is because the fieldnames don't match exactly between the two MDBs it was written for).</p>
<pre><code>Public Sub ImportMembers(strSQL As String, strTmpDB As String)
Const STR_QUOTE = """"
Dim db As Database
Dim rsSource As Recordset '
Dim fld As Field
Dim strUpdateField As String
Dim strZLS As String
Dim strSet As String
Dim strWhere As String
' EXTENSIVE CODE LEFT OUT HERE
Set db = Application.DBEngine(0).OpenDatabase(strTmpDB)
' UPDATE EXISTING RECORDS
Set rsSource = db.OpenRecordset(strSQL)
strSQL = "UPDATE qdfNewMembers INNER JOIN qdfOldMembers ON "
strSQL = strSQL & "qdfNewMembers.EntityID = qdfOldMembers.EntityID IN '" _
& strTmpDB & "'"
If rsSource.RecordCount <> 0 Then
For Each fld In rsSource.Fields
strUpdateField = fld.Name
'Debug.Print strUpdateField
If InStr(strUpdateField, "ID") = 0 Then
If fld.Type = dbText Then
strZLS = " & ''"
Else
strZLS = vbNullString
End If
strSet = " SET qdfOldMembers." & strUpdateField _
& " = varZLStoNull(qdfNewMembers." & strUpdateField & ")"
strWhere = " WHERE " & "qdfOldMembers." & strUpdateField & strZLS _
& "<>" & "qdfNewMembers." & strUpdateField & strZLS _
& " OR (IsNull(qdfOldMembers." & strUpdateField _
& ")<>IsNull(varZLStoNull(qdfNewMembers." _
& strUpdateField & ")));"
db.Execute strSQL & strSet & strWhere, dbFailOnError
'Debug.Print strSQL & strSet & strWhere
End If
Next fld
End If
End Sub
</code></pre>
<p>Code for function varZLSToNull():</p>
<pre><code>Public Function varZLStoNull(varInput As Variant) As Variant
If Len(varInput) = 0 Then
varZLStoNull = Null
Else
varZLStoNull = varInput
End If
End Function
</code></pre>
<p>I don't know if that's too complex to make sense, but maybe it will help somebody.</p>
|
When should I use primitives instead of wrapping objects? <p>Actually <a href="http://stackoverflow.com/questions/564/what-is-the-difference-between-an-int-and-an-integer-in-javac">here</a> is a similar topic with little practical value.
As far as I understand, primitives perform better and should be used everywhere except for the cases where Object-related features (e.g. <code>null</code> check) are needed. Right?</p>
|
<p>Do not forget that, since creating a new wrapper for every boxing occurrence is quite expensive, especially considering it usually being used at a single scope of a method, <a href="http://chaoticjava.com/posts/autoboxing-tips/">Autoboxing</a> uses a pool of common wrappers.</p>
<p>This is in fact an implementation of the <a href="http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/FlyweightPattern.htm">flyweight design pattern</a>. When a boxing occurs for a well-known value, instead of creating a new wrapper instance, a pre-created instance is fetched from a pool and returned.</p>
<p>One consequence is: <strong>itâs still not recommended to use autoboxing for scientific calculations</strong>. For example, the code d = a * b + c is using Integer classes for a, b, c and d, and the generated code is d.valueOf(a.intValue() * b.intValue() + c.intValue()). All these method invocations have their own overhead, so <strong>itâs usually recommended to use autoboxing when needed to store primitives in collections</strong>.</p>
<p>And even then, if you have a <strong>huge collection</strong> of Integer wrapping int, the overhead can implies longer execution times, up to <strong>20 times longer</strong>, as <a href="http://www.javaspecialists.co.za/archive/Issue090.html">reported in this article</a>.</p>
<p><hr /></p>
<p>Jb adds this important comment: </p>
<blockquote>
<p>Also Wrapper.valueOf(primitive) uses pool of wrappers. So prefer Integer.valueOf(5) to new Integer(5)</p>
</blockquote>
|
What tools to use for developing flash/flex based touch screen user interface for embedded system <p>We are looking at developing a device with a touch screen and an embedded PC like computer for the user interface.</p>
<p>What are the benefits and disadvantages of using flash/flex for this user interface development?</p>
<p>One of our goals is to seperate the design (= look and feel) and the functionality of the application to ease the development.</p>
|
<p>Regarding Flash</p>
<p>Pros:</p>
<ul>
<li>Readily available</li>
<li>Powerful editing tools</li>
<li>Lots of people know how to use it</li>
</ul>
<p>Cons:</p>
<ul>
<li>(Very) bad performance in contrast to what it does</li>
<li>Open source implementations still lagging</li>
<li>Use of Adobe's flash component is regulated by their EULA</li>
<li>Does not offer a clear cut API for embedding</li>
</ul>
|
SQL CE 3.5 deployment problem, concerning interop between C# and C++ <p>We have a situation where a C# application is working with SQL CE 3.5 . To allow for a legacy program to use some of its features we have produced a C++ dll which uses interop to extract the info that it needs from the C# program. For this to work, the C#-program needs to access the database. Its not a very complex scenario.</p>
<p>When trying to deploy with a private install some problems occur though.
<strong>There is no problem with the C# program, it can access the database and work with it without any problems.</strong></p>
<p><strong>But when trying to access functions in the C#-program through the C++ interop which forces the C#-program to access the database, we get a crash with the exception saying that "...the Provider: System.Data.SqlServerCe.3.5 is not installed".</strong></p>
<p>This is obviously because we cannot add a App.config file to the executing program.</p>
<p>How can we get around this? Is there another way to fix this? Any other forms of SQL CE 3.5 install methods are out of the question. So we must get this to work.</p>
<p>Regards,</p>
<p>P</p>
<p><strong>Edit:</strong></p>
<p>I'm not working against SQL CE directly, but through Linq2SQL. I have tried to add config files to all my dll's, it does not help. It seems to only matter if the executable file have got a app.config.</p>
<p>The exception thrown says - The provider System.Data.SqlServerCe.3.5 is not installed.</p>
<p>And the latest function to be called according to the stack trace is
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Initialize(...).</p>
<p><strong>Edit 2</strong></p>
<p>I have added all the files necessery for the deployment to work. As I wrote above, it works if I use the program dll (which uses Linq 2 Sql) through a .net executable with a app.config file that specifies where to look for the SQL CE 3.5 dll. Deployment will <em>not</em> work with only the files, an app.config file is necessary.</p>
<p>The problem is that we have to use the dll file through a C++ executable which have no means of telling .net where to look for the Sql Ce 3.5 dll.</p>
|
<p>add the following files to your application folder:</p>
<ul>
<li>sqlceca35.dll</li>
<li>sqlcecompact35.dll</li>
<li>sqlceer35E.dll</li>
<li>sqlceme35.dll</li>
<li>sqlceoledb35.dll</li>
<li>sqlceqp35.dll</li>
<li>sqlcese35.dll</li>
<li>System.Data.SqlServerCe.dll</li>
</ul>
<p>then it will work.</p>
<p>that is necessary if you have not explicitely installed sql server ce 3.5 on the target machine (which is case for most deployments i think).</p>
|
Question about MSDN and commercial use <p>I work for a small digital marketing company as a programmer, and we are not a Microsoft partner or any sort (Gold/Silver/Bronze). However, we use .NET.</p>
<p>What I am confused about is that the developer before me has left, and he gets subscription DVDs of latest Microsoft tools, delivered to the company (Sql Server etc).</p>
<p>I am assumign this is not a personal subscription, because if it was he'd have changed addresses.</p>
<p>Anyway, the subscription is Professional and we use the tools for commercial purposes. Is this allowed? Also, am I allowed to use the tools that we get, at home? I want to use Windows Server at home for dev purposes (learning it for my exams).</p>
<p>Thanks</p>
<hr>
<p>Thanks for the advice guys.</p>
<p>The license is registered in my boss name but I think a networking guy has added himself as an additional user.</p>
<p>MSDN FAQ says I can have up to 10 instances of the tools installed. I was thinking if I use a product key off MSDN, then that key is forever in use and no additional licenses can be installed.</p>
|
<p>For the definitive answer read through the <a href="http://msdn.microsoft.com/en-us/subscriptions/aa948864.aspx">MSDN subscription FAQ</a> which includes the license terms.</p>
<p>My understanding is that you can use the software to support development work for your company, but not run production servers. Ie. you could develop Exchange add-ins but not run your company's email using the Exchange Server that comes with MSDN.</p>
<p>Using the software at home is probably a grey area. If it is on company owned equipment and supports your development goals then it sounds OK. If it is on your own equipment then it likely goes against the details of the EULA. You could always try calling Microsoft and asking.</p>
|
Securing .NET application with keys <p>I am at the point where I need to add keys to my app. What are some of the possible solutions you guys used? I've looked at an earlier <a href="http://stackoverflow.com/questions/118031/best-activation-key-software-for-net-application">post</a> so far, anything else before I decide. My 2 influential factors are:</p>
<ol>
<li>Price</li>
<li>Ease of use</li>
</ol>
<p>Thanks</p>
|
<p>If you are talking about software protection, take a minute to reconsider it.</p>
<p>Protection schemes are mostly a waste of time. If .NET is similar in this regard to Java, decompiling the code and removing any kind of protection is trivial. The only more or less robust solutions are network based- and these can be very annoying because you are introducing a new point of failure to your application- what happens if your authentication server is down or they lose internet connectivity?</p>
<p>I know that "The Powers That Be" like this stuff, but please, analyze the situation carefully.</p>
|
Web Application Time Zone Issue <p>We have a ASP.Net 2.0 web application up and running with the server in the Midwest (Eastern Standard Time). At this moment all of our customers are in the same time zone as the server. We are bringing another server online in Arizona (Mountain Standard Time).</p>
<p>We are storing all our times in a SQL 2005 database via C# codebehind DateTime.UtcNow.</p>
<p>During testing we encountered some time zone conversion issues.
Our problem is that in the web browser our times are displaying the Mountain Standard Time instead of the time zone we are testing from which is Eastern Standard Time. </p>
<p>When we enter new information it gets stored as UTC in the database, but when we go to view that info in the browser it is displaying the Mountain Standard Time.
Below is the code which takes the UTC value from the database and displays it in the browser.</p>
<pre><code>lblUpdatedDate.Text = Convert.ToDateTime(dr["UpdatedDate"]).ToLocalTime().ToString();
</code></pre>
<p>The above code returns Mountain Standard Time where the server is, not Eastern Standard Time where the browser is running from. How do we get the time to display where the user is?</p>
|
<p>I had the same issue. We sold our application to a user that was in a different time zone than the web server. We did not store any time information in UTC, but it was actually working correctly. Time displayed in the server's time zone was displaying exactly 3 hours behind. All we had to do was add a time zone drop down so they could select their time zone for the entire site (since the only users of the application would be in their time zone). We saved this setting and then inserted a function to take all datetime displays and convert from one time zone to the other using the TimeZoneInfo namespace. It works perfectly.</p>
|
How can I wrap a method so that I can kill its execution if it exceeds a specified timeout? <p>I have a method that I would like to call. However, I'm looking for a clean, simple way to kill it or force it to return if it is taking too long to execute.</p>
<p>I'm using Java.</p>
<p>to illustrate:</p>
<pre><code>logger.info("sequentially executing all batches...");
for (TestExecutor executor : builder.getExecutors()) {
logger.info("executing batch...");
executor.execute();
}
</code></pre>
<p>I figure the <code>TestExecutor</code> class should <code>implement Callable</code> and continue in that direction.</p>
<p>But all i want to be able to do is stop <code>executor.execute()</code> if it's taking too long.</p>
<p>Suggestions...?</p>
<p><strong>EDIT</strong></p>
<p>Many of the suggestions received assume that the method being executed that takes a long time contains some kind of loop and that a variable could periodically be checked.
However, this is not the case. So something that won't necessarily be clean and that will just stop the execution whereever it is is acceptable.</p>
|
<p>You should take a look at these classes :
<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html">FutureTask</a>, <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Callable.html">Callable</a>, <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html">Executors</a></p>
<p>Here is an example :</p>
<pre><code>public class TimeoutExample {
public static Object myMethod() {
// does your thing and taking a long time to execute
return someResult;
}
public static void main(final String[] args) {
Callable<Object> callable = new Callable<Object>() {
public Object call() throws Exception {
return myMethod();
}
};
ExecutorService executorService = Executors.newCachedThreadPool();
Future<Object> task = executorService.submit(callable);
try {
// ok, wait for 30 seconds max
Object result = task.get(30, TimeUnit.SECONDS);
System.out.println("Finished with result: " + result);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
System.out.println("timeout...");
} catch (InterruptedException e) {
System.out.println("interrupted");
}
}
}
</code></pre>
|
MYSQL: Create Table If Not Exists <p>If I do a <strong>Create Table If Not Exists</strong>, and a table with the same name exists with fewer rows (or columns), what would happen?</p>
|
<p>The table will not be created if a table with the same name already exists regardless of table layout.</p>
|
Transfer variables between PHP pages <p>I want to get user input in one page, store that in a php variable and use it in another php page. I have tried using 'sessions' but it doesn't seem to be working. Is there another safe alternative? This information is likely to be usernames and passwords.</p>
|
<p>Try changing your session code as this is the best way to do this.</p>
<p>For example:</p>
<h2>index.php</h2>
<pre><code><?php
session_start();
if (isset($_POST['username'], $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
echo '<a href="nextpage.php">Click to continue.</a>';
} else {
// form
}
?>
</code></pre>
<h2>nextpage.php</h2>
<pre><code><?php
session_start();
if (isset($_SESSION['username'])) {
echo $_SESSION['username'];
} else {
header('Location: index.php');
}
?>
</code></pre>
<p>However I'd probably store something safer like a userid in a session rather than the user's login credentials.</p>
|
Convert a string to GregorianCalendar <p>I have a string from an email header, like <code>Date: Mon, 27 Oct 2008 08:33:29 -0700</code>. What I need is an instance of GregorianCalendar, that will represent the same moment. As easy as that -- how do I do it?</p>
<p>And for the fastest ones -- this is <strong>not</strong> going to work properly:</p>
<pre><code>SimpleDateFormat format = ... // whatever you want
Date date = format.parse(myString)
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date)
</code></pre>
<p>because it will normalize the timezone to UTC (or your local machine time, depending on Java version). What I need is calendar.getTimeZone().getRawOffset() to return <code>-7 * milisInAnHour</code>.</p>
|
<p>I'd recommend looking into the Joda Time library, if that's an option. I'm normally against using a third-party library when the core platform provides similar functionality, but I made this an exception because the author of Joda Time is also behind JSR310, and Joda Time is basically going to be rolled into Java 7 eventually.</p>
<p><a href="http://joda-time.sourceforge.net/">http://joda-time.sourceforge.net/</a></p>
<p>So anyway, if Joda Time is an option, something like this <em>should</em> work:</p>
<pre><code>DateTimeFormatter formatter =
DateTimeFormat.forPattern("your pattern").withOffsetParsed();
DateTime dateTime = formatter.parseDateTime("your input");
GregorianCalendar cal = dateTime.toGregorianCalendar();
</code></pre>
<p>I hope this helps.</p>
|
In PHP, how do you change the key of an array element? <p>I have an associative array in the form <code>key => value</code> where key is a numerical value, however it is not a sequential numerical value. The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value.</p>
<p>I didn't see a function that does this, but I'm assuming I need to provide the old key and new key (both of which I have) and transform the array. Is there an efficient way of doing this?</p>
|
<pre><code>$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
</code></pre>
|
How to Programatically read the Documentation section of a WSDL in C# <p>i am using a WSDL file to create a the proxy class file, this service has a big Enumeration. the description for each enum value is in documentation section, how can i programatically read that section?</p>
|
<p>A WSDL file is always an XML file, so you can open it and read the elements data. For example, given the <a href="http://developer.ebay.com/webservices/latest/eBaySvc.wsdl" rel="nofollow">eBay Services WSDL file</a>, you can query the documentation of the value <code>COD</code> of the enumeration <code>BuyerPaymentMethodCodeType</code> like this:</p>
<pre><code> XmlDocument wsdlDoc = new XmlDocument();
wsdlDoc.Load(@"D:\temp\eBaySvc.wsdl");
XmlNamespaceManager nsMgr = new XmlNamespaceManager(wsdlDoc.NameTable);
nsMgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
XmlNode node = wsdlDoc.SelectSingleNode("//xs:simpleType[@name='BuyerPaymentMethodCodeType']/xs:restriction/xs:enumeration[@value='COD']/xs:annotation/xs:documentation", nsMgr);
string description = node.InnerText;
</code></pre>
|
Asp.net Usercontrol LoadControl Issue <p>I am having an issue when using <code>LoadControl( type, Params )</code>. Let me explain...</p>
<p>I have a super simple user control (ascx)</p>
<pre><code><%@ Control Language="C#" AutoEventWireup="True" Inherits="ErrorDisplay" Codebehind="ErrorDisplay.ascx.cs" EnableViewState="false" %>
<asp:Label runat="server" ID="lblTitle" />
<asp:Label runat="server" ID="lblDescription" />
</code></pre>
<p>with code ( c# ) behind of:</p>
<pre><code>public partial class ErrorDisplay : System.Web.UI.UserControl
{
private Message _ErrorMessage;
public ErrorDisplay()
{
}
public ErrorDisplay(Message ErrorMessage)
{
_ErrorMessage = ErrorMessage;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (_ErrorMessage != null)
{
lblTitle.Text = _ErrorMessage.Message;
lblDescription.Text = _ErrorMessage.Description;
}
}
}
</code></pre>
<p>Elsewhere in my web application I am adding an instance of the usercontrol to the page using the following code:</p>
<pre><code>divValidationIssues.Controls.Add(LoadControl(typeof(ErrorDisplay), new object[] { MessageDetails }));
</code></pre>
<p>I am using the overloaded version of LoadControl because I want to pass the Message parameter to the constructor. All this <em>appears</em> to work ok.</p>
<p>However, when the <code>OnPreRender()</code> is fired on the ErrorDisplay usercontrol the lblTitle and lblDescription variables are both <code>null</code>, despite them having a markup equivalent. The message variable has been correctly populated.</p>
<p>Can anyone shed any light on why this may be happening?</p>
<p>Thanks</p>
<p><strong>EDIT:</strong></p>
<p>Just for clarity I'll also add that the code which is programatically adding the usercontrol to the page is running in response to a button press, so the 'hosting page' has progressed through Init, Page_Load and is now processing the event handlers.</p>
<p>I cannot add the usercontrols at an earlier asp lifecycle stage as they are being created in response to a button click event.</p>
|
<p>I have tried the following code as well - which yields the same result (i.e. both lblTitle and lblDescription are null)</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if (_ErrorMessage != null)
{
lblTitle.Text = _ErrorMessage.Message;
lblDescription.Text = _ErrorMessage.Description;
}
}
</code></pre>
<p>I had the understanding that the LoadControl function brought the control it is loading up to the current 'state' of the page onto which it is being included on. hence the Init, Page_Load etc are all run as part of the LoadControl call.</p>
<p>Interestingly this (unanswered) asp.net forums post exhibits the same problem as I am experiencing.</p>
<p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2333625&SiteID=1">MSDN Forums Post</a></p>
<p>Additionally - From the MSDN:</p>
<blockquote>
<p>When you load a control into a container control, the container raises all of the added control's events until it has caught up to the current event. However, the added control does not catch up with postback data processing. For an added control to participate in postback data processing, including validation, the control must be added in the Init event rather than in the Load event. </p>
</blockquote>
<p>Therefore shouldn't LoadControl correctly initalise the control?</p>
<p><strong>EDIT:</strong></p>
<p>Ok, so I'm answering my own question here ..</p>
<p>I found an answered version of the forum post I linked to above <a href="http://forums.asp.net/t/1174838.aspx">Here</a> </p>
<p>Essentially the answer is that the <code>LoadControl( type, params )</code> cannot infer the 'page infront' ascx to parse and hence it doesn't bother initalising any of the controls. When you use the <code>LoadControl( "ascx path" )</code> version it is given the page infront and hence does all the parsing and initalision.</p>
<p>So in summary I need to change the code which is initalising the control and split it into seperate parts. I.e.</p>
<pre><code>Control ErrorCntrl = LoadControl("ErrorDisplay.ascx");
ErrorCntrl.ID = SomeID;
(ErrorCntrl as ErrorDisplay).SetErrorMessage = MessageDetail;
divErrorContainer.Controls.Add(ErrorCntrl);
</code></pre>
<p>And it should work ok.. It isn't as neat as my previous attempt, but at least it will work.</p>
<p>I am still open to suggestions to improve the above.</p>
<p>Cheers</p>
|
Cross-site scripting from an Image <p>I have a rich-text editor on my site that I'm trying to protect against XSS attacks. I think I have pretty much everything handled, but I'm still unsure about what to do with images. Right now I'm using the following regex to validate image URLs, which I'm assuming will block inline javascript XSS attacks: </p>
<pre><code>"https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+"
</code></pre>
<p>What I'm not sure of is how open this leaves me to XSS attacks from the remote image. Is linking to an external image a serious security threat?</p>
<p>The only thing I can think of is that the URL entered references a resource that returns "<code>text/javascript</code>" as its MIME type instead of some sort of image, and that javascript is then executed.</p>
<p>Is that possible? Is there any other security threat I should consider?</p>
|
<p>Another thing to worry about is that you can easily embed PHP code inside an image and upload that most of the time. The only thing an attack would then have to be able to do is find a way to include the image. (Only the PHP code will get executed, the rest is just echoed). Check the MIME-type won't help you with this because the attacker can easily just upload an image with the correct first few bytes, followed by arbitrary PHP code. (The same is somewhat true for HTML and Javascript code).</p>
|
How Important is a Team Having Shared Vision? <p>Just watching <a href="http://www.infoq.com/interviews/11-Commitments-Jim-McCarthy" rel="nofollow">Jim McCarthy's talk</a> about 11 commitments for shared vision over at InfoQ and it got me thinking.</p>
<p>Specifically, how important is having a shared vision to a team?</p>
<p>Looking back over my, wow-is-it-that-long, many years in this game I see that the best teams that I've worked on have had a shared vision and shared commitment to the vision.</p>
<p>Has anyone been involved in a team, for a reasonably sized project, that was successful where they <strong>didn't</strong> have a shared vision?</p>
|
<p>Shared vision is fine, if you're talking about the ultimate goal of the project. A lot of times, this is extended into the minutiae of actually building the system.</p>
<p>On a project I've worked on, the group had A Way to do things, and the majority held onto The Way even in cases when it didn't make sense, or was actually detrimental to a particular module or the project as a whole. </p>
<p>Everyone in a group should be working toward the same goal. That said, it's important to have dissenting opinion, questions, even outright arguments about the details. It's also important to have someone managing everything, who can make a final decision (even an unpopular one) about something, rather than letting the "team" steer the project.</p>
|
How to use SQL_ASCII encoding in a rails application? <p>I have to connect to a legacy postgre database wich has <strong>ENCODING = 'SQL_ASCII';</strong>. How do I set this encoding in my rails app?</p>
|
<p>You can set this in your database.yml:</p>
<pre><code>development:
adapter: postgresql
encoding: sql_ascii
database: appname_development
username: root
password:
host: localhost
</code></pre>
|
How to manually drop down a DataGridViewComboBoxColumn? <p>I have a DataGridView with one DataGridViewComboBoxColumn in my WinForms application. I need to drop down (open) this DataGridViewComboBoxColumn manually, let's say after a button is clicked.</p>
<p>The reason I need this is I have set SelectionMode to FullRowSelect and I need to click 2-3 times to open the combo box. I want to click on the combobox cell and it should drop down immediately. I want to do this with CellClick event, or is there any other way?</p>
<p>I am searching in Google and VS help, but I haven't found any information yet.</p>
<p>Can anybody help please?</p>
|
<p>I know this can't be the ideal solution but it does create a single click combo box that works within the cell.</p>
<pre><code> Private Sub cell_Click(ByVal sender As System.Object, ByVal e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
DataGridView1.BeginEdit(True)
If DataGridView1.Rows(e.RowIndex).Cells(ddl.Name).Selected = True Then
DirectCast(DataGridView1.EditingControl, DataGridViewComboBoxEditingControl).DroppedDown = True
End If
End Sub
</code></pre>
<p>where "ddl" is the combobox cell I added in the gridview. </p>
|
jQuery UI: Filter selectable dates on datepicker <p>I want to filter the selectable dates on a datepicker. I basically need to filter by work days - i.e. make holidays and weekends not selectable.</p>
<p>I know you can specify dates using a function in the beforeShowDate: and you can also use $.datepicker.noWeekends.</p>
<p>Question is: can you do both?</p>
|
<p>$.datepicker.noWeekends is a pretty simple bit of code:</p>
<pre><code>function (date) {
var day = date.getDay();
return [day > 0 && day < 6, ""];
}
</code></pre>
<p>Since you're going to have to write up the function for holidays, you can just include this logic in that function too.</p>
|
Vista, Office Interop not working <p>Does anyone know how to get the MS Office 2007 .NET C# Interop libraries to work with Vista? </p>
<p>I have a .NET C# application that I have setup to run as a Windows service. This program will open up a Word or Excel template depending on the situation and modify its contents and then save the document back out. All of this worked great when I was doing it on a Windows Server 2003 or XP machine using Office 2007. When I moved everything to a Server 2008 box, everything quit working. In Excel for example, I get a COM exception telling me that the Excel file cannot be opened when the file is clearly there and I can open it just fine when doing it manually. The windows service is running under the same user account that I log into the machine with and that account is an Administrator. </p>
<p>Does anyone have any idea what to do?</p>
|
<p>On Vista and Windows Server 2008, services run in something called Session0. Before Vista, regular programs would run in Session0 alongside services.</p>
<p>This means that Session0 has become a desktop-less wasteland where your services can't even access explorer.exe. I'm pretty sure the problem is that Office applications are expecting to be able to access a few components that are normally on the desktop.</p>
<p>Since Excel, Word, etc. are only supported on a desktop-ed session, you only have a few choices:</p>
<ol>
<li>Set the Desktop checkbox in the LogOn tab of your Service's properties and pray that it appeases the Office gods. (It probably wont.)
<ul>
<li>After trying 1, go through your code and try and remove/work around anything that causes it to crash.</li>
</ul></li>
<li>Use remoting/WCF to make a server that performs the interop work, and make your service communicate with it.
<ul>
<li>You'll need to have a logged in interactive user and the user needs to start the server application somehow. Perhaps best to use autostart.</li>
<li>You can try turning on Automatic login. <a href="http://support.microsoft.com/kb/324737" rel="nofollow">http://support.microsoft.com/kb/324737</a></li>
</ul></li>
<li>Try impersonating a Logged in user using CreateProcessAsUser and friends.
<ul>
<li>Note: I don't know how well this works unless a user is actually logged in, so it might not be any more useful than 2 above, and is much harder to pull off. (Needs P/Invoke)</li>
</ul></li>
<li>Rewrite your program to use the OpenXML sdk or use something like SpreadsheetGear. </li>
</ol>
|
Setting up a backup DB server in ASP.NET web.config file <p>I currently have an asp.net website hosted on two web servers that sit behind a Cisco load balancer. The two web servers reference a single MSSQL database server.</p>
<p>Since this database server is a single point of failure, I'm adding an additional MSSQL server for backup. I would like to setup my web.config files to write everything to both MSSQL servers, but only read from the "primary" database server unless it is unreachable for some reason, at which point the backup MSSQL server would be used.</p>
<p>Is this possible via a web.config file setting, or must this be done in code? Thanks in advance for any help.</p>
<p>New Information:
I just wanted to add further information on this topic after researching it for the past several days - Microsoft TechNet has a good article title "Implementing Application Failover with Database Mirroring" (<a href="http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/implappfailover.mspx#EMD" rel="nofollow">http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/implappfailover.mspx#EMD</a>).</p>
<p>This specifically covers the database mirroring feature in Microsoft SQL Server 2005 and the new new "Failover Partner" connection string keyword that allows you to specify two server/db instances in a single connection string.</p>
<p>The article is well worth a read if your interested in implementing this type of feature.</p>
|
<p>What you want is called "failover", where if one database fails your queries are automatically redirected to the other. This is acheived at the database level, not the application. There are a lot of walkthroughs etc for setting up failover clusters: here's one for <a href="http://www.microsoft.com/technet/prodtechnol/sql/2000/maintain/failclus.mspx" rel="nofollow">SQL 2000</a>, and another for <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=818234dc-a17b-4f09-b282-c6830fead499&displaylang=en" rel="nofollow">SQL 2005</a>. Basically, once you set it up, the primary database communicates all activity to the secondary one. If the primary fails, the secondary is (almost) up to date and takes over.</p>
<p>The servers form a cluster, and look like a single unit - similar to the way your load-balanced web servers look to the outside world. The backup monitors the primary, and if the primary stops responding, the backup takes over receiving queries. If you're Googling, try also looking adding the keywords "database mirroring" and "quorum".</p>
|
Single Table Inheritance in Django <p>Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate. </p>
<p>Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager_id (parent_id) would be a good approximation of the problem I am solving. </p>
<p>In my case, I would like to represent the idea that an employee can manage other employees while being managed by a different employee. There are not separate classes for Manager and Worker, which makes this hard to spread across tables. Sub-classes would represent types of employees-programmers, accountants, sales, etc and would be independent of who supervises who (OK, I guess it's no longer a typical corporation in some respect). </p>
|
<p>There are currently two forms of inheritance in Django - MTI (model table inheritance) and ABC (abstract base classes).</p>
<p>I wrote a <a href="http://web.archive.org/web/20090227074910/http://thisweekindjango.com/articles/2008/jun/17/abstract-base-classes-vs-model-tab/" rel="nofollow">tutorial</a> on what's going on under the hood.</p>
<p>You can also reference the official docs on <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance" rel="nofollow">model inheritance</a>.</p>
|
What is the meaning of CHECKDB=FALSE in MSI? <p>When running an MSI through the command line what does passing the arguement "CHECKDB=FALSE" really do?</p>
<p>The MSI of course can be anything from Microsoft, to Compuware DevPartner, to a programmer compiled MSI from .NET.</p>
|
<p>Running an MSI with that parameter would set the public property named CHECKDB equal to a false value. I have not seen that particular property before and I don't see any reference to it online. I suspect that it is specific to the MSI that you are using.</p>
|
"Join" of time series <p>I am designing a simple internal framework for handling time series data.
Given that LINQ is my current toy hammer, I want to hit everything with it.</p>
<p>I want to implement methods in class TimeSeries (Select(), Where() and so on) so that I can use LINQ syntax to handle time series data</p>
<p>Some things are straight forward, e.g. (from x in A select x+10), giving a new time series.</p>
<p>What is the best syntax design for combining two or more time series?
(from a in A from b in B select a+b) is not great, since it expresses a nested loop.
Maybe some join? This should correspond to join on the implicit time variable.
(What I have in mind corresponds to the lisp 'zip' function)</p>
<p><hr /></p>
<p><strong>EDIT:</strong> <em>Some clarification is necessary.</em></p>
<p>A time series is a kind of function depending on time, e.g. stock quotes.
A combination of time series could be the difference between two stock prices, as a function of time.</p>
<pre><code>Stock1.MyJoin(Stock2, (a,b)=>a-b)
</code></pre>
<p>is possible, but can this be expressed neatly using some LINQ syntax?
I am expecting to implement LINQ methods in <code>class MyTimeSeries</code> myself.</p>
|
<p><code>Union</code> sounds like the right way to go - no query expression support, but I think it expresses what you mean.</p>
<p>You might be interested in looking at the Range-based classes in <a href="http://pobox.com/~skeet/csharp/miscutil" rel="nofollow">MiscUtil</a> which can be nicely used for times. Combined with a bit of extension method fun, you can do:</p>
<pre><code>foreach (DateTime day in 19.June(1976).To(DateTime.Today).Step(1.Day()))
{
Console.WriteLine("I'm alive!");
}
</code></pre>
<p>I'm not suggesting this should replace whatever you're doing, just that you might be able to take some ideas to make it even neater. Feel free to contribute back, too :)</p>
|
How to use an Open Source License <p>I'm a little unsure how the open source licensing stuff works. If I were to choose a particular open source license, what do you actually have to do to make it applicable to your software? I would imagine it would be a little more involved than just 'stating' that you're releasing your software under LGPL. And how does this 'contract' bind legally to your software?</p>
|
<p>It's as simple as deciding to license your software under a particular license. This is not technically contract law, but copyright law. As the owner/licenser of your intellectual property (the source and binaries) you may license its distribution anyway you see fit. Providing a clear disclaimer as to the recipients rights under the license is all that is necessary. Without a license, whether closed or open, no one has a right to distribute your copyrighted work. The purpose of all licenses is to grant some of your rights to other parties.</p>
<p><a href="http://eu.conecta.it/paper/Open%5Fsource%5Fcopyright%5Flaw.html" rel="nofollow">See here</a> for more information. Or for perhaps too much information, check out O'Reilly's <a href="http://oreilly.com/catalog/osfreesoft/book/" rel="nofollow">Understanding Open Source and Free Software Licensing</a>.</p>
<p>~ William Riley-Land</p>
|
jQuery & ASP.Net Resources & Gotchas <p>What are some good jQuery Resources along with some gotchas when using it with ASP.Net?</p>
|
<p>ASP.Net's autogenerated id's make using jQuery's selector syntax somewhat difficult.</p>
<p>Two easy ways around this problem:</p>
<ul>
<li>Search for objects using css class instead of id</li>
<li>You can weed out the uniqueid garbage with: <code>$('[id$=myid]')</code></li>
</ul>
|
Auto start print html page using javascript <p>Is there anyway to automatically run <code>javascript:window.print()</code> when the page finishes loading? </p>
|
<p><code><body onload="window.print()"></code>
or
<code>window.onload = function() { window.print(); }</code></p>
|
Indexing vs. no indexing when inserting records <p>I have a few questions about whether or not it would be best to not use indexing.</p>
<p>BACKGROUND:
My records have a timestamp attribute, and the records will be inserted in order of their timestamps (i.e., inserted chronologically).</p>
<p>QUESTIONS:</p>
<ol>
<li><p>If I DON'T use indexing is it typical for the database to insert the records in the order that they were inserted? </p></li>
<li><p>If answer to #1 is yes, when I do a "SELECT .. WHERE timestamp > X" type query will the database be efficient at it, or will it have to go through every single record since it isn't indexed? I would assume if there were no index, the database would not "know" that the records were inserted in sorted order and could not, therefore, make use of sorted property of the database. </p></li>
</ol>
<p>I assume a clustered index would be best for these types of records & their inserts.</p>
<p>Please let me know what you guys think.</p>
<p>Thanks,
jbu</p>
|
<p>In my experience, yes, the database will insert stuff in the chronological order, especially if you never delete anything. However, it is not guaranteed, and it's a really bad idea to try to rely on behaviour that is not guaranteed.</p>
<p>Also, the query planner isn't going to know this fact, so any query you do without an index will cause a full table scan. Whether that's slower than an indexed query will depend a lot on what sort of data you have, and what percentage of it comes after the "X" in your query.</p>
|
Best way to access user/site settings <p>There have been a couple of questions that sort of dealt with this but not covering my exact question so here we go.</p>
<p>For site settings, if these are stored in a database do you:</p>
<ol>
<li>retrieve them from the db every time someone makes a request</li>
<li>store them in a session variable on login</li>
<li>???????</li>
</ol>
<p>For user specific settings do I do the same as site settings??</p>
<p>Any guidance/best practice would be greatly appreciated.</p>
<p>Cheers</p>
|
<p>I suggest creating a module for retrieving preferences that could be implemented either way, and then for your first implementation hit the database every time since that's easier. If you have performance problems, add caching to the module to reduce the database traffic.</p>
|
What's a good way to profile the connection speed of Web users? <p>I have a client whose desired Web UI is graphically intense; we would like to gather statistics on the average bandwidth of those connecting to the site. Is there an easy way to do that? The "simplest thing that could possibly work" would seem to be a Flash or Silverlight component that times the download of a file of some size (say 200K), then POSTing the result to a URI that saves the data. Will that work? Should I write my own or is there an easy drop-in element that I can download from somewhere?</p>
|
<p>I would look at Google Analytics. It's a simple javascript that you include on your page, and it uses Google's massive analytics databases to track who's accessing your site over what sort of connections, which is all in a database that they maintain.</p>
<p>You could certainly write a Flash or Silverlight (or javascript) component to download a file in the background, time it, and report that, but you're likely to anger your users for filling up their tubes.</p>
|
What is the quickest way to get the String contents of a URL using Cocoa/iPhoneSDK? <p>Say I want to get the HTML of</p>
<pre>http://www.google.com</pre>
<p>as a String using some built-in classes of the Cocoa Touch framework.</p>
<p>What is the least amount of code I need to write?</p>
<p>I've gotten this far, but can't figure out how to progress. There must be an easier way.</p>
<pre><code>CFHTTPMessageRef req;
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
req = CFHTTPMessageCreateRequest(kCFAllocatorDefault,
CFSTR("GET"),
(CFURLRef)url,
kCFHTTPVersion1_1);
</code></pre>
|
<p>The <i>quickest</i> way is to use NSString's <code>+stringWithContentsOfURL:</code> method. However, this is a modal call, and your application will be non-responsive while it runs. You can either move it to a background thread, or use the NSURLConnection class to make a proper, asynchronous request.</p>
|
Groovlet in Grails apps <p>How do I drop a Groovlet into a Grails app? Say, for example, in web-app/groovlet.groovy</p>
<pre>
import java.util.Date
if (session == null) {
session = request.getSession(true);
}
if (session.counter == null) {
session.counter = 1
}
println """
<html>
<head>
<title>Groovy Servlet</title>
</head>
<body>
Hello, ${request.remoteHost}: Counter: ${session.counter}! Date: ${new Date()}
<br>
"""
</pre>
|
<ol>
<li><code>grails install-templates</code></li>
<li>Edit <code>src/templates/web/web.xml</code> to include your groovlet</li>
<li><code>grails war</code></li>
<li>deploy</li>
</ol>
<p>I've not personally done this to incorporate a groovlet, but this is the documented way to modify the deployed Grails <code>web.xml</code></p>
|
Get MultiView like behavior with ASP.NET MVC <p>I am trying to build a generic form submission system using ASP.NET MVC. I'd like to make it as easy as possible to create forms with a form view and a "success" view. Using the WebForms method, this was easy and could be accomplished with templates or multiviews. With MVC, I'm a bit stuck.</p>
<p>Here's what I'd like to emulate:</p>
<pre><code><% if (formNotSubmitted) { %>
<% Html.BeginForm(...); %>
<%= Html.TextBox("FirstName") %>
<%= Html.TextBox("LastName") %>
<input id='submit' type='submit' value='Submit' />
<%= Html.ValidationSummary %>
<% Html.EndForm(); %>
<% } else { %>
<p>Thank you!</p>
<p><img src='thanks.jpg' /></p>
<p>Other items here maybe.</p>
<% } %>
</code></pre>
<p>Ideally, I'd like to use Ajax, but also have it work with a straight POST. I'd also like to wrap this somehow to avoid the "if..else" code. What makes this harder than a typical ASP.NET MVC Ajax form is that the controller won't know what the success message/content is supposed to be. Most demos I've seen have the controller send back a message, but I need that code in the view.</p>
<p>Any guidance is appreciated.</p>
|
<p>You could it with the Controller</p>
<pre><code>[AcceptVerbs("GET")]
public ActionResult Signup( )
{
// somecode that builds an html string
ViewData["form"] = htmlStringYouBuilt;
}
[AcceptVerbs("POST")]
public ActionResult Login( string username, string password )
{
// etc
}
then in the view
<%= ViewData["form"] %>
</code></pre>
<p>I've been able to use this technique successfully.</p>
|
How is profiling different from logging? <p>How is profiling different from logging?</p>
<p>Is it just that profiling is used for performance measurements to see how long each function takes? Or am I off?</p>
<p>Typically, how are profiling libraries used?</p>
<p>What types of stats are obtained by profiling?</p>
|
<p>Logging tells you <em>what</em> happened. It's great for forensics and debugging.</p>
<p>Profiling quantifies that: it tells you how much time your code spent in each area, or how many times a body of code was executed. It helps you improve your code's performance.</p>
<p>Profiling typically operates at the level of a line of code, a function call, or sometimes a file. For each level, it can typically tell you:</p>
<ul>
<li><p><em>How many times</em> the unit was executed. It's generally less important to optimize rarely-used code than code that executes millions of times. One exception is code that makes a user (or another process) wait for it to complete.</p></li>
<li><p>How many times a <em>branch</em> was taken, say in an <code>if</code> or <code>switch</code> statement. Again, you typically care most about optimizing often-used code.</p></li>
<li><p><em>How much time</em> was spent <em>in a particular function</em>. <strong>Warning:</strong> even experienced developers are often surprised by these results. It's very difficult to predict where your "time sinks" are.</p></li>
<li><p><em>How much time</em> was spent in a function <em>and all functions called within that function</em>. Maybe it's not the function itself, but its children, that need optimizing.</p></li>
<li><p><em>How many times</em> the unit was called <em>by each caller</em>. You may find that a particular function is called primarily from an unexpected place.</p></li>
</ul>
<p>Armed with the data from a good profiler, you can often gain significant improvements in performance with relatively little effort.</p>
|
Multi Column Listbox <p>Is there a way to bind a Generic List to a multicolumn listbox, yes listbox...I know but this is what I am stuck with and can't add a grid or listview.</p>
<p>Thanks</p>
|
<p>You could bind a list to a listbox like this:</p>
<pre><code>List<int> list = new List<int> { 1, 2, 4, 8, 16 };
listBox1.DataSource = list;
</code></pre>
<p>As for multicolumn listbox documentation says <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.multicolumn.aspx" rel="nofollow">ListBox.MultiColumn</a> only places items into as many columns as are needed to make vertical scrolling unnecessary. </p>
<p>If you want to show several columns of information for which an entire row will get selected you could use <a href="http://www.codeproject.com/KB/combobox/multicolumnlistbox.aspx" rel="nofollow">Multi Column List Box</a> by Chris Rickard.</p>
|
What features make a site "social"? <p>If you are trying to position your web application as "social" (or Web 2.0), what are the top features you should implement?</p>
<p>A decent starting point is <a href="http://www.marketingeric.com/12/10-features-every-social-website-should-have/" rel="nofollow">this page</a>, but even this perhaps goes a little too far (I think the bar is likely lower).</p>
|
<p>This strikes me as putting the cart before the horse. Work out what features will be useful to users, and implement those. If people deem the result to be "social" then so be it. If they don't, but it's still useful and popular, what's the problem?</p>
|
What are the ways to obtain HDD serial number without WMI? <p>I can get the HDD serial number using <code>ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia")</code>, and for each <code>ManagementObject</code> from the result set I can read the serial number.</p>
<p>I am interested in another way of obtaining this information (without WMI) for IDE and SATA HDD, since I get mixed results with my current approach.</p>
<p><strong>Edit</strong> - It seems that the only alternative is using <code>DeviceIoControl</code>. Can anyone point me to a full example of C# code invoking <code>DeviceIoControl</code>? I have no experience using <code>P/Invoke</code>.</p>
<p>Environment: C# 2.0, Windows 2000 or newer.</p>
|
<p><a href="http://www.winsim.com/diskid32/" rel="nofollow">http://www.winsim.com/diskid32/</a></p>
|
Copying content from a hidden or clipped window in XP? <p>I need to copy the content of a window (BitBlt) which is hidden, to another window. The problem is that once I hide the source window, the device context I got isn't painted anymore.</p>
|
<p>What you need is the <a href="http://msdn.microsoft.com/en-us/library/ms535695.aspx">PrintWindow</a> function that's available in Win32 API since Windows XP. If you need it to work with older versions of Windows, you can try <a href="http://msdn.microsoft.com/en-us/library/ms534856(VS.85).aspx">WM_PRINT</a>, although I've never been able to make it work.</p>
<p>There's a nice article <a href="http://msdn.microsoft.com/en-us/library/ms997649.aspx">here</a> that shows how to use PrintWindow, and here's the relevant code snippet from that article:</p>
<pre><code>// Takes a snapshot of the window hwnd, stored in the memory device context hdcMem
HDC hdc = GetWindowDC(hwnd);
if (hdc)
{
HDC hdcMem = CreateCompatibleDC(hdc);
if (hdcMem)
{
RECT rc;
GetWindowRect(hwnd, &rc);
HBITMAP hbitmap = CreateCompatibleBitmap(hdc, RECTWIDTH(rc), RECTHEIGHT(rc));
if (hbitmap)
{
SelectObject(hdcMem, hbitmap);
PrintWindow(hwnd, hdcMem, 0);
DeleteObject(hbitmap);
}
DeleteObject(hdcMem);
}
ReleaseDC(hwnd, hdc);
}
</code></pre>
<p>I should have some Python code that uses wxPython to achieve the same thing. Drop me a note if you want it.</p>
|
Algorithm: Voyage planning <p>I need to plan a voyage connecting n locations in the sea with a specified origin and specified destination with following constraints.<br />
The voyage has to touch all locations.<br />
If there is a reservation from A to B then a has to be touched before B <br />
The time spend at each location varies (depends upon the reservations to that location)<br />
Each location has a working window. If the vessel reaches before working window it has to wait.<br />
Note: "Minimum spanning tree" algorithms may not be as the time required at each port depends on the previous route (due to working window)<br />
Is there any algorithm available for this?</p>
|
<p>See <a href="http://en.wikipedia.org/wiki/Travelling_salesman_problem" rel="nofollow">Traveling salesman problem</a></p>
|
Display Ajax Loader while page rendering <p>This is probably a simple question but how can I best use an AJAX loader in ASP.NET to provide a loading dialog whilst the page is being built?</p>
<p>I currently have an UpdatePanel with an associated UpdateProgressPanel which contains the loading message and gif in a ProgressTemplate. </p>
<p>Currently I have a page that onLoad() goes and gets the business entities and then displays them. While it is doing this I would like to display an AJAX loader. </p>
<p>Would it be better to have nothing in the page load and have a hidden button that is triggered onLoadComplete or unLoad() which would then wait for the button click method to complete displaying the UpdateProgressPanel? </p>
|
<p>You can do it in HTML outside of .Net. In your ASPX page you have code like:</p>
<pre>
<div id="loading"><br />
<!-- Animated GIF or other indication that stuff is happening --><br />
</div>
</pre>
<p>At the very bottom of your page, right before the you can have a code snippet that looks like this:</p>
<pre>
<script language="javascript"><br >
document.getElementById("loading").style.display = "none";<br />
</script>
</pre>
<p>The graphic--- as long as it's at the top of the page--- will render first. Then all of your onLoad stuff will happen, and finally the inline JavaScript will happen last since it's at the bottom of the page.</p>
<p>A lot of times I'll disable the buttons in their unloaded state and enable them in that bottom JavaScript too. That prevents the user from getting click happy and triggering events before the page is ready.</p>
|
How can I change the size of scroll box(thumb) of a CScrollBar? <p>I can't find any method to change it. Any help will be appreciated!</p>
|
<p>The size of the scroll box is controlled by the range and page size of the scroll bar. You can use the <a href="http://msdn.microsoft.com/en-us/library/092c3690.aspx" rel="nofollow"><code>CScrollBar::SetScrollInfo</code></a> function to control these settings, specifically the <code>nMin</code>, <code>nMax</code>, and <code>nPage</code> members of the <a href="http://msdn.microsoft.com/en-us/library/bb787537.aspx" rel="nofollow"><code>SCROLLINFO</code></a> structure.</p>
<p>You can find more information on scroll bars on <a href="http://msdn.microsoft.com/en-us/library/bb787527.aspx" rel="nofollow">this page</a> in MSDN - read the "Scroll Box Position and Scrolling Range" section.</p>
|
Rails meta plugin install script? <p>I wanna see if there is an approach to pack a few plugins together as a meta plugin that install everything together automatically, works like a project template.</p>
<p>Why not a script? Because I want to put it in github so I don't have to worry about it when I am not with my own PC :) but of coz a script based solution is welcomed too.</p>
|
<p>My solution (ruby script):</p>
<pre><code>plugins = %w{
http://url_to_plugin_1
http://url_to_plugin_2
http://url_to_plugin_3
http://url_to_plugin_4
http://url_to_plugin_5
}
plugins.each do | p |
`ruby script/plugin install -x #{p}`
end
</code></pre>
<p>run from project root directory</p>
|
Is mutation testing useful in practice? <p>Do you have any examples of real life applications of mutation testing? Does it work better than simple test coverage tools? Or is it useless?</p>
<p>What are the advantages/disadvantages of mutation testing in the real world?</p>
|
<p>The usefulness of unit tests is no longer discussed. They are essential in conception of a quality application. But, how can we assess their relevance?
A code coverage indicator up to 100% doesnât mean the code is 100% tested. This is just a view of executed code during unit tests execution.
Mutation testing will allow you to have more confidence in your tests.</p>
<p>This is a two step process:</p>
<ol>
<li>Generate mutants.</li>
<li>Check that the mutations are found by the tests.</li>
</ol>
<p>I wrote a entire <a href="http://blog.octo.com/en/mutation-testing-a-step-further-to-the-perfection/">article</a> about this process, including some concrete cases.</p>
|
Downsides to using Int64 universally instead of int (C#) <p>We use a base entity with properties such as version (datetime needed for NHibernate) and guid (as key).</p>
<p>It also has an Id (int) field with two functions. Firstly to relate to legacy application key if there is one. Secondly as a shorthand code: for instance files are sometimes created based on these which would look ugly and long using our guid key. My question is not really about pros and cons of base entities but about up-typing this Id to Int64?</p>
<p>It would not affect how it is stored within our MS SQL Server database. Would it have more cost in our cache and memory?. Is this really that much of a worry?</p>
<p>I am interested to hear other downsides besides performance. Consider also these values will probably be exposed through web services to third parties in time too.</p>
<p>The alternative is to deal with the exceptions of larger integers as they arise and implement them specifically in derived entities. The downside is this would need to be done in code and what would we do when we discover some cases when in production of larger integers? There would of course be input validation to stop actual errors but it may restrict expanding data.</p>
|
<p>If your app is running on a 64 bit CPU then probably not much difference at all.</p>
<p>On a 32 bit CPU, a 64 bit integer will be more processor intensive to perfom calculations with.</p>
<p>There is also the obvious memory use.</p>
|
How to set the PYTHONPATH in Emacs? <p>Emacs does not recognize my correct python path. I think it is a general problem with emacs not recognizing my environment variables. I have GNU Emacs 22.1.1 (i386-apple-darwin8.9.1, Carbon Version 1.6.0) of 2007-06-17 installed.</p>
<p>I have set the PYTHONPATH in my ~/.bashrc. Maybe I should set it somewhere else?</p>
|
<p><code>.bashrc</code> only gets read when a shell starts; it won't affect Carbon Emacs. Instead, use <code>setenv</code> in your <code>.emacs</code>:</p>
<pre><code>(setenv "PYTHONPATH" "PATH_STRING_HERE")
</code></pre>
<p>You can set <code>PYTHONPATH</code> for the entire Mac OS session, by adding it to <code>~/.MacOSX/environment.plist</code> (more <a href="http://developer.apple.com/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html#//apple_ref/doc/uid/20002093-113982">here</a>). You probably don't want to do this unless you have XCode (and its property list editor) installed.</p>
<p>(<a href="http://procrastiblog.com/2007/07/09/changing-your-path-in-emacs-compilation-mode/">Via Procrastiblog</a>)</p>
|
ASP.NET Session State Server - Saving Unserialized Data <p>As you know, in ASP.NET, you can store session data in one of following three modes:</p>
<ul>
<li>InProc</li>
<li>Session State </li>
<li>SQL Server</li>
</ul>
<p>For InProc mode, you can store any kind of data objects even it's not serializable. However, in Session State and SQL Server modes, you can only store serialized data. </p>
<p>In my project, I have a ready made portal which use "InProc" mode to store its session. I need to use Session State instead due to some scalability and failure handling issues. </p>
<p>The problem that this portal is internally storing unserialized objects in the session context (i.e The stored objects doesn't implement ISerializable interface). I have no access to their code. Is there any work around so that I can be able to store the session objects in State Server without changing their code. I still have access to their web.config file if this would help in any kind.</p>
|
<p>AFAIK, the simple answer is no. If you don't mind changing your code, you could inject a wrapper object between the actual object and yours, and make your wrapper deal with serializing the wrapped object (essentially as a serialization surrogate) - but by then it would almost be easier to simply re-write the code...</p>
<p>What sort of objects are they? Typically, objects for session-state would be simple data classes, so there shouldn't be too much issue serializing them?</p>
|
Can I find out which control events will fire on an ASP postback? <p>Is it possible to get a list of control events that are going to fire before they happen, say inside the <code>Page_Load</code> handler?</p>
<p>For example if a button was clicked can I figure this out before the <code>button_click</code> event handler is called?</p>
|
<p>Unfortunately, interrogating the __EVENTTARGET value won't do the trick. Often, that value will be empty. The postback processing makes some decisions about what events to raise based on more than just the event target value (if any) testing control state values against the values posted by the form (such as for a textbox) determines whether events like TextChanged should be raised.</p>
<p>Aside from actually hooking up an event handler to all the controls you wish to capture events for, I don't think there is any way to determine it. It might be possible to do basically what the framework does though. You would need to do it between when the controls have been created and viewstate has been restored but before the posted values are processed. You could compare the current control values (from viewstate) with the posted values, essentially determining what events <em>would</em> fire.</p>
<p>What is your goal with this? Perhaps there is a better solution.</p>
|
Passing input to a state machine (c#) <p>I'll try to explain my scenario as best i can;</p>
<p>At each application <em>tick</em> I query the current state of the keyboard and mouse and wrap them in individual classes and data structures. For the keyboard it's an array of my <em>Keys</em> enum (one item for each of the keys that are currently pressed) and for the mouse it's a class containing coordinate delta's and bools for each buttons pressed.</p>
<p>I also have a rudimentary state machine managed via a state manager class which maintains the stack and marshalls the states.</p>
<p>All I want to know is, how best to pass the input (snapshots) to the individual states my app can be in at any one time?</p>
<p>I would like to process as much of the input as possible away from the individual states, so as to reduce repeating logic within the states.</p>
<p>Or would it be better to keep the input snapshots as pure as possible and pass them to the states so they can keep they're input-specific-logic hidden?</p>
<p><strong>Note</strong><br/>
This structure is similiar to how I imagine a game would work, and although this application is not a game it does need to be processed as quickly as possible.</p>
|
<p>Why are you querying the state of the keyboard and mouse with each tick? A much better and traditional solution would be to capture events fired from the keyboard and mouse. That way you only need to update the state when you HAVE to.</p>
|
What are some useful PHP Idioms? <p>I'm looking to improve my PHP coding and am wondering what PHP-specific techniques other programmers use to improve productivity or workaround PHP limitations.</p>
<p>Some examples:</p>
<ol>
<li><p>Class naming convention to handle namespaces: <code>Part1_Part2_ClassName</code> maps to file <code>Part1/Part2/ClassName.php</code></p></li>
<li><p><code>if ( count($arrayName) ) // handles $arrayName being unset or empty</code></p></li>
<li><p>Variable function names, e.g. <code>$func = 'foo'; $func($bar); // calls foo($bar);</code></p></li>
</ol>
|
<p>Ultimately, you'll get the most out of PHP first by learning generally good programming practices, before focusing on anything PHP-specific. Having said that...</p>
<hr>
<h2>Apply liberally for fun and profit:</h2>
<ol>
<li><p>Iterators in foreach loops. There's almost never a wrong time.</p></li>
<li><p>Design around class autoloading. Use <code>spl_autoload_register()</code>, not <code>__autoload()</code>. For bonus points, have it scan a directory tree recursively, then feel free to reorganize your classes into a more logical directory structure.</p></li>
<li><p>Typehint everywhere. Use assertions for scalars.</p>
<pre><code>function f(SomeClass $x, array $y, $z) {
assert(is_bool($z))
}
</code></pre></li>
<li><p>Output something other than HTML.</p>
<pre><code>header('Content-type: text/xml'); // or text/css, application/pdf, or...
</code></pre></li>
<li><p>Learn to use exceptions. Write an error handler that converts errors into exceptions.</p></li>
<li><p>Replace your <code>define()</code> global constants with class constants.</p></li>
<li><p>Replace your Unix timestamps with a proper <code>Date</code> class.</p></li>
<li><p>In long functions, <code>unset()</code> variables when you're done with them.</p></li>
</ol>
<hr>
<h2>Use with guilty pleasure:</h2>
<ol>
<li><p>Loop over an object's data members like an array. Feel guilty that they aren't declared private. This isn't some heathen language like Python or Lisp.</p></li>
<li><p>Use output buffers for assembling long strings.</p>
<pre><code>ob_start();
echo "whatever\n";
debug_print_backtrace();
$s = ob_get_clean();
</code></pre></li>
</ol>
<hr>
<h2>Avoid unless absolutely necessary, and probably not even then, unless you really hate maintenance programmers, and yourself:</h2>
<ol>
<li><p>Magic methods (<code>__get</code>, <code>__set</code>, <code>__call</code>)</p></li>
<li><p><code>extract()</code></p></li>
<li><p>Structured arrays -- use an object</p></li>
</ol>
|
Oracle PL/SQL Query Order By issue with Distinct <p>Does anyone know what is wrong with this query?</p>
<pre><code> SELECT DISTINCT c.CN as ClaimNumber,
a.ItemDate as BillReceivedDate, c.DTN as
DocTrackNumber
FROM ItemData a,
ItemDataPage b,
KeyGroupData c
WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
AND a.ItemNum = b.ItemNum
AND b.ItemNum = c.ItemNum
ORDER BY a.DateStored DESC;
</code></pre>
<p>I have done T-Sql most of my career and this looks correct to me, however this query is for an Oracle database and Toad just places the cursor on the a.DateStored in the Order By section. I'm sure this is elementary for anyone doing PL/SQL.</p>
<p>Thanks!</p>
<p>[EDIT] For future reference, the error given by SQL*Plus was: "ORA-01791: not a SELECTed expression" </p>
|
<p>You will need to modify the query as such:</p>
<pre><code>SELECT DISTINCT c.CN as ClaimNumber,
a.ItemDate as BillReceivedDate, c.DTN as
DocTrackNumber, a.DateStored
FROM ItemData a,
ItemDataPage b,
KeyGroupData c
WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
AND a.ItemNum = b.ItemNum
AND b.ItemNum = c.ItemNum
ORDER BY a.DateStored DESC;
</code></pre>
<p>When doing a DISTINCT your order by needs to be one of the selected columns.</p>
|
adodb and access changing ® to î <p>i connecting to a access database with php and adodb. Strings with characters like ® are saved in the database as î .
What can i do to store it correctly?</p>
|
<p>Looks like you're passing in a UTF8 string but you're not storing it as UTF8. Change it one way or the other so they match up (preferably change your database to UTF8).</p>
|
How to fake a validation error in a MonoRail controller unit-test? <p>I am running on Castle's trunk, and trying to unit-test a controller-action where validation of my DTO is set up. The controller inherits from SmartDispatcherController. The action and DTO look like:</p>
<pre><code>
[AccessibleThrough(Verb.Post)]
public void Register([DataBind(KeyReg, Validate = true)] UserRegisterDto dto)
{
CancelView();
if (HasValidationError(dto))
{
Flash[KeyReg] = dto;
Errors = GetErrorSummary(dto);
RedirectToAction(KeyIndex);
}
else
{
var user = new User { Email = dto.Email };
// TODO: Need to associate User with an Owning Account
membership.AddUser(user, dto.Password);
RedirectToAction(KeyIndex);
}
}
public class UserRegisterDto
{
[ValidateNonEmpty]
[ValidateLength(1, 100)]
[ValidateEmail]
public string Email { get; set; }
[ValidateSameAs("Email")]
public string EmailConfirm { get; set; }
[ValidateNonEmpty]
public string Password { get; set; }
[ValidateSameAs("Password")]
public string PasswordConfirm { get; set; }
// TODO: validate is not empty Guid
[ValidateNonEmpty]
public string OwningAccountIdString { get; set; }
public Guid OwningAccountId
{
get { return new Guid(OwningAccountIdString); }
}
[ValidateLength(0, 40)]
public string FirstName { get; set; }
[ValidateLength(0, 60)]
public string LastName { get; set; }
}
</code></pre>
<p>The unit test looks like:</p>
<pre><code>
[Fact]
public void Register_ShouldPreventInValidRequest()
{
PrepareController(home, ThorController.KeyPublic, ThorController.KeyHome, HomeController.KeyRegister);
var dto = new UserRegisterDto { Email = "ff" };
home.Register(dto);
Assert.True(Response.WasRedirected);
Assert.Contains("/public/home/index", Response.RedirectedTo);
Assert.NotNull(home.Errors);
}
</code></pre>
<p>("home" is my HomeController instance in the test; home.Errors holds a reference to an ErrorSummary which should be put into the Flash when there's a validation error).</p>
<p>I am seeing the debugger think that dto has no validation error; it clearly should have several failures, the way the test runs.</p>
<p>I have read <a href="http://joeydotnet.com/blog/archive/2007/10/25/monorail-controller-test-analysis---problem-and-resolution.aspx" rel="nofollow">Joey's blog post on this</a>, but it looks like the Castle trunk has moved on since this was written. Can someone shed some light, please?</p>
|
<p><a href="http://www.candland.net/blog/2008/07/09/WhatsNeededForCastleValidationToWork.aspx" rel="nofollow">http://www.candland.net/blog/2008/07/09/WhatsNeededForCastleValidationToWork.aspx</a> would appear to contain an answer.</p>
|
How can I automate running commands remotely over SSH? <p>I've searched around a bit for similar questions, but other than running one command or perhaps a few command with items such as:</p>
<pre><code>ssh user@host -t sudo su -
</code></pre>
<p>However, what if I essentially need to run a script on (let's say) 15 servers at once. Is this doable in bash? In a perfect world I need to avoid installing applications if at all possible to pull this off. For argument's sake, let's just say that I need to do the following across 10 hosts:</p>
<ol>
<li>Deploy a new Tomcat container</li>
<li>Deploy an application in the container, and configure it</li>
<li>Configure an Apache vhost</li>
<li>Reload Apache</li>
</ol>
<p>I have a script that does all of that, but it relies on me logging into all the servers, pulling a script down from a repo, and then running it. If this isn't doable in bash, what alternatives do you suggest? Do I need a bigger hammer, such as Perl (Python might be preferred since I can guarantee Python is on all boxes in a RHEL environment thanks to yum/up2date)? If anyone can point to me to any useful information it'd be greatly appreciated, especially if it's doable in bash. I'll settle for Perl or Python, but I just don't know those as well (working on that). Thanks!</p>
|
<p>You can run a local script as shown by che and Yang, and/or you can use a Here document:</p>
<pre><code>ssh root@server /bin/sh <<\EOF
wget http://server/warfile # Could use NFS here
cp app.war /location
command 1
command 2
/etc/init.d/httpd restart
EOF
</code></pre>
|
Assign auto-incrementing value to new column in Oracle <p>I have this table in an Oracle DB which has a primary key defined on 3 of the data columns. I want to drop the primary key constraint to allow rows with duplicate data for those columns, and create a new column, 'id', to contain an auto-incrementing integer ID for these rows. I know how to create a sequence and trigger to add an auto-incrementing ID for new rows added to the table, but is it possible to write a PL/SQL statement to add unique IDs to all the rows that are already in the table?</p>
|
<p>Once you have created the sequence:</p>
<pre><code>update mytable
set id = mysequence.nextval;
</code></pre>
|
Why are hidden form elements still read by JAWS? <p><strong>The Situation</strong></p>
<p>I have an area of the screen that can be shown and hidden via JavaScript (something like "show/hide advanced search options"). Inside this area there are form elements (select, checkbox, etc). For users using assistive technology like a screen-reader (in this case JAWS), we need to link these form elements with a label or use the "title" attribute to describe the purpose of each element. I'm using the title attribute because there isn't enough space for a label, and the tooltip you get is nice for non-screen-reader users.</p>
<p>The code looks something like this:</p>
<pre><code><div id="placeholder" style="display:none;">
<select title="Month">
<option>January</option>
<option>February</option>
...
</select>
</div>
</code></pre>
<p><strong>The Problem</strong></p>
<p>Normally, JAWS will not read hidden elements... because well, they're hidden and it knows that. However, it seems as though if the element has a title set, JAWS reads it no matter what. If I remove the title, JAWS reads nothing, but obviously this is in-accessible markup.</p>
<p><strong>Possible Solutions</strong></p>
<p>My first thought was to use a hidden label instead of the title, like this:</p>
<pre><code><div id="placeholder" style="display:none;">
<label for="month" style="display:none">Month</label>
<select id="month">...</select>
</div>
</code></pre>
<p>This results in the exact same behavior, and now we lose the tool-tips for non-screen-reader users. Also we end up generating twice as much Html.</p>
<p>The second option is to still use a label, put position it off the screen. That way it will be read by the screen-reader, but won't be seen by the visual user:</p>
<pre><code><div id="placeholder" style="display:none;">
<label for="month" style="position:absolute;left:-5000px:width:1px;">Month</label>
<select id="month">...</select>
</div>
</code></pre>
<p>This actually works, but again we lose the tool-tip and still generate additional Html.</p>
<p>My third possible solution is to recursively travel through the DOM in JavaScript, removing the title when the area is hidden and adding it back when the area is shown. This also works... but is pretty ugly for obvious reasons and doesn't really scale well to a more general case.</p>
<p>Any other ideas anyone? Why is JAWS behaving this way?</p>
|
<p>This definitely looks like a bug in JAWS as the spec definitively states that display:none should cause an element and its children not to be displayed in any media.</p>
<p>However, playing with the speak: aural property might be useful? I don't know as I don't have JAWS available.</p>
<p><a href="http://www.w3.org/TR/CSS2/aural.html#speaking-props" rel="nofollow">http://www.w3.org/TR/CSS2/aural.html#speaking-props</a></p>
|
VB.NET Importing Classes <p>I've seen some code where a <em>Class</em> is imported, instead of a namespace, making all the static members/methods of that class available. Is this a feature of VB? Or do other languages do this as well?</p>
<p>TestClass.vb</p>
<pre><code>public class TestClass
public shared function Somefunc() as Boolean
return true
end function
end class
</code></pre>
<p>MainClass.vb</p>
<pre><code>imports TestClass
public class MainClass
public sub Main()
Somefunc()
end sub
end class
</code></pre>
<p>These files are in the App_Code directory. Just curious, because I've never thought of doing this before, nor have I read about it anywhere. </p>
|
<p>One of the reasons this feature is in place is to emulate Visual Basic 6.0's GlobalMultiUse Option for Instancing. Visual Basic 6.0 doesn't have the ability to make modules public across a DLL boundary. Instead you set the instancing property to <code>GlobalMultiUse</code>. It is used mainly for utility classes like a class that export a series of math functions.</p>
<p>Every time you call a subroutine or function on a class with the <code>GlobalMultiUse Instancing</code>, Visual Basic 6.0 instantiates a class behind the scenes before calling the function.</p>
<p>It can be abused to generate global functions/variables with all the advantages and disadvantages.</p>
|
Apache Abdera Client - Posting/Putting <p>Looking for help using the Apache Abdera Atom Client. I am trying to post and put files to a feed but I am getting a 400 error saying that the content type must be <code>application/x-www-form-urlencoded</code> or <code>multipart/form-data</code></p>
|
<p>You need to check where you are posting too. Abdera is used to post ATOM-XML format. It looks like you try to post to the same URL your web form is posting to, which would be a HTML submission a.k.a. <code>x-www-form-urlencoded</code>. Check with the blog server software if and where they support the ATOM publishing protocol.</p>
|
Strange error when creating Excel files with Spreadsheet_Excel_Writer <p>Here's the code. Not much to it. </p>
<pre><code><?php
include("Spreadsheet/Excel/Writer.php");
$xls = new Spreadsheet_Excel_Writer();
$sheet = $xls->addWorksheet('At a Glance');
$colNames = array('Foo', 'Bar');
$sheet->writeRow(0, 0, $colNames, $colHeadingFormat);
for($i=1; $i<=10; $i++)
{
$row = array( "foo $i", "bar $i");
$sheet->writeRow($rowNumber++, 0, $row);
}
header ("Expires: " . gmdate("D,d M Y H:i:s") . " GMT");
header ("Last-Modified: " . gmdate("D,d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
$xls->send("test.xls");
$xls->close();
?>
</code></pre>
<p>The issue is that I get the following error when I actually open the file with Excel:</p>
<pre><code>File error: data may have been lost.
</code></pre>
<p>Even stranger is the fact that, despite the error, the file seems fine. Any data I happen to be writing is there.</p>
<p>Any ideas on how to get rid of this error?</p>
<p><hr /></p>
<h3>Edit</h3>
<p>I've modified the code sample to better illustrate the problem. I don't think the first sample was a legit test.</p>
|
<p>The code in the question has a bug which causes the error.</p>
<p>This line writes a bunch of column names to row 0</p>
<pre><code>$sheet->writeRow(0, 0, $colNames, $colHeadingFormat);
</code></pre>
<p>Then we have the loop which is supposed to write out the value rows.</p>
<pre><code>for($i=1; $i<=10; $i++)
{
$row = array( "foo $i", "bar $i");
$sheet->writeRow($rowNumber++, 0, $row);
}
</code></pre>
<p>The problem is that <strong>$rowNumber</strong> isn't declared anywhere so it overwrites row 0 on the first pass through the loop.</p>
<p>This overwriting seems to cause an issue with Excel Writer.</p>
<p>The strange thing is that, on the Excel file that gives the error, you still see the row with the column names even though it's technically been overwritten.</p>
<p>I found the solution <a href="http://groups.google.com/group/spreadsheet-writeexcel/browse_thread/thread/6656856820b6f799/">here on Google Groups</a>. Scroll down to the bottom. It's the last post by <strong>Micah</strong> that mentions the issue.</p>
<p><hr /></p>
<p>And here's the fix</p>
<pre><code><?php
include("Spreadsheet/Excel/Writer.php");
$xls = new Spreadsheet_Excel_Writer();
$rowNumber = 0;
$sheet = $xls->addWorksheet('At a Glance');
$colNames = array('Foo', 'Bar');
$sheet->writeRow($rowNumber, 0, $colNames, $colHeadingFormat);
for($i=1; $i<=10; $i++)
{
$rowNumber++;
$row = array( "foo $i", "bar $i");
$sheet->writeRow($rowNumber, 0, $row);
}
header ("Expires: " . gmdate("D,d M Y H:i:s") . " GMT");
header ("Last-Modified: " . gmdate("D,d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
$xls->send("test.xls");
$xls->close();
?>
</code></pre>
|
Does silverlight code need protection? <p>I don't quite understand how Silverlight code works within the browser. Are the assemblies downloaded to the client machine? Is there any chance of the code getting decompiled using Reflector or some similar tool? If so, what options does one have to protect the code? Do .net obfuscators work with Silverlight?</p>
|
<p>Whenever you are in a web browser, all client side code is downloaded to the machine and can be examined by the user. This goes for Javascript, Flash, and Silverlight.</p>
<p>If you have proprietary code that absolutely must be hidden then you need to put it on the server and expose an API that the clients can call to show information to the user.</p>
|
Creating a System.Web.Caching.Cache object in a unit test <p>I'm trying to implement a unit test for a function in a project that doesn't have unit tests and this function requires a System.Web.Caching.Cache object as a parameter. I've been trying to create this object by using code such as...</p>
<pre><code>System.Web.Caching.Cache cache = new System.Web.Caching.Cache();
cache.Add(...);
</code></pre>
<p>...and then passing the 'cache' in as a parameter but the Add() function is causing a NullReferenceException. My best guess so far is that I can't create this cache object in a unit test and need to retrieve it from the HttpContext.Current.Cache which I obviously don't have access to in a unit test.</p>
<p>How do you unit test a function that requires a System.Web.Caching.Cache object as a parameter?</p>
|
<p>When I've been faced with this sort of problem (where the class in question doesn't implement an interface), I often end up writing a wrapper with associated interface around the class in question. Then I use my wrapper in my code. For unit tests, I hand mock the wrapper and insert my own mock object into it.</p>
<p>Of course, if a mocking framework works, then use it instead. My experience is that all mocking frameworks have some issues with various .NET classes.</p>
<pre><code>public interface ICacheWrapper
{
...methods to support
}
public class CacheWrapper : ICacheWrapper
{
private System.Web.Caching.Cache cache;
public CacheWrapper( System.Web.Caching.Cache cache )
{
this.cache = cache;
}
... implement methods using cache ...
}
public class MockCacheWrapper : ICacheWrapper
{
private MockCache cache;
public MockCacheWrapper( MockCache cache )
{
this.cache = cache;
}
... implement methods using mock cache...
}
public class MockCache
{
... implement ways to set mock values and retrieve them...
}
[Test]
public void CachingTest()
{
... set up omitted...
ICacheWrapper wrapper = new MockCacheWrapper( new MockCache() );
CacheManager manager = new CacheManager( wrapper );
manager.Insert(item,value);
Assert.AreEqual( value, manager[item] );
}
</code></pre>
<p>Real code</p>
<pre><code>...
CacheManager manager = new CacheManager( new CacheWrapper( HttpContext.Current.Cache ));
manager.Add(item,value);
...
</code></pre>
|
wxPython wxDC object from win32gui.GetDC <p>I am getting a DC for a window handle of an object in another program using win32gui.GetDC which returns an int/long. I need to blit this DC into a memory DC in python. The only thing I can't figure out how to do is get a wxDC derived object from the int/long that win32gui returns. None of the wxDC objects allow me to pass an actual DC handle to them from what I can tell. This of course keeps me from doing my blit. Is there any way to do this?</p>
|
<p>I downloaded the wxWidgets source and dug around, and I think this will work.</p>
<p>You need the handle (HWND) for the external window, not the DC.</p>
<pre><code>window = wx.Frame(None, -1, '')
window.AssociateHandle(hwnd)
dc = wx.WindowDC(window)
</code></pre>
|
Farpoint spreadsheet - disable cell right click menu <p>I'm using Farpoint Spreadsheet for WinForms with C#.
How can I disable the "context menu" displayed when right-clicking over a cell that is being edited?</p>
|
<p>set AutoClipboard property of fpspread component to false</p>
|
Query antivirus definitions date? <p>Is it possible at all to query (WMI?) the virus defnintions date of definitions installed on remote computers? I'd like to start specificially with Symantec Endpoint Protection, and then branch out to other antivirus products.</p>
<p>This is a WinForms, .NET project.</p>
|
<p><strong>Symantec Endpoint Protection</strong></p>
<p>There is no common library in use on operating systems to tell which definitions are in use. However, for each anti virus application you could find out if there's an API to call. Symantec Endpoint Protection goes without, but it stores activities in a Syslog compliant log file (syslog.log). See if that log file contains information about updates and definitions.</p>
<p><strong>Clam AntiVirus</strong></p>
<p><a href="http://stackoverflow.com/questions/194013/anti-virus-integration-with-net-application">http://stackoverflow.com/questions/194013/anti-virus-integration-with-net-application</a></p>
<p><strong>McAfee VirusScan</strong></p>
<p>A powershell script by Ying Li to check against a list of servers for McAfee virus definitions installed.</p>
<p><a href="http://www.myitforum.com/articles/40/view.asp?id=10522" rel="nofollow">http://www.myitforum.com/articles/40/view.asp?id=10522</a></p>
|
What is the proper syntax for a cross-table SQL query? <p>Right now, I have </p>
<pre><code>SELECT gp_id FROM gp.keywords
WHERE keyword_id = 15
AND (SELECT practice_link FROM gp.practices
WHERE practice_link IS NOT NULL
AND id = gp_id)
</code></pre>
<p>This does not provide a syntax error, however for values where it should return row(s), it just returns 0 rows.</p>
<p>What I'm trying to do is get the gp_id from gp.keywords where the the keywords table keyword_id column is a specific value and the practice_link is the practices table corresponds to the gp_id that I have, which is stored in the id column of that table.</p>
|
<p>I'm not even sure that is valid SQL, so I'm surprised it is working at all:</p>
<pre><code>SELECT gp_id
FROM gp.keywords
WHERE keyword_id = 15
AND (SELECT practice_link FROM gp.practices WHERE practice_link IS NOT NULL AND id = gp_id)
</code></pre>
<p>How about this instead:</p>
<pre><code>SELECT kw.gp_id, p.practice_link
FROM gp.keywords AS kw
INNER JOIN gp.practices AS p
ON p.id = kw.gp_id
WHERE kw.keyword_id = 15
</code></pre>
<p>I would steer clear of implicit joins as in the other examples. It only leads to tears later.</p>
|
app GUI similar to Control Panel in Vista <p>I was playing a bit with Windows Vista (still using XP) and I liked how the standard Control Panel worked. Do you think this design is good also for normal applications?</p>
<p>I like the idea of showing main topics with large fonts + icons. Details within each main topic are displayed using a small font and are immediatelly accessible without the need to browse the menu. Probably everybody knows Vista, but anyway, <a href="http://www.computerperformance.co.uk/images/Vista/control_panel2.jpg" rel="nofollow">here</a> is the Control Panel layout.</p>
<p>Compared to a classic layout of icons for main topics and menu for minor topics, the Control Panel GUI seems to be good at first sight.</p>
<p>I haven't seen any app using this kind of GUI, so I don't know if I should rather use the common approach with icons and menu for a common application? Maybe this Control Panel GUI is suitable only for setting some options, other than working with any data?</p>
|
<p>I'm on the fence on this. The old Windows XP layout got cluttered quickly with programs adding their own control panel applets, while the new Windows Vista layout can be annoying to process visually at first. The search feature really helps (though not <a href="http://toastytech.com/guis/osx14control.png" rel="nofollow">nearly as slick as Mac OS X's search</a>) but I'm not a fan of visually laying out something that's better seen in a list into two distinct columns containing the same type of data. In list/details form it's intuitive for a user to sort the items through different attributes. I find this new presentation in the IIS 7 management applet to be particularly troublesome.</p>
|
Duplicate spring configurations being loaded? <p>I'm looking at the output from spring being loaded up by tomcat and there's something very strange...Everything is duplicated. What would cause this? Whatever it is, it's causing my application to run in odd ways.</p>
<p><strong>Additional Info:</strong></p>
<p>The application is a web app. All the spring information is loaded using the context loader(?) defined in the web.xml file. My configuration files are split amoung 6 (or so) files.</p>
<p>Example debug output:</p>
<blockquote>
<p>[DEBUG,DefaultFilterInvocationDefinitionSource,main] Added URL pattern: /<code>**</code>; attributes: [REQUIRES_SECURE_CHANNEL]</p>
<p>[DEBUG,DefaultFilterInvocationDefinitionSource,main] Added URL pattern: /<code>**</code>; attributes: [REQUIRES_SECURE_CHANNEL]</p>
<p>[DEBUG,DefaultFilterInvocationDefinitionSource,main] Added URL pattern: /<code>**</code>; attributes: [ROLE_READ, ROLE_UPDATE]</p>
<p>[DEBUG,DefaultFilterInvocationDefinitionSource,main] Added URL pattern: /<code>**</code>; attributes: [ROLE_READ, ROLE_UPDATE]</p>
<p>[DEBUG,AbstractFallbackMethodDefinitionSource,main] Adding security method [CacheKey[com.service.impl.FooServiceImpl; public abstract java.lang.Boolean com.service.IFooService.saveOrUpdateFoo(com.model.Foo2,java.lang.String) throws org.springframework.dao.DataAccessException]] with attribute [[ROLE_UPDATE]]</p>
<p>[DEBUG,AbstractFallbackMethodDefinitionSource,main] Adding security method [CacheKey[com.service.impl.FooServiceImpl; public abstract java.lang.Boolean com.service.IFooService.saveOrUpdateFoo(com.model.Foo2,java.lang.String) throws org.springframework.dao.DataAccessException]] with attribute [[ROLE_UPDATE]]</p>
<p>[INFO,AbstractSecurityInterceptor,main] Validated configuration attributes</p>
<p>[INFO,AbstractSecurityInterceptor,main] Validated configuration attributes</p>
</blockquote>
|
<p>Are you sure that something in the logging configuration isn't adding each category/logger to the appender more than once?</p>
<p>That's something that's possible with log4j, not sure about JCL or whatever the latest version of Tomcat uses under the cover.</p>
|
C# refreshing textbox from BindingSource <p>I am having difficulty refreshing windows forms controls that are using a BindingSource object. We have a CAB/MVP/SCSF client that I (actually âweâ since it is a team effort) are developing that will interact with WCF services running on a remote server. (This is our first attempt at this, so we are in a learning mode). One of the calls (from the Presenter) to the service returns a DataSet that contains 3 DataTables, named âContractâ, âLoanâ and âTermsâ. Each table contains just one row. When the service returns the dataset, we store it in the SmartPart/View in a class member variable, by calling a function in the view called BindData() and passing the dataset in to the view from the presenter class;</p>
<pre><code>private System.Data.DataSet _ds = null;
public void BindData(System.Data.DataSet ds)
{
string sErr = "";
try
{
_ds = ds; // save to private member variable
// more code goes down here
}
}
</code></pre>
<p>We are trying to bind each of the three DataTables to an assortment of Windows Forms TextBoxes, MaskedEditBoxes, and Infragistics UltraComboEditor Dropdown comboboxes We created three BindingSource objects, one for each DataTable using the VS2008 IDE.</p>
<pre><code>private System.Windows.Forms.BindingSource bindsrcContract;
private System.Windows.Forms.BindingSource bindsrcLoan;
private System.Windows.Forms.BindingSource bindsrcTerms;
</code></pre>
<p>We are binding the values like this</p>
<pre><code>if (bindsrcContract.DataSource == null)
{
bindsrcContract.DataSource = _ds;
bindsrcContract.DataMember = âcontractâ;
txtContract.DataBindings.Add(new Binding("Text", bindsrcContract, "contract_id", true));
txtLateFeeAmt.DataBindings.Add(new Binding("Text", bindsrcContract, "fee_code", true));
txtPrePayPenalty.DataBindings.Add(new Binding("Text", bindsrcContract, "prepay_penalty", true));
txtLateFeeDays.DataBindings.Add(new Binding("Text", bindsrcContract, "late_days", true));
}
if (bindsrcLoan.DataSource == null)
{
bindsrcLoan.DataSource = _ds;
bindsrcLoan.DataMember = âloanâ;
mskRecvDate.DataBindings.Add(new Binding("Text", bindsrcLoan, "receive_date", true));
cmboDocsRcvd.DataBindings.Add(new Binding("Value", bindsrcLoan, "docs", true));
}
</code></pre>
<p>This works when we do the first read from the service and get a dataset back. The information is displayed on the form's controls, we can update it using the form, and then âsaveâ it by passing the changed values back to the WCF service.</p>
<p>Here is our problem. If we select a different loan key and make the same call to the service and get a new DataSet, again with 3 tables with one row each, the controls (textboxes, masked edit boxes, etc.) are not being updated with the new information. Note that the smartPart/View is not closed or anything, but remains loaded in between calls to the service. On the second call we are not rebinding the calls, but simply trying to get the data to refresh from the updated DataSet.</p>
<p>We have tried everything we can think of, but clearly we are missing something. This is our first attempt at using the BindingSource control. We have tried</p>
<pre><code>bindsrcContract.ResetBindings(false);
</code></pre>
<p>and </p>
<pre><code>bindsrcContract.ResetBindings(true);
</code></pre>
<p>and </p>
<pre><code>bindsrcContract.RaiseListChangedEvents = true;
</code></pre>
<p>and </p>
<pre><code>for (int i = 0; i < bindsrcContract.Count; i++)
{
bindsrcContract.ResetItem(i);
}
</code></pre>
<p>As well as resetting the DataMember property again.</p>
<pre><code>bindsrcContract.DataMember = âContractâ;
</code></pre>
<p>Weâve looked at a lot of examples. Many examples make reference to the BindingNavigator but since the DataTables only have one row, we did not think we needed that. There are a lot of examples for grids, but weâre not using one here. Can anyone please point out where we are going wrong, or point us to resources that will provide some more information?</p>
<p>Weâre using VisualStudio 2008, C# and .Net 2.0, XP client, W2K3 server.</p>
<p>Thanks in advance</p>
<p>wes</p>
|
<p>I was having a similar issue today and found this works.</p>
<pre><code>private void btnCancel_Click(object sender, EventArgs e)
{
this.MyTable.RejectChanges();
this.txtMyBoundTextBox.DataBindings[0].ReadValue();
this.EditState = EditStates.NotEditting;
}
</code></pre>
|
What do parentheses in a C variable declaration mean? <p>Can someone explain what this means?</p>
<pre><code>int (*data[2])[2];
</code></pre>
|
<p><strong>What are the parentheses for?</strong></p>
<p>In C brackets [] have a higher precedence than the asterisk *</p>
<p><strong>Good explanation from Wikipedia:</strong></p>
<blockquote>
<p>To declare a variable as being a
pointer to an array, we must make use
of parentheses. This is because in C
brackets ([]) have higher precedence
than the asterisk (*). So if we wish to declare a pointer to an array, we need to supply parentheses to override this:</p>
</blockquote>
<pre><code>double (*elephant)[20];
</code></pre>
<blockquote>
<p>This declares that elephant is a
pointer, and the type it points at is
an array of 20 double values.</p>
<p>To declare a pointer to an array of
pointers, simply combine the
notations.</p>
</blockquote>
<pre><code>int *(*crocodile)[15];
</code></pre>
<p><a href="http://en.wikipedia.org/wiki/C_variable_types_and_declarations">Source</a>.</p>
<p><strong>And your actual case:</strong></p>
<pre><code>int (*data[2])[5];
</code></pre>
<p>data is an array of 2 elements. Each element contains a pointer to an array of 5 ints.</p>
<p>So you you could have in code using your 'data' type:</p>
<pre><code>int (*data[2])[5];
int x1[5];
data[0] = &x1;
data[1] = &x1;
data[2] = &x1;//<--- out of bounds, crash data has no 3rd element
int y1[10];
data[0] = &y1;//<--- compiling error, each element of data must point to an int[5] not an int[10]
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.