input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
SharePoint - Determine the Site Definition used to create a Site Template (.STP) <p>A SharePoint site template is basically a saved version the differences between a Site Definition and the current state of a site. I've read that Site Templates can only be applied to sites that use the same Site Definition that was used to create the template.</p>
<p>If you have an STP file, how do you determine which Site Definition was used to create the Site Template?</p>
| <p>STP files are just ZIP-compressed files. If you rename the extension to *.ZIP you can extract the contents and examine the XML files that will contain the info you are looking for.</p>
<p>I don't have a STP file around so I can't tell you exactly what file to look for but I've done that before and is not that hard to find.</p>
<p>Good luck!</p>
|
Good c++ lib for threading <p>I prefer a lib solely based on pthreads. What is a good c++ lib to for threading?</p>
| <p>How about <a href="http://www.boost.org/doc/libs/1%5F38%5F0/doc/html/thread.html" rel="nofollow">boost threads</a>?</p>
<blockquote>
<p>Boost.Thread enables the use of
multiple threads of execution with
shared data in portable C++ code. It
provides classes and functions for
managing the threads themselves, along
with others for synchronizing data
between the threads or providing
separate copies of data specific to
individual threads.</p>
</blockquote>
|
With Apache httpd, how do I configure no caching for a given UserAgent? <p>I have Apache HTTPD configured to add a cache header to requests for most static content:</p>
<pre><code>ExpiresActive On
ExpiresDefault "access plus 1 year"
# Force JNLP and BSH files to expire immediately so updates are checked for
# and seen (We need this so we see changes in the dynamic content in both)
ExpiresByType application/x-java-jnlp-file "now"
ExpiresByType application/x-bsh "now"
</code></pre>
<p>How can I disable this caching for any request where the <code>UserAgent</code> contains the string JNLP? When the request comes from the User Agent JNLP (for example "<code>User-Agent: JNLP/6.0 javaws/1.6.0_12 (b04) Java/1.6.0_12</code>") I don't want <em>any</em> <code>Cache-Control</code> or other cache-related headers on the HTTP response.</p>
<p>I can find configuration examples for several things based on user agent, but I cannot figure out how to configure caching depending on the user agent.</p>
| <p>Your <code>ExpiresByType</code> directive looks like a good idea... if that's not enough, then try using <code>BrowserMatch</code>:</p>
<pre><code>BrowserMatch JNLP ua_is_jnlp
</code></pre>
<p>This sets the environment variable <code>ua_is_jnlp</code> to some value for any request whose user agent header contains the string <code>JNLP</code> (there is also a case-insensitive variant, <code>BrowserMatchNoCase</code>). Then you can clear any caching headers with</p>
<pre><code>Header unset Cache-Control env=ua_in_jnlp
Header unset Expires env=ua_in_jnlp
</code></pre>
<p>although if you want to disable caching entirely, you'd be better off setting</p>
<pre><code>Header set Cache-Control no-cache env=ua_in_jnlp
Header set Expires 0 env=ua_in_jnlp
</code></pre>
|
How can I get the current network interface throughput statistics on Linux/UNIX? <p>Tools such as MRTG provide network throughput / bandwidth graphs for the current network utilisation on specific interfaces, such as eth0. How can I return that information at the command line on Linux/UNIX?</p>
<p>Preferably this would be without installing anything other than what is available on the system as standard.</p>
| <p><code>iftop does for network usage what top(1) does for CPU usage</code> -- <a href="http://www.ex-parrot.com/~pdw/iftop/">http://www.ex-parrot.com/~pdw/iftop/</a></p>
<p>I don't know how "standard" iftop is, but I was able to install it with <code>yum install iftop</code> on Fedora.</p>
|
Testing document uploads in Development server using json files <p>I just built a small application(using Django) which will accept any jobseeker resumes. So any jobseeker uploads his/her resume in the form provided. How do I test this using testcases. I am used to writing fixtures for my initial data using json files. How would I have the same sort of a thing with doc files? So simply I want to run my testcases on a different set of resumes. How can I achieve this with minimum complexity.</p>
| <p>you can try <a href="http://www.djangosnippets.org/snippets/1300/" rel="nofollow">django fake file uploads</a></p>
|
How can I pass along the Page Number in a HyperLinkField in a GridView? <p>I have gridview that I am using paging on. I want to pass along the current page in a asp:Hyperlink so I can send them back to the current page when they are done viewing the details of a record. Is this possible? If it is how can I do this?</p>
<pre><code><asp:GridView ID="grdObitList" runat="server" allowpaging="true"
PageSize="10" AutoGenerateColumns="false" CssClass="grdClass"
BorderStyle="None" GridLines="None" CellSpacing="2" >
<PagerStyle HorizontalAlign="Center" />
<PagerSettings Position="Bottom" FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" />
<Columns>
<asp:HyperLinkField HeaderText="Name" DataTextField="obit_fullname" DataNavigateUrlFields="obit_id" DataNavigateUrlFormatString="obitDisplay.aspx?oid={0}" />
<asp:BoundField ReadOnly="true" HeaderText="Date" DataField="obit_dod" DataFormatString="{0:d/M/yyyy}" />
<asp:BoundField ReadOnly="true" HeaderText="Resident Of" DataField="obit_resident" />
<asp:BoundField ReadOnly="true" HeaderText="Funeral Home" DataField="obit_funeralhome" />
</Columns>
</code></pre>
<p></p>
| <p>One way to do it is converting it to a template column, that way you can use normal databind syntaxt to get to it (<%#)</p>
|
AS3 How to remove previous loaders <p>In Flash CS4, I'm creating a photo gallery. My goal is to load different thumbnails from a number of images. I have managed that when one clicks an image, a number of thumbnails are being displayed, but when one clicks another image, the new thumbnails are placed on top of the old ones. Can someone help me on how to get rid of the old thumbnails?</p>
<p>Here is the code:</p>
<pre><code>for (var i:int = 0; i < thumbnails.length(); i++) {
imgLoader.unload();
imgLoader = new Loader();
imgLoader.load(new URLRequest(thumbnails[i]));
imgLoader.name= i;
imgLoader.x = 95 * columns;
imgLoader.y = 80 * rows;
imgLoader.alpha = 0;
details.gallery.addChild(imgLoader);
if (columns+1< 5) {
columns++;
} else {
columns = 0;
rows++;
}
}
</code></pre>
| <p>This is where an Array is your friend. You could do this without an array by merely using a while loop to remove every last child from the sprite or movieclip that you added the thumbs to. The reason we use arrays is so that we can reuse the thumbs, instead of reloading them we merely remove them from the display list. You push a reference to each object into an array for each thumb as you add it to the display list. Each thumbContainer node in the XML gets its own array which get added to the main array. The main array holds references to thumbnail arrays. Thumbnail arrays hold references to loaded thumbnails so that they can be added and removed from the display list. If you plan to never use the thumbs after they have been seen once you may set it's reference equal to null, otherwise merely remove it from the display list; There is no reason to load it many times. When you are ready to add the new thumbs you must clear out previous thumbs. The easiest way to do this is with a while loop.</p>
<pre><code>//Assuming the thumbs were loaded into container
while(container.numChildren > 0)
{
//Remove the first child until there are none.
container.removeChildAt(0);
}
//The XML / 2 Containers / thumbContainer[0] and thumbContainer[1]
</code></pre>
<p></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xml>
<thumbContainer>
<thumb path="path/to/file" />
<thumb path="path/to/file" />
<thumb path="path/to/file" />
</thumbContainer>
<thumbContainer>
<thumb path="path/to/file" />
<thumb path="path/to/file" />
<thumb path="path/to/file" />
</thumbContainer>
</xml>
</code></pre>
<p></p>
<pre><code>package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class DocumentClass extends Sprite
{
private var _container:Sprite;
private var _mainArray:Array;
private var _xml:XML;
private var _urlLoader:URLLoader;
private var _urlRequest:URLRequest;
public function DocumentClass():void
{
if(stage) _init();
else addEventListener(Event.ADD_TO_STAGE, _init, false, 0 , true);
}
private function _init(e:Event = null):void
{
//Will contain arrays for each thumbContainer in the XML.
_mainArray = [];
_urlRequest = new URLRequest('path/to/xml');
_urlLoader = new URLLoader();
_urlLoader.addEventListener(Event.COMPLETE, _onXMLComplete, false, 0, true);
}
private function _onXMLComplete(e:Event):void
{
_xml = new XML(e.target.data);
_loadThumbs(0);
}
private function _loadThumbs(pIndex:int):void
{
_clearThumbs();
//Find out how many sets of thumbs there and add to _mainArray
for(var i:int = 0; i < _xml.thumbContainer.length(); i++)
{
var tempArray:Array = new Array();
for(var j:int = 0; j < _xml.thumbContainer[i].thumb.length; j++)
{
tempArray[i].push(_xml.thumbContainer[i].thumb[j].@path);
}
_mainArray.push(tempArray);
}
//Here is where we add the new content to container, or you can call a function to do it.
}
private function _clearThumbs():void
{
while(container.numChildren > 0)
{
//Remove the first child until there are none.
container.removeChildAt(0);
}
}
}
}
</code></pre>
<p>Again, it is good practice to hold a reference to something that is reusable and to simply remove it from the display list instead of setting to null and prepping for garbage collection only to be loaded again later. I already have written more than I intended and wasn't able to slap in all the code I wanted. It is important to setup the code that makes sure it only loads a particular set of thumbs once; That is the whole idea. As for removing them, it's as simple as the while loop I showed you, you just need to know the name of the DisplayObjectContainer that parents them.</p>
|
How to show "busy" dialog (spinning wheel) on Smart Phone <p>Can't find how it is called nor how to pop it up.</p>
<p>My CF application is talking over the web with a web service. Want to show my user some "busy activity" dialog.</p>
<p>Any suggestions how to show the default one from WinMo?</p>
| <p>The following should work...</p>
<pre><code>using System.Windows.Forms;
...
Cursor.Current = Cursors.WaitCursor;
</code></pre>
|
How do I simulate a slow internet connection (Edge/3g) on a mac. Is there a Firefox plugin? <p><strong>Exact Duplicate</strong>: <a href="http://stackoverflow.com/questions/473465/firefox-plugin-to-simulate-slow-internet-connection">http://stackoverflow.com/questions/473465/firefox-plugin-to-simulate-slow-internet-connection</a></p>
<p>How do I simulate a slow internet connection (Edge/3g) on a Mac? Is there a Firefox plugin?</p>
| <p>On a Mac or BSD, use:</p>
<pre><code>sudo ipfw pipe 1 config bw 350kbit/s plr 0.05 delay 500ms
sudo ipfw add pipe 1 dst-port http
</code></pre>
<p>And to reset to your initial settings:</p>
<pre><code>sudo ipfw flush
</code></pre>
|
Problems with using nsIURIContentListener in Firefox Extension <p>I am developing a small extension that has to redirect certain URLs to another Site. It's working fine, except for one situation: if open the Link with "Context-Menu -> Open in new Tab", the current page is redirectet to my page and a second tab opens with the link that should be redirected. What am I making wrong? Is there a better way to achieve what I want?</p>
<pre><code>var myListener =
{
QueryInterface: function(iid)
{
if (iid.equals(Components.interfaces.nsIURIContentListener) ||
iid.equals(Components.interfaces.nsISupportsWeakReference) ||
iid.equals(Components.interfaces.nsISupports))
return this;
throw Components.results.NS_NOINTERFACE;
},
onStartURIOpen: function(aUri)
{
if (check_url(aUri)) {
getBrowser().mCurrentTab.linkedBrowser.loadURI(######REDIRECT IS HERE#############);
return true;
}
return false;
},
doContent: function(aContentType, aIsContentPreferred, aRequest, aContentHandler )
{
throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
},
canHandleContent: function(aContentType, aIsContentPreferred, aDesiredContentType)
{
throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
},
isPreferred: function(aContentType, aDesiredContentType)
{
try
{
var webNavInfo =
Components.classes["@mozilla.org/webnavigation-info;1"]
.getService(Components.interfaces.nsIWebNavigationInfo);
return webNavInfo.isTypeSupported(aContentType, null);
}
catch (e)
{
return false;
}
},
GetWeakReference : function()
{
throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
}
}
</code></pre>
<p>The complete extension can be found here : <a href="http://github.com/bitboxer/firefox-detinyfy" rel="nofollow">http://github.com/bitboxer/firefox-detinyfy</a></p>
| <p>Okay, I did some research. The Hook was a wrong aproach. I changed the code now. Look into the git to find out more...</p>
|
What's the best way to monitor an InputStream? <p>I'm reading a file in via apache.commons.FtpClient.</p>
<p>This works fine 99.9% of the time but sometimes it just dies in the read() method...</p>
<pre><code>InputStream inStream = ftp.retrieveFileStream(path + file.getName());
String fileAsString = "";
if(inStream == null){
return;
}
while((c = inStream.read()) != -1){ //this is where the code sometimes just hangs
fileAsString += Character.valueOf((char)c);
}
</code></pre>
<p>My question is what is the most reliable way to protect against this locking up the system indefinitely. Should I be setting a timer in a separate thread? Or is there a simpler way to do it?</p>
| <p>If your code hangs it means your FTP server has not sent the entire file. You can use a Timer, but I believe FtpClient allows you to set a timeout.</p>
<p>BTW: the way you read the file is <em>very</em> inefficient. If your file is larger than a few K it will use increasing amounts of CPU.</p>
<p>You are creating a Character from a byte (which is a bad idea in itself) and a String object for every byte in the file.</p>
<p>I suggest using the copy method provided or the one which comes with commons-io library to copy the data to a ByteArrayInputStream.</p>
|
CSS: Simulating flexible width (without min-width)- <p>I have a DIV container of 100% width holding x divs. The last child DIV floats right, the rest float left. All child DIV's remain in a line so long as they fit in the bar (all oriented left, except for the last div which sits by itself on the right). If the window is resized smaller and the children don't have enough room, they collapse from their horizontal orientation (which I don't want). To fix this, I know I can set a min-width of the DIV container, the issue is that there is a variable amount of DIVs in the container, of variable width. I'd like to simulate being able to set a min-width where of the container where min-width = width of all children, but I cannot compute these because they are variable (which would simulate flexible space between the right div and the rest, but not let them get closer than they should be allowed (hence collapsing the divs)).</p>
<p>I know this is a little unclear so here's a picture: <img src="http://i.stack.imgur.com/sCVxE.jpg" alt="http://img3.imageshack.us/img3/933/barfuo.jpg"></p>
<p>Thanks!</p>
| <p>I hate to say it (or rather the anti-table crowd will hate it) but you know what does this pretty easily?</p>
<p>That's right: tables.</p>
<pre><code><style type="text/css">
#topbar { width: 100%; }
#topbar div { white-space: nowrap; overflow: hidden; }
#topright div { text-align: right; }
</style>
<table id="topbar">
<tr>
<td><div>Item 1</div></td>
<td><div>Item 2</div></td>
<td><div>Item 3</div></td>
<td><div>Item 4</div></td>
<td><div>Item 1</div></td>
<td id="topright"><div>Item Right</div></td>
</tr>
</table>
</code></pre>
<p>The internal divs are important because overflow hidden only works on block elements and table cells aren't block elements (they're "table-cell" display type).</p>
|
Button BackgroundImage Property <p>I am trying to write an application on Windows Mobile but I am experiencing a problem.</p>
<p>I want to draw a picture of arrows on the button but I do not know how to do this. </p>
<p>How can I accomplish this?</p>
| <p>You need to draw a custom control. See this <a href="http://msdn.microsoft.com/en-us/library/ms229655.aspx" rel="nofollow">link</a> for an example. You can draw the icon using Graphics.DrawImage function.</p>
|
How to determine a windows executables DLL dependencies programatically? <p>How to determine what DLL's a binary depends on using programmatic methods? </p>
<p>To be clear, I am not trying to determine the DLL dependencies of the running exec, but of any arbitrary exec (that may be missing a required DLL). I'm looking for a solution to implement in a C/C++ application. This is something that needs to be done by my application at runtime and can't be done by a third party app (like depends).</p>
| <p>Take a look at the <a href="http://msdn.microsoft.com/en-us/library/ms680209%28VS.85%29.aspx"><code>IMAGE_LOAD_FUNCTION</code></a> API. It will return a pointer to a <a href="http://msdn.microsoft.com/en-us/library/ms680349%28VS.85%29.aspx"><code>LOADED_IMAGE</code></a> structure, which you can use to access the various sections of a PE file. </p>
<p>You can find some articles that describe how the structures are laid out <a href="http://msdn.microsoft.com/en-us/magazine/bb985992.aspx">here</a>, and <a href="http://msdn.microsoft.com/en-us/magazine/bb985994.aspx">here</a>. You can download the source code for the articles <a href="http://code.msdn.microsoft.com/mag200202Windows/Release/ProjectReleases.aspx?ReleaseId=1908">here</a>.</p>
<p>I think this should give you everything you need.</p>
<p><strong>Update:</strong></p>
<p>I just downloaded the source code for the article. If you open up <code>EXEDUMP.CPP</code> and take a look at <code>DumpImportsSection</code> it should have the code you need.</p>
|
Change font of cell in DataGrid on Windows Mobile <p>I'm using VS 2005 to create a Windows Mobile program in C#. I need to display data in a grid. The only grid control I could find for Windows Mobile is DataGrid, so I placed one on my form. I now need to change the width of some columns and the font & color of some cells. How do I do this?</p>
<p>Also is there is a better control to use for Windows Mobile?</p>
<p>thanks
John.</p>
| <p>I am not sure you can change the font for individual columns or cells. The grid has a property that lets you set the font and size.
To set the width of columns, I use this method (it adds a table style to the grid):</p>
<pre><code>private void SetColumnWidth(int columnID, int width)
{
// add table style if first call
if (this.dataGrid1.TableStyles.Count == 0)
{
// Set the DataGridTableStyle.MappingName property
// to the table in the data source to map to.
dataGridColumnTableStyle.MappingName = "<name of your table in the DS here>";
// Add it to the datagrid's TableStyles collection
this.dataGrid1.TableStyles.Add(dataGridColumnTableStyle);
}
// set width
this.dataGrid1.TableStyles[0].GridColumnStyles[columnID].Width = width;
}
</code></pre>
<p>This method is also helpful when you want to hide a column that is in the bound DataTable, but you don't want to show (then you set width = 0).</p>
|
How can I use "mod rewrite" to redirect a folder path to a subdomain, but without a browser redirect? <p>I have a file that I want to redirect to a subdomain using mod_rewrite. For example, I would like to redirect the request for <code>http://www.mydomain.com/xyz</code> to the subdomain <code>xyz.example.com</code></p>
<p>I don't want to send a redirect to the browser though (so it doesn't know the page is different).</p>
<p>BTW. <code>xyz</code> is a CNAME record, pointing to <code>www.otherdomain.com.</code></p>
<p>Another example, just to clarify. If <code>http://www.mydomain.com/xyz/something</code> is entered into the browser, I want Apache to return the contents of <code>http://xyz.mydomain.com/something</code></p>
| <p>I <em>THINK</em> this will do what you want it to:</p>
<pre><code>Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*?)/(.*?)$ http://$1.mydomain.com/$2
</code></pre>
<p>As this stands it will redirect EVERY request that goes to a subfolder so if you links for images or css that are in a sub folder it will also rewrite those, if you want to list only certain things you could use this</p>
<pre><code>Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(blog|store|other)/(.*?)$ http://$1.mydomain.com/$2
</code></pre>
<p>This will only redirect mydomain.com/blog/ mydomain.com/store/ and mydomain.com/other/</p>
|
Do you know good tutorial websites to develop a prePost in Tomcat? <p>We want to integrate a prepost rutine in our webserver (tomcat). A filter that will capture the post before sent to the user and add a line of code in the html before sent to the user. We are looking for tutorial or any help on this.</p>
| <p>Not 100% sure I understand the question, but it sounds like you may be looking for servlet filters:</p>
<p><a href="http://java.sun.com/products/servlet/Filters.html" rel="nofollow">http://java.sun.com/products/servlet/Filters.html</a></p>
|
C# Threading Patterns - is this a good idea? <p>I was playing with a project of mine today and found an interesting little snippet, given the following pattern, you can safely cleanup a thread, even if it's forced to close early. My project is a network server where it spawns a new thread for each client. I've found this useful for early termination from the remote side, but also from the local side (I can just call <code>.Abort()</code> from inside my processing code).</p>
<p>Are there any problems you can see with this, or any suggestions you'd make to anyone looking at a similar approach?</p>
<p>Test case follows:</p>
<p><hr /></p>
<pre><code>using System;
using System.Threading;
class Program
{
static Thread t1 = new Thread(thread1);
static Thread t2 = new Thread(thread2);
public static void Main(string[] args)
{
t1.Start();
t2.Start();
t1.Join();
}
public static void thread1() {
try {
// Do our work here, for this test just look busy.
while(true) {
Thread.Sleep(100);
}
} finally {
Console.WriteLine("We're exiting thread1 cleanly.\n");
// Do any cleanup that might be needed here.
}
}
public static void thread2() {
Thread.Sleep(500);
t1.Abort();
}
}
</code></pre>
<p>For reference, without the try/finally block, the thread just dies as one would expect.</p>
| <p>Aborting another thread at all is just a bad idea unless the whole application is coming down. It's too easy to leave your program in an unknown state. Aborting your <em>own</em> thread is occasionally useful - ASP.NET throws a <code>ThreadAbortException</code> if you want to prematurely end the response, for example - but it's not a terribly nice design.</p>
<p>Safe clean-up of a thread should be mutual - there should be some shared flag <em>requesting</em> that the thread shuts down. The thread should check that flag periodically and quit appropriately.</p>
|
Understanding JavaScript - Resource <p>Using the tiny Diggit/Blog feature of StackOverflow described <a href="http://stackoverflow.com/about">here</a>:</p>
<p></p>
<p>I would like to post the following Google tech talk video I have just saw and that I found quite interesting.</p>
<p>I have always had problems understanding javascript "nature".</p>
<p>Here, the <a href="http://www.youtube.com/watch?v=hQVTIJBZook" rel="nofollow">JavaScript good parts</a> are described by Douglas Crockford</p>
<p>I hope you find this link useful. </p>
<p>Now the question part: </p>
<p>What are your complaints about javascript?
Do you use an IDE for javascript editting?
Do you think this video helps to understand the "good parts"?</p>
| <p>JavaScript: the bad parts.</p>
<ol>
<li><p>The biggest mistake is late error detection. JavaScript will happily let you access a non-existant object member, or pass the wrong number of arguments to a function, and fill the gap with âundefinedâ objects, which, unless you deliberately check for them (which is impractical to keep doing everywhere), will cause an exception or generate an unexpected value later on. Possibly much later on, resulting in subtle and difficult-to-debug errors appearing nowhere near the actual problem code. These conditions should have generated exceptions, except that JS didn't originally have exceptions to raise. âundefinedâ was a quick and dirty hack we're now stuck with.</p></li>
<li><p>Undeclared variables defaulting to global scope. This is almost never what you want and can cause subtle and difficult-to-debug errors when two functions both forget âvarâ and start diddling the same global.</p></li>
<li><p>The model of constructor functions is weird even for a prototype-based-OO language and confuses even experienced users. Forgetting ânewâ can result in subtle and difficult-to-debug errors. Whilst you <em>can</em> make a passable class/instance system out of it, there's no standard, and most of the class systems proposed in the early tutorials that people are still using are both desperately inadequate, and obfuscate what JavaScript is actually doing.</p></li>
<li><p>Lack of bound methods. It's utterly unintuitive that accessing âobject.methodâ when calling it makes a magic connection to âobjectâ in âthisâ, but passing âobject.methodâ as a reference loses the connection; no other language works this way. When this happens, âthisâ is set to an unexpected value, but it's not âundefinedâ or something else that would raise an exception. Instead, all the property access ends up on âwindowâ, causing subtle and difficult-to-debug errors later.</p></li>
<li><p>There is no integer type. Number looks like one but breaks down in various ways (eg. n+1==n for high enough n). Any time a NaN or Infinity sneaks in (quite unexpectedly if you think you are dealing with integers) you won't find out immediately; instead there will be subtle and difficult-to-debug errors down the line.</p></li>
<li><p>There is no associative array type. Object looks like one but breaks down under various unexpected keys. Arrays aren't pure lists. Any time you ever use âfor...inâ, you have probably fallen into a trap, and will experience... yes, subtle and difficult-to-debug errors.</p></li>
<li><p>Generally poor string handling, for a scripting language at least. String.split(, limit) and String.replace() don't do what you might think, causing... you know. The results of toString() are generally poor and not useful for debugging. Meanwhile we are stuck with a load of rubbish Netscape thought might be useful, like String.prototype.blink(), and the perpetually broken escape(). Yay.</p></li>
<li><p>And <em>then</em> there's all the browser differences (IE is still missing a lot of essential methods on the basic objects), and the DOM...</p></li>
<li><p>And finally, even when an exception does occur, it is hidden away from view, so the author won't even realise something is wrong. The result is that most sites are chock full of errors; turn on full JavaScript error reporting in IE and the result is unusable.</p></li>
</ol>
<p>It scares me to think a new generation of programmers are learning this tosh as a first language. What's worse, most of the tutorial material they're learning from (âMy fiRST AEWsome R0LL0VERZ!â) invariably encourages the worst possible practice. âjavascript:â URLs, âeval()â for everything, browser-specific DOM access... oy.</p>
|
Making forms in Rails <p>So far I've built a simple form for a user using the <code>form_for</code> method to wrap around my user model.</p>
<p>But if I'm going to create a form now which doesn't doesn't map directly to any particular model, should I still be using <code>form_for</code>?</p>
| <p>You probably just want <a href="http://api.rubyonrails.com/classes/ActionView/Helpers/FormTagHelper.html#M001697" rel="nofollow"><code>form_tag</code></a>.</p>
|
problem with setting formula in column <p>I have problem with setting the formula in particular field.I am using sql database have been added from->add new item->sql database.I have orders table with following field
ordernum primary key
orderdate smalldatetime,
custemail varchar(50),
subtotal money,
salestax money,
shipping money,
total AS(subtotal+salestax+shipping)</p>
<p>How to set this total formula,there is no datatype mentioned in total field.</p>
<p>Thanks,
Habib</p>
| <p>This example should illustrate what you are looking to achieve.</p>
<pre><code> create table #table
(
ordernum int identity(1,1) primary key,
orderdate smalldatetime,
custemail varchar(50),
subtotal money,
salestax money,
shipping money,
total AS(subtotal+salestax+shipping)
)
insert into #table
(
orderdate,
custemail,
subtotal,
salestax,
shipping
)
select
getDate(),
'some@email.com',
1.00,
1.00,
1.00
select * from #table
drop table #table
</code></pre>
<p>cheers, John</p>
|
What is the best alternative for QueryString <p>We heard a lot about the vulnerabilities of using QueryStrings and the possible attacks.
Aside from that, yesterday, an error irritated me so much that i just decide to stop using QueryStrings, i was passing something like:</p>
<pre><code>Dim url As String = "pageName.aspx?type=3&st=34&am=87&m=9"
</code></pre>
<p>I tried to </p>
<pre><code>Response.Write(url)
</code></pre>
<p>in the redirecting page, it printed the "type" as 3, then i tried it in the target page, it printed 3,0....i know this can be easily dealt with, but why? i mean why should i pass 3 and have to check for 3.0 in the next page's load to take my action accordingly???</p>
<p>So what should we use? what is the safest way to pass variables, parameters...etc to the next page?</p>
| <p>You could use <a href="http://msdn.microsoft.com/en-us/library/ms178139.aspx" rel="nofollow">Cross-Page Postbacks</a>.</p>
<p>Check also this article: </p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx" rel="nofollow">How to: Pass Values Between ASP.NET Web Pages</a></li>
</ul>
|
What are the differences between a multidimensional array and an array of arrays in C#? <p>What are the differences between multidimensional arrays <code>double[,]</code> and array-of-arrays <code>double[][]</code> in C#?</p>
<p>If there is a difference, what is the best use for each one?</p>
| <p>Array of arrays (jagged arrays) are faster than multi-dimensional arrays and can be used more effectively. Multidimensional arrays have nicer syntax.</p>
<p>If you write some simple code using jagged and multidimensional arrays and then inspect the compiled assembly with an IL disassembler you will see that the storage and retrieval from jagged (or single dimensional) arrays are simple IL instructions while the same operations for multidimensional arrays are method invocations which are always slower.</p>
<p>Consider the following methods:</p>
<pre><code>static void SetElementAt(int[][] array, int i, int j, int value)
{
array[i][j] = value;
}
static void SetElementAt(int[,] array, int i, int j, int value)
{
array[i, j] = value;
}
</code></pre>
<p>Their IL will be the following:</p>
<pre><code>.method private hidebysig static void SetElementAt(int32[][] 'array',
int32 i,
int32 j,
int32 'value') cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ldelem.ref
IL_0003: ldarg.2
IL_0004: ldarg.3
IL_0005: stelem.i4
IL_0006: ret
} // end of method Program::SetElementAt
.method private hidebysig static void SetElementAt(int32[0...,0...] 'array',
int32 i,
int32 j,
int32 'value') cil managed
{
// Code size 10 (0xa)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ldarg.2
IL_0003: ldarg.3
IL_0004: call instance void int32[0...,0...]::Set(int32,
int32,
int32)
IL_0009: ret
} // end of method Program::SetElementAt
</code></pre>
<p>When using jagged arrays you can easily perform such operations as row swap and row resize. Maybe in some cases usage of multidimensional arrays will be more safe, but even Microsoft FxCop tells that jagged arrays should be used instead of multidimensional when you use it to analyse your projects.</p>
|
problem occuring when i am inserting date <p>while inserting date mysql server takes the year and day correctly but the month is defaultly taking januavary into the database.
i am using mysql server version 5.0.22
i am inserting the date though application.
the application was developed by using Springs web mvc frame-work and Hibernate.</p>
| <p>Can you display the mysql INSERT statement which is being used to insert the data into the database? This would indicate whether it is a malformed INSERT statement or whether it is a valid statement using incorrect data. </p>
<p>Once you know what is happening, you can track down where the problem really is. I would guess it is a faulty date-parsing function.</p>
<p>Another possibility is that the software is expecting the date in European format (dd-mm-yyyy) and getting the entry in US format (mm-dd-yyyy) or vice-versa. And this is causing parsing errors.</p>
|
How to prevent UIView's drawRect from clearing out the paths drawn by previous drawRect calls? <p>Everytime UIView's drawRect is called, the content drawn by previous drawRect (using Core Graphics) is cleared out. How can I make it so that the paths rendered from previous drawRect calls stay until I explicitly clear it?</p>
| <p>You basically need to clip the 'dirty' part of your rect where changes have been made, and only this part will be re-drawn.</p>
<pre><code>- (void)setNeedsDisplayInRect:(CGRect)invalidRect
</code></pre>
|
Northwind Starters Kit <p>Is the Northwind Starter Kit from Codeplex a good starting point to learn more about how to best architect an ASP.NET application?</p>
<p>Is there something similar for the AdventureWorks database examples?</p>
| <p>Northwind database was the best sample database for SQL Server 2000.</p>
<p>Talk about SQL Server 2005, AdventureWorks is better than Northwind. Northwind is not the best database due to few new features of analysis and reporting service of SQL Server 2005.</p>
<p>MSDN Book On Line (BOL) uses the AdventureWorks in all of their example and it makes it easy to follow up if proper understanding of AdventureWorks schema is developed.<p>
<p>However, SQL Server Compact Edition uses Northwind as sample database. So decide on basis of your version.</p>
|
C# Session management <p>I am using a C# Webservice to log a user out. I am using the formsauthentication.signout for the same. </p>
<p>I am passing this webservice call through JQuery. How to I get the user to redirect to login page? I tried the window.location = "login.aspx", it works but if i type in another page in the secure area, it opens up again.</p>
<p>Thanks.</p>
| <p>Are you sure that the FormsAuthentication.SignOut() is running? (Debug to make sure it is hit by the web service.) </p>
<p>You should also manually clear out the authentication cookie on the client, in your jQuery handler after a successful call to the web service.</p>
|
Weird apache behavior when trying to display urls without html extension <p>I have a url that is easily accessible when you request it as:</p>
<pre>
http://example.com/2005/01/example.html
or
http://example.com/2005/01/example
</pre>
<p>(I actually don't know why it works without the extension. Instead, it should return the usual 404 error.)</p>
<p>However, when I try to access the following url:</p>
<pre>
http://example.com/2005/01/example/
(note the trailing slash)
</pre>
<p>I get a 404 Not found error but with the requested url printed as:</p>
<pre>
http://example.com/2005/01/example.html/
</pre>
<p>So, it seems the ".html" part was automatically added by apache.</p>
<p>My question is: how do I disable this behavior? I need to do it because I want add mod_rewrite rules to hide the html extension, so that I can access that url as: </p>
<pre>
http://example.com/2005/01/example/
</pre>
<p>My apache is 2.2.9 on Ubuntu 8.10.</p>
<p>Thanks!</p>
| <p><a href="http://httpd.apache.org/docs/2.2/content-negotiation.html#multiviews"><code>MultiViews</code></a> could cause this behavior. Try to disable it:</p>
<pre><code>Options -MultiViews
</code></pre>
|
Internationalization with Nibs. Is that really a good idea? <p>In the Apple Docs they say that a Nib enables internationalization by just translating the Nib into many languages. I am thinking now about a worse but realistic scenario: You have made a huge user interface. Then you translate this into 25 languages. So you get 25 different Nibs. You also get a huge redundancy in styling and defining the UI: 25 times the same stuff. Same Bindings, same everything. Just text is different.</p>
<p>So, I really think this is a very bad approach. Instead, I would prefer to just link in all texts from a resource bundle or something like that. Just a file with text strings, which is linked in at run time from the appropriate language resource. Then you only have "trouble" linking in the text which really doesnt make any fun. But then, you can do changes on your UI ONCE without having to do the same step 25 times over and over again. A new Binding in every nib. That would be so horrible!!</p>
<p>Now, please tell me I got that wrong. Apple does not assume that we do something so creazy?</p>
| <p>The localization situation is not ideal. Although Cocoa UI elements support some dynamic flexibility in their sizing (the ausosizing flags), it's very difficult to arrange them in a view so that they will accommodate any sized text.</p>
<p>As Heng-Cheong points out, this usually means that some adjustment to layout is required on a per-localization basis. Apple supports a process called incremental localization with a tool called "ibtool", bundled with your developer tools. The process is far from intuitive and seems to have some subtle bugs, but it helps to make the process easier than, say, separately maintaining 25 different nibs manually. The process essentially involves mapping changes you make to your primary nib onto the other localized nibs. Apple describes the process in more detail:</p>
<p><a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/LoadingResources/CocoaNibs/CocoaNibs.html" rel="nofollow">https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/LoadingResources/CocoaNibs/CocoaNibs.html</a></p>
<p>In order to avoid this painful process, some people take a different approach. If you compromise on the layout of your views, you can achieve a situation where every UI element accommodates the largest localized string. Using the alignment features of text fields, etc., you can thus arrange an acceptable layout, though the extra spacing required for the localization with the largest strings often causes a less-than-ideal layout for the language whose strings are shortest. If you take this approach, you need to design your nibs so that a controller class populates the nib's UI elements with the correct localized strings at runtime.</p>
<p>Finally, some developers go so far as to apply their own relayout to the elements in a nib, optimizing them for the sizes of the strings that have been set upon them. This would be a refinement of the strategy above, where a single nib is used and manipulated at runtime to achieve the desired effect.</p>
|
Weblogic "Abandoning transaction" warning <p>We randomly get warnings such as below on our WL server. We'd like to better understand what exactly these warnings are and what we should possibly do to avoid them. </p>
<blockquote>
<p>Abandoning transaction after 86,606
seconds:
Xid=BEA1-52CE4A8A9B5CD2587CA9(14534444),
Status=Committing,numRepliesOwedMe=0,numRepliesOwedOthers=0,seconds
since begin=86605, seconds
left=0,XAServerResourceInfo[JMS_goJDBCStore]=(ServerResourceInfo[JMS_goJDBCStore]= (state=committed,assigned=go_server),xar=JMS_goJDBCStore,re-Registered
= true),XAServerResourceInfo[weblogic.jdbc.wrapper.JTSXAResourceImpl]=
(ServerResourceInfo[weblogic.jdbc.wrapper.JTSXAResourceImpl]=(state=new,assigned=none),xar=
weblogic.jdbc.wrapper.JTSXAResourceImpl@1a8fb80,re-Registered
= true),SCInfo[go+go_server]= (state=committed),properties=({weblogic.jdbc=t3://10.6.202.37:18080}),local
properties=
({weblogic.transaction.recoveredTransaction=true}),OwnerTransactionManager=
ServerTM[ServerCoordinatorDescriptor=(CoordinatorURL=go_server+10.6.202.37:18080+go+t3+,
XAResources={JMS_goJDBCStore,
weblogic.jdbc.wrapper.JTSXAResourceImpl},NonXAResources=
{})],CoordinatorURL=go_server+10.6.202.37:18080+go+t3+)</p>
</blockquote>
<p>I do understand the BEA <a href="http://e-docs.bea.com/wls/docs81/messages/TX.html" rel="nofollow">explanation</a>: </p>
<blockquote>
<p><strong>Error</strong>: Abandoning transaction after secs seconds: tx</p>
<p><strong>Description</strong>: When a transaction is abandoned,
knowledge of the transaction is
removed from the transaction manager
that was attempting to drive the
transaction to completion. The JTA
configuration attribute
AbandonTimeoutSeconds determines how
long the transaction manager should
persist in trying to commit or
rollback the transaction.</p>
<p><strong>Cause</strong>: A resource or participating server may
have been unavailable for the duration of the
AbandonTimeoutSeconds period.</p>
<p><strong>Action</strong>: Check participating resources for heuristic
completions and correct any data inconsistencies.</p>
</blockquote>
<p>We have observed that you can get rid of these warnings by deleting the *.tlog files but this doesn't seem like the right strategy to deal with the warnings.</p>
<p>The warnings refer to JMS and our JMS store. We do use JMS. We just don't understand why transactions are hanging out there and why they would be "abandoned"??</p>
| <p>I know it's not very satisfying, but we do delete *.tlog files before startup in our app hosted on WLS 7.</p>
<p>Our app is an event-processing back-end, largely driven by JMS. We aren't interested in preserving transactions across WLS restarts. If it didn't complete before the shutdown, it tends not to complete after a restart. So doing this *.tlog cleanup just eliminates some warnings and potential flaky behavior.</p>
<p>I don't think JMS is fundamental to any of this, by the way. At least not that I know.</p>
<p>By the way, we moved from JDBC JMS store to local files. That was said to be better performing and we didn't need the location independence we'd get from using JDBC. If that describes your situation also, maybe moving to local files would eliminate the root cause for you?</p>
|
MySQL: Check if the user exists and drop it <p>Thereâs not standard way to check if a MySQL user exists and based on that drop it. Are there any workarounds for this? </p>
<p>Edit: I need a straight way to run this without throwing up an error<br />
e.g.</p>
<pre><code>DROP USER test@localhost; :
</code></pre>
| <p>This worked for me:</p>
<pre><code>GRANT USAGE ON *.* TO 'username'@'localhost';
DROP USER 'username'@'localhost';
</code></pre>
<p>This creates the user if it doesn't already exist (and grants it a harmless privilege), then deletes it either way. Found solution here: <a href="http://bugs.mysql.com/bug.php?id=19166">http://bugs.mysql.com/bug.php?id=19166</a></p>
<p>Updates: <a href="http://stackoverflow.com/a/22866506/20772">@Hao recommends</a> adding <code>IDENTIFIED BY</code>; @andreb (in comments) suggests disabling <code>NO_AUTO_CREATE_USER</code>.</p>
|
How do I fix Postgres so it will start after an abrupt shutdown? <p>Due to a sudden power outage, the <code>PostGres</code> server running on my local machine shut down abruptly. After rebooting, I tried to restart postgres and I get this error:</p>
<p><strong><code>$ pg_ctl -D /usr/local/pgsql/data restart</code></strong></p>
<pre><code>pg_ctl: PID file "/usr/local/pgsql/data/postmaster.pid" does not exist
Is server running?
starting server anyway
server starting
$:/usr/local/pgsql/data$ LOG: database system shutdown was interrupted at 2009-02-28 21:06:16
LOG: checkpoint record is at 2/8FD6F8D0
LOG: redo record is at 2/8FD6F8D0; undo record is at 0/0; shutdown FALSE
LOG: next transaction ID: 0/1888104; next OID: 1711752
LOG: next MultiXactId: 2; next MultiXactOffset: 3
LOG: database system was not properly shut down; automatic recovery in progress
LOG: redo starts at 2/8FD6F918
LOG: record with zero length at 2/8FFD94A8
LOG: redo done at 2/8FFD9480
LOG: could not fsync segment 0 of relation 1663/1707047/1707304: No such file or directory
FATAL: storage sync failed on magnetic disk: No such file or directory
LOG: startup process (PID 5465) exited with exit code 1
LOG: aborting startup due to startup process failure
</code></pre>
<p>There is no <code>postmaster.pid</code> file in the data directory. What possibly could be the reason for this sort of behavior and of course what is the way out?</p>
| <p>You'd need to <a href="http://www.postgresql.org/docs/8.3/static/app-pgresetxlog.html">pg_resetxlog</a>. Your database can be in an inconsistent state after this though, so dump it with <code>pg_dumpall</code>, recreate and import back.</p>
<p>A cause for this could be:</p>
<ul>
<li><p>You have not turned off hardware
write cache on disk, which often
prevents the OS from making sure data is written before it reports successful write to application. Check with</p>
<p><code>hdparm -I /dev/sda</code></p>
<p>If it shows "*" before "Write cache" then this could be the case. <a href="http://www.postgresql.org/ftp/source/v8.3.6/">Source of PostgreSQL</a> has a program src/tools/fsync/test_fsync.c, which tests speed of syncing data with disk. Run it - if it reports all times shorter than, say, 3 seconds than your disk is lying to OS - on a 7500rpm disks a test of 1000 writes to the same place would need at least 8 seconds to complete (1000/(7500rpm/60s)) as it can only write once per route. You'd need to edit this test_fsync.c if your database is on another disk than /var/tmp partition - change</p>
<p><code>#define FSYNC_FILENAME "/var/tmp/test_fsync.out"</code></p>
<p>to</p>
<p><code>#define FSYNC_FILENAME "/usr/local/pgsql/data/test_fsync.out"</code></p></li>
<li><p>Your disk is failing and has a bad block, check with <a href="http://en.wikipedia.org/wiki/Badblocks">badblocks</a>.</p></li>
<li><p>You have a bad RAM, check with <a href="http://www.memtest.org/">memtest86+</a> for at least 8 hours.</p></li>
</ul>
|
'&' before the parameter name <p>Just a quick and no doubt easy question. I'm pretty new to PHP and am looking through some existing code. I have tried to find the answer to my question on google, but to no avail.</p>
<p>Can somebody please let me know what the '&' sign before the parameter $var does??</p>
<pre><code>function setdefault(&$var, $default="")
{
if (! isset($var))
{
$var = $default;
}
}
</code></pre>
| <p>Passes it by reference.</p>
<p><strong>Huh?</strong>
Passing by reference means that you pass the address of the variable instead of the value. Basically you're making a pointer to the variable.</p>
<p><a href="http://us.php.net/language.references.pass">http://us.php.net/language.references.pass</a></p>
|
At which point in the life of an xmlHttpRequest object is serialised XML parsed into a DOM? <p>In JavaScript, <code>xmlHttpRequest.responseXML()</code> returns a <code>DOM Document</code> object. The <code>DOM Document</code> object is created from an XML-structured HTTP response body.</p>
<p>At what point during the life of an <code>xmlHttpRequest</code> object is the XML string parsed into the <code>DOM Document</code>?</p>
<p>I can imagine it may occur in one of two places.</p>
<ul>
<li>When <code>responseXML()</code> is called.<br>
No need to waste resources parsing the XML string into a DOM until you know it's actually needed.<br><br></li>
<li>When the HTTP response has been received.<br>
If the server returns a text/xml content-type, it's clear you've requested XML and you're probably going to want the response body parsed into a DOM as you otherwise can't do much with the requested data.</li>
</ul>
<p>Both options have some merit, although I'm inclined to say that the XML string is parsed only when <code>responseXML</code> is called.</p>
<p>At what point does parsing of the XML string occur?</p>
<p>Reaons for asking: I need to measure browser-based XML deserialisation performance, with the aim of comparing this to JSON deserialisation performance.</p>
| <p>I wouldn't be surprised if this is browser dependent. Why not profile all three?</p>
|
decode base64 with dollar sign in ruby 1.8.5 <p>I have base64-encoded string (with two dollar signs, so it's not a common base64 string)</p>
<p>The problem: Base64.decode64 (or .unpack("m")) decodes it just fine on my local machine(ruby 1.8.6), but with ruby 1.8.5 (the version used by Heroku) it doesn't work</p>
<p>Any ideas ?</p>
<p><strong>edit:</strong></p>
<p>I have :</p>
<p>$$YTo1OntzOjM6Im1pZCI7czo3OiI3MTE5Njg3IjtzOjQ6Im5hbWUiO3M6MjE6IkthbnllIFdlc3QgLSBTdHJvbmd
lciI7czo0OiJsaW5rIjtzOjQ4OiJodHRwOi8vd3d3LmVhc3kxNS5jb20vMDIgU3Ryb25nZXIgKFNuaXBwZXQpMS5tcD
MiO3M6OToiX3BsYXl0aW1lIjtzOjU6IjgzMjAwIjtzOjg6Il9uZXh0aWRzIjtzOjEzNDoiMjc1ODE0MDYsMjc0MDE1
NzAsMjI1MTU0MDMsMTU1ODM2NjYsMTYzMTUzMzksMjgwNDY5MTUsMzAzOTMxODksMzUyMDAyMTMsMjIwNTE1MzAsMj
c1NTg1MTQsMTM3ODkyNTYsMTk4MTY5OTgsMzA0NzI4MDEsMTUyNTk5NzksMTg5OTkxMzciO30=</p>
<p>I successed in decoding it with '...'.unpack("m") locally but not on the heroku server (ruby 1.8.5, maybe the ruby version it's not the issue)</p>
| <p>The dollar sign is not part of the Base64 specification.</p>
<p>Simply strip the leading <code>$$</code> before unpacking:</p>
<pre><code>str.sub(/^\$*/, '').unpack('m')
</code></pre>
<p>To strip all non-Base64 characters, emulating new (Ruby 1.8.6) behaviour,</p>
<blockquote>
<p><code>str.gsub(/[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\+\/]/, '').unpack('m')</code></p>
</blockquote>
<p>Ruby 1.8.6 will ignore all non-Base64 symbols (including the <code>$</code>) inside the string to decode, whereas 1.8.5 will stop processing at the first such character (see <code>pack.c</code> in the Ruby source.)</p>
|
Where do I find all Apple Guides for objective-c and cocoa? <p>I find that the xcode-builtin-documentation reader is hard to use. I want to see the root of all Guides available, to get an idea of how long I will have to keep reading until I can start. All the time some new Guide pops up to me, and I am wondering how many they are.</p>
<p>Is there an overview somewhere?</p>
| <p>Start with <a href="http://developer.apple.com/mac" rel="nofollow">http://developer.apple.com/mac</a> - there are lots of docs there.</p>
|
How to import attributes and elements from XML to Filemaker? <p>I have an application that stores its user database to an XML file and I need to export selected fields to Filemaker so my client and mine the data on Filemaker. I managed to make XSLT file to import XML elements, but cannot seem to find a way to import any elements. Pointers in solving this problem are greatly anticipated.</p>
<p>Example of the XML-file:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<APPLICATION_NAME>
<USERS>
<USER>
<ID>15001</ID>
<USERNAME>Administrator</USERNAME>
<!-- other elements -->
<PROPERTYBAG>
<ITEM NAME="LastModifiedDate" VALUE="Fri, 05 Sep 2008 13:13:16 GMT"/>
<ITEM NAME="Registered" VALUE="5.9.2008 16:13:16"/>
<!-- other elements -->
</PROPERTYBAG>
</USER>
<!-- more users -->
</USERS>
</APPLICATION_NAME>
</code></pre>
<p>So far I've managed to import elements by following instruction from this site: <a href="http://edoshin.skeletonkey.com/2005/10/use%5Fmodular%5Fxsl.html" rel="nofollow">http://edoshin.skeletonkey.com/2005/10/use_modular_xsl.html</a></p>
<p>And here is the XSLT that imports those elements but not attributes:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.filemaker.com/fmpxmlresult">
<xsl:include href="FileMaker.xslt"/>
<xsl:template match="/">
<xsl:call-template name="TABLE">
<xsl:with-param name="METADATA-FIELDS">
<xsl:call-template name="FIELD">
<xsl:with-param name="NAME" select="'ID'"/>
</xsl:call-template>
<xsl:call-template name="FIELD">
<xsl:with-param name="NAME" select="'USERNAME'"/>
</xsl:call-template>
<xsl:call-template name="FIELD">
<xsl:with-param name="NAME" select="'ISADMINISTRATOR'"/>
</xsl:call-template>
<xsl:call-template name="FIELD">
<xsl:with-param name="NAME" select="'LastModifiedDate'"/>
</xsl:call-template>
<xsl:call-template name="FIELD">
<xsl:with-param name="NAME" select="'Registered'"/>
</xsl:call-template>
</xsl:with-param>
<xsl:with-param name="RESULTSET-RECORDS">
<xsl:for-each select="//USER">
<xsl:call-template name="ROW">
<xsl:with-param name="COLS">
<xsl:call-template name="COL">
<xsl:with-param name="DATA" select="ID"/>
</xsl:call-template>
<xsl:call-template name="COL">
<xsl:with-param name="DATA" select="USERNAME"/>
</xsl:call-template>
<xsl:call-template name="COL">
<xsl:with-param name="DATA" select="ACCOUNT/ISADMINISTRATOR"/>
</xsl:call-template>
<xsl:call-template name="COL">
<xsl:with-param name="DATA" select="@Registered"/>
</xsl:call-template>
</xsl:with-param>
</xsl:call-template>
</xsl:for-each>
</xsl:with-param>
</xsl:call-template>
</xsl:template>
</xsl:stylesheet>
</code></pre>
| <p>I have to say I'm not sure I understood what you need here.<br />
If I did understand - you are not getting the value of </p>
<pre><code><ITEM NAME="LastModifiedDate" VALUE="Fri, 05 Sep 2008 13:13:16 GMT"/>
</code></pre>
<p>by using </p>
<pre><code><xsl:call-template name="COL">
<xsl:with-param name="DATA" select="@Registered"/>
</xsl:call-template>
</code></pre>
<p><hr/><strong>Edit:</strong><br />
If this is the case then try using ITEM/@Registered like so: </p>
<pre><code><xsl:call-template name="COL">
<xsl:with-param name="DATA" select="PROPERTYBAG/ITEM[@NAME='Registered']/@VALUE"/>
</xsl:call-template>
</code></pre>
<p>you want the value attribute of ITEM element with name attribute equals Registered under propertybag element that is under each user...</p>
<p><hr/>
<strong>Original:</strong><br />
If this is the case then try using ITEM/@Registered like so: </p>
<pre><code><xsl:call-template name="COL">
<xsl:with-param name="DATA" select="ITEM/@Registered"/>
</xsl:call-template>
</code></pre>
<p>you want the ITEM that is under each user...</p>
|
Social networks in an Delphi win32 application <p>I want to create some kind âsocialâ connection/interaction in an application that I am creating.</p>
<p>The application is for a restrict group of professionals, that would benefits for social connection/interaction with each other.</p>
<p>So now I donât know what to do. Do something new, integrate with an existing one ?</p>
<p>I am open for ideas. </p>
<p>---- UPDATE ----</p>
<p>Some basic features should be:</p>
<p>â¢Private Messages</p>
<p>â¢Blog functionality</p>
<p>â¢Publications</p>
<p>â¢A user profile, with basic info</p>
<p>â¢Friends list</p>
<p>â¢Pools</p>
<p>Open source product, if possible.</p>
<p>Platform. For now yes win32 application. Later if the concept catch on we can go web. Be this is only an extra feature of a big application, not the main feature.</p>
| <p>Your question is quite vague but I try to give you some pointers. </p>
<p>First you need to define what functionality you want in your application. You want a social network site for professionals so we can rule out the fluffy bits. But there are other aspects of a social network site that you maybe want to include:</p>
<ul>
<li>Real time chat (one on one or multi, and do you want to include voice and view)</li>
<li>Private Messages (like email)</li>
<li>Discussions (like a discussion forum)</li>
<li>Blog functionality</li>
<li>Publications</li>
<li>A user profile, and what do you want to include.</li>
<li>Do we need to maintain a friends list?</li>
<li>And special purpose groups.</li>
</ul>
<p>Then you need to decide if you are going to buy, take or make the software. Maybe you can adapt some open source product. </p>
<p>Then you need to decide on a platform. You have tagged this question delphi win32. But why not use a web based concept.</p>
<p>If you have more concrete problems, we are glad to help.</p>
|
What represents the most mentally challenging form of coding? <p>I am pursuing a graduate degree in Organic Chemistry.</p>
<p>Right now, many talented people in my area are headed towards nanotechnology.</p>
<p>What is the equivalent field in modern computer science?</p>
| <p>For me, it's threading. Even relatively "simple" threading is challenging, and if you delve into the realms of lock-free code it gets even hairier. There are certainly threading paradigms which <em>don't</em> raise as many mental headaches (actors, message passing etc) but they tend to come with their own trade-offs.</p>
<p>This is a level of "deep" complexity in my view, but there are other areas of coding which are challenging in different ways. Security, i18n and date/time handling (or pretty much anything related to actual <em>human</em> characteristics) is very finicky, with lots of corner cases to learn and watch out for. This is certainly hard, but in a different way to concurrency.</p>
<p>EDIT: As a response to twk's answer: yes, there are lots of people trying to make concurrency easier. While there are already various platforms which support concurrency well (e.g. Erlang) there's more of a move at the moment to bring simpler concurrency to already-mainstream platforms. From my point of view as a .NET developer (well, an amateur/enthusiast .NET developer anyway; professionally Java at the moment) the <a href="http://blogs.msdn.com/pfxteam/" rel="nofollow">Parallel Extensions</a> and <a href="http://en.wikipedia.org/wiki/Concurrency%5Fand%5FCoordination%5FRuntime" rel="nofollow">Coordination and Concurrency Runtime</a> are the two most interesting recent developments. I don't expect this to make concurrency <em>easy</em> - just <em>feasible for mortals</em>.</p>
|
Linq Query to Dataset <p>I got a linq query. I wanna take this query results to a dataset. How can I do this ?</p>
<pre><code>var variable = from t in db.Islems
where t.Tarih >= dateTimePicker1.Value
&& t.Tarih < dateTimePicker2.Value
select t;
DataSet ds = new DataSet();
</code></pre>
<p>I wanna load the query results to the dataset, then use it in Crystal Reports.</p>
| <p>Check the extension method that I posted <a href="http://stackoverflow.com/questions/523153/how-do-i-transform-a-listt-into-a-dataset/523168#523168">here</a>, it uses reflection and generics to convert any IEnumerable<T> collection to a DataTable.</p>
|
Most important things about C# generics... lesson learned <p>What are most important things you know about generics: hidden features, common mistakes, best and most useful practices, tips...</p>
<p>I am starting to implement most of my library/API using generics and would like to collect most common patterns, tips, etc., found in practice.</p>
<p>Let me formalize the question: What is the most important thing you've learned about generics?</p>
<p><strong>Please try to provide examples -- it would be easier to understand, as opposed to convoluted and overly-dry descriptions</strong></p>
<p>Thanks</p>
<p>This question is somewhat similar to <a href="http://stackoverflow.com/questions/215548/whats-the-hardest-or-most-misunderstood-aspect-of-linq?...I">Jon's question</a>, though, on a different subject.</p>
| <p>One of the most important things I've learned is that you can <a href="http://msdn.microsoft.com/en-us/library/d5x73970.aspx">constrain the generic type parameter(s)</a>. This can be very powerful, allowing you to take customize the class for only certain types of objects and allowing you to use the members of that type in your generic class. I realize that this is pretty fundamental, but it's one of the things that makes generics incredibly useful.</p>
|
Retrieving data with Selenium <p>I want to get the business hours from ScotiaBank branches that are near to me.</p>
<p>The base-URL is: <a href="http://maps.scotiabank.com/" rel="nofollow">http://maps.scotiabank.com/</a></p>
<p>I then,</p>
<p>Click on the "Branches" radiobox.</p>
<p>Click on the "Open Saturdays" checkbox.</p>
<p>Enter "B3H 1M7" (my postal code) into the search box.</p>
<p>Click the Search button.</p>
<p>Click on the first result that pops up (Micmac shopping centre).</p>
<p>Store the business hours as a variable (called businessHours).</p>
<p>And now I'm stuck.</p>
<p>How can I export the data that I assigned to the variable to a text file or anywhere else where I can view it later?
I'm not sure if this is even possible with Selenium, but if it's not, can you tell me an alternative of how I could do this?</p>
<p>Below is the HTML code for the current Selenium script that I have.</p>
<pre><code><tr>
<td>open</td>
<td>/en/index.php</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>rb_branch</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>cb_saturday</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>input_address</td>
<td>B3H 1M7</td>
</tr>
<tr>
<td>clickAndWait</td>
<td>btn_search_address</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>result0</td>
<td></td>
</tr>
<tr>
<td>storeTextPresent</td>
<td>Mon: 9:30 AM - 5:00 PM Thu: 9:30 AM - 8:00 PM
<br />Tue: 9:30 AM - 5:00 PM Fri: 9:30 AM - 5:00 PM
<br />Wed: 9:30 AM - 5:00 PM Sat: 9:00 AM - 1:00 PM</td>
<td>businessHours</td>
</tr>
</code></pre>
| <p>Here's an idea - if you can't write to a file or DB, you can certainly write quick little web app, and have selenium enter the data and click Submit there!</p>
|
Run db query (sql server 2005) with ajax. Is it possible? <p>I never worked with ajax.</p>
<p>I need to know if it is possible to use ajax to run a query on the db (sql server 2005).</p>
<p>My target is to run a query with refreshing the page.</p>
<p>Have you got any ideas?</p>
| <p>Directly, no. And that is a very good thing, since the JavaScript is generally running on an untrusted machine.</p>
<p>But it should be pretty easy to have your AJAX fire off a callback (e.g. a post) and then have that do the query on the server side.</p>
|
Silverlight page not catching input events <p>I have been attempting to handle the KeyDown event of a UserControl (page) in my Silverlight application, but there seems to be some strange behaviour on the part of Silverlight user input functionality. The event is not getting raised under any circumstance. I have even tried attaching the event handler to each container control within the UserControl, but still with no luck. Indeed, the Silverlight user input "event routing" system is quite novel and seems rather strange to me, so perhaps it is just a misunderstanding on my part, though I have rather clueless about how to proceed.</p>
<p>The following code is a template of the particular page with which I am testing.</p>
<pre><code><UserControl x:Class="MyNamespace.CreditsPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
KeyDown="UserControl_KeyDown">
<Grid x:Name="LayoutRoot">
<Border>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Vertical">
<TextBlock TextAlignment="Center">
A line of text.<LineBreak />
<LineBreak />
A line of text.<LineBreak />
<LineBreak />
A line of text.<LineBreak />
<LineBreak />
A line of text.<LineBreak />
</TextBlock>
</StackPanel>
</Border>
</Grid>
</UserControl>
</code></pre>
<p>In WPF, the obvious solution for such an issue would be to handle the PreviewKeyDown event, but unfortunately this is not available in Silverlight 2. Any ideas would be welcome (and a short explanation of why Silverlight event routing is behaving as it is).</p>
| <p>You can manage the user input from the main UIElement : Application.Current.RootVisual</p>
<pre><code>Application.Current.RootVisual.KeyDown += Application_KeyDown
</code></pre>
<p>Then you can handle in the Application_KeyDown method all user inputs from the keyboard.</p>
<p>You can also look at this issue : <a href="http://www.silverlightissues.com/issue.php5?i=18" rel="nofollow">Handling KeyDown event in a Canvas</a></p>
|
How do I run command line "explorer /n, /select,(filename)" in c++ builder? <p>I've tried shellexecute, I've tried createprocess, I can't seem to get this to do anything.</p>
<p>Running the command line manually (at the actual command prompt in a console window) works, but nothing I've tried so far will run it from within a c++ builder app.</p>
<p>Obviously (filename) is just a place holder. It would be given a valid file name, such as </p>
<p>explorer /n, /select,c:\123.doc</p>
| <p>Are you using escaped backslashes in your filename? For example:;</p>
<pre><code>"c:\123.doc"
</code></pre>
<p>should be:</p>
<pre><code>"c:\\123.doc"
</code></pre>
<p><strong>Edit:</strong></p>
<pre><code> execlp("explorer", "/n, /select,c:\\foo.txt", 0)
</code></pre>
<p>works for me.</p>
<p>To avoid replacing the the current process, use <strong>spawnlp</strong> instead</p>
|
Generation PDF from HTML (component for .NET) <p>Can you please point me to open source or a reasonably priced comercial product capable of generating PDF from HTML?</p>
| <p>We currently use ABCpdf in one of our more complex applications. It has served us well and is not very expensive at all. I like that fact that I can send it raw HTML text and it will render it to a PDF in memory or as a file so we use to generate PDFs on the fly and serve them up via the web without actually ever saving it disk ever.</p>
<p>We have been using it for about 3 years and early on I had to use their support for a very odd issue that was very specific and the support was very fast and help solved the issue quickly.</p>
<p>You can find more information on their website at:
<a href="http://www.websupergoo.com/abcpdf-1.htm">http://www.websupergoo.com/abcpdf-1.htm</a></p>
|
Business entities / value objects framework with DbC support <p>The thing I think I spend most time on when building my business models is the validation of business entities and making sure the entity objects and their relationships maintains good integrity. My dream for a good entity/value object framework would help me create reusable entities/value objects and easily create constraints and rules for relationships as you would in a db but since I feel this really is business rules they belong in the model and should be totally independent of the database.</p>
<p>It should be easy to define that the Name property of a Person object should be required and that the Email property should be required and match a certain regex and that these rules should be easily reusable f.ex. in validating input in my web app.</p>
<p>I have absolutely most experience with Linq to sql and even though it certainly is nice to work with it has limit by not supporting value objects and others. My question is would Entity framework or NHibernate be more suiting or are there other technologies that fit my needs better?</p>
| <p>There was a <a href="http://rads.stackoverflow.com/amzn/click/1430216468" rel="nofollow">small book I read last year by Steve Sanderson himself</a> that briefed me on DDD concepts. Even though the book was on ASP.NET MVC as a preview, he really focused on the "M" in MVC as a true and pure Domain Model - using almost 1/2 the book on modeling approaches (which I very much enjoyed). One thing he approached was using Value Objects in the context of Aggregate Roots (obviously). But, he also showed how to use Linq to represent the entities, as well as the Value Objects. </p>
<p>The point is, he noted the limitation of Linq that it must have an identity on every object, including Value Objects. He acknowledged it broke the pure domain model approach; but, it was the only way to get it to work with Linq-to-SQL. </p>
<p>His work-around was to give your Value Object an Identity; but, make that identity internal so it is not exposed outside of your model. This will allow you to link and share your objects using Linq in your repositories; while not exposing it to the client layers - so, it is as though they are Value Objects exclusively.</p>
<p>The Entity Framework I believe suffers from the same requirement.</p>
<p>A C# example is below.</p>
<pre><code>public class MyEntity
{
[Column(IsPrimaryKey = true
, IsDbGenerated = true
, AutoSync = AutoSync.OnInsert)]
public int EntityID { get; set; }
[Column(CanBeNull = false)]
public string EntityProperty
{
get
{
// insert business rules here, if need be
}
set;
}
}
public class MyValueObjectForMyEntity
{
// make your identity internal
[Column(IsPrimaryKey = true
, IsDbGenerated = true
, AutoSync = AutoSync.OnInsert)]
internal int ValueObjectID { get; set; }
// everything else public
[Column(CanBeNull = false)]
public string MyProperty { get; set; }
}
</code></pre>
|
How do you translate this code from Processing to C++? <p>I wrote this code in Processing (<a href="http://www.processing.org/" rel="nofollow">www.processing.org</a>) and was wondering how would one implement it using C++?</p>
<pre><code>int i = 0;
void setup()
{
size(1000,1000);
}
void draw()
{
// frameRate(120);
PImage slice = get();
set(0,20,slice);
if( i % 2 == 0 ) fill(128); else fill(0);
i++;
rect(0,0,width,20);
}
</code></pre>
<p>As you can see this simply scrolls down rectangles of alternating colors as fast as possible. Can the C++ implementation be as short? OpenGL?</p>
| <p>I'd probably use <a href="http://www.libsdl.org/" rel="nofollow">SDL</a> for this. Your program will be a little longer, because you'll have to do some setup and tear-down on your own (plenty of good examples, though). You could do the same with OpenGL, but it would be quite a bit more work. If you go that route, <a href="http://nehe.gamedev.net/" rel="nofollow">NeHe Productions</a> offers practically the gold standard in OpenGL tutorials.</p>
|
Navigation Based Application with TabBar <p>I have a Navigation-Based Application that shows a TableView where you can select a cell and it brings you to a "Detail View" for that cell. I want this view to then have a TabBar where I can select between 3 subviews. I have found several solutions online for this but none are very helpful. Is there a tutorial for this specifically or is their source code indicating how it can be done? Thanks</p>
| <p>Basically What you need to do is push a Tab View Controller onto the Navigation Controller's viewcontroller stack.</p>
<p>Starting with a fresh "Navigation-Based Application" template. I added the following method in RootViewController.m :</p>
<pre><code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//Navigation logic may go here. Create and push another view controller.
UIViewController *viewOneViewController = [[UIViewController alloc] init];
viewOneViewController.title = @"One";
viewOneViewController.view.backgroundColor = [UIColor redColor];
UIViewController *viewTwoViewController = [[UIViewController alloc] init];
viewTwoViewController.title = @"Two";
viewTwoViewController.view.backgroundColor = [UIColor orangeColor];
UIViewController *viewThreeViewController = [[UIViewController alloc] init];
viewThreeViewController.title = @"Three";
viewThreeViewController.view.backgroundColor = [UIColor greenColor];
UITabBarController *anotherViewController = [[UITabBarController alloc] init];
anotherViewController.viewControllers = [NSArray arrayWithObjects:viewOneViewController, viewTwoViewController, viewThreeViewController, nil];
[self.navigationController pushViewController:anotherViewController animated:YES];
[anotherViewController release];
</code></pre>
<p>}</p>
<p>Changed this to 25 to test: </p>
<pre><code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 25;
}
</code></pre>
<p>Now when I build and run I'll see what you are looking for in a basic way. What you will want to do after you get this working is to change the UIViewControllers to Custom Subclasses that you create to hold the code for each view. (If you are also using Interface Builder, change the init to initWithNibNamed:).</p>
<p>Hope this helps you get on your way a bit.</p>
|
Is there any way i can remove the line which is shown in MASKEDTEXTBOX fields when we set the mask? <p>The line that appears when we set the mask of a masked text box in winforms for c# does not seem attractive at all to me .I want to know if there is any way i can set the mask of
the masked text box and that line is not shown???</p>
| <p>In VB.NET, the MaskedTextBox has a property called PromptChar (I'm sure it's the same in C#). It defaults to the underscore that you see. Change that.</p>
|
How to pass information using an HTTP redirect (in Django) <p>I have a view that accepts a form submission and updates a model.</p>
<p>After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.</p>
<p>How can I "pass" this message to the other page? HttpResponseRedirect only accepts a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow">URL</a>. I've seen this done before on other sites. How is this accomplished?</p>
| <p>This is a built-in feature of Django, called "messages"</p>
<p>See <a href="http://docs.djangoproject.com/en/dev/topics/auth/#messages">http://docs.djangoproject.com/en/dev/topics/auth/#messages</a></p>
<p>From the documentation:</p>
<blockquote>
<p>A message is associated with a User.
There's no concept of expiration or
timestamps.</p>
<p>Messages are used by the Django admin
after successful actions. For example,
"The poll Foo was created
successfully." is a message.</p>
</blockquote>
|
collection of system properties using web browser <p>Hi I am doing distributed computing environment. For the applications need to get distributed to different clients connected to the server in the network, I prefered to collect the client's system properties like free memory available in the client's system, so that I could distribute the application according to that efficiently. Please give me some good idea. Thanks in advance</p>
| <p>Since you have tagged this with Java, I am assuming you are using a Java based client server model. What is the communication model between the client and the server here? RMI? Some proprietary protocol? Or is it a Java applet based app running in the browser?</p>
<p>Update based on clarification : In that case you can you can always collect the system properties inside the applet code and send them back to the server (maybe by using a servlet?)</p>
|
Why doesn't the weakref work on this bound method? <p>I have a project where i'm trying to use weakrefs with callbacks, and I don't understand what I'm doing wrong. I have created simplified test that shows the exact behavior i'm confused with. </p>
<p>Why is it that in this test test_a works as expected, but the weakref for self.MyCallbackB disappears between the class initialization and calling test_b? I thought like as long as the instance (a) exists, the reference to self.MyCallbackB should exist, but it doesn't.</p>
<pre><code>import weakref
class A(object):
def __init__(self):
def MyCallbackA():
print 'MyCallbackA'
self.MyCallbackA = MyCallbackA
self._testA = weakref.proxy(self.MyCallbackA)
self._testB = weakref.proxy(self.MyCallbackB)
def MyCallbackB(self):
print 'MyCallbackB'
def test_a(self):
self._testA()
def test_b(self):
self._testB()
if __name__ == '__main__':
a = A()
a.test_a()
a.test_b()
</code></pre>
| <p>You want a <a href="http://code.activestate.com/recipes/81253/">WeakMethod</a>. </p>
<p>An explanation why your solution doesn't work can be found in the discussion of the recipe:</p>
<blockquote>
<p>Normal weakref.refs to bound methods don't quite work the way one expects, because bound methods are first-class objects; <strong>weakrefs to bound methods are dead-on-arrival</strong> unless some other strong reference to the same bound method exists.</p>
</blockquote>
|
Modify VB property template in VS2008 <p>In VS2008 (VB.NET) when you type Public Property X As SomeType
and press enter, VS auto-generates the rest of that property definition for you.</p>
<p>I would like to be able to customize what VS generates.</p>
<p>Any thoughts on how to go about that? VS must have a template for it somewhere, eh?</p>
<p>Thanks.</p>
| <p>I think that the Property generation uses an inbuilt macro. I haven't found it in the list of sample macros provided with VS. However, you can edit the <code>DefineAProperty.snippet</code>* file to modify it as per your requirement. Personally, though, I would suggest creating your own snippet rather than modifying the pre-installed ones.</p>
<p>Some links to more information/Snippet Editors:</p>
<ol>
<li><a href="http://msdn.microsoft.com/en-us/library/ms165392.aspx" rel="nofollow">Creating and using Snippets - MSDN</a></li>
<li><a href="http://msdn.microsoft.com/en-us/vbasic/bb973770.aspx" rel="nofollow">Code snippet editor for VB 2008</a></li>
<li><a href="http://www.codeplex.com/SnippetDesigner" rel="nofollow">Snippet Designer - CodePlex</a></li>
</ol>
|
PSExec: How can I show a JPG file on a remote computer? <p>I need to start a document on a remote computer instead of an executable file, using PSExec.</p>
<p>I tried to provide the file name of a jpg file to psexec associated with the -c command to copy the file, but the message returned for documents (and not executables) is always "The system cannot find the file specified."</p>
<p>Anyone any ideas what the command-line for psexec should be?</p>
| <p>Try to use the command:</p>
<pre><code>cmd.exe /c START c:\path\to\document.jpg
</code></pre>
<p>Document must be on the remote computer, so you have to copy it there by other command before calling psexec.</p>
|
static member variable of a subclassed class <p>Is it OK to have a static member variable defined in a base class, and having several derived classes each using its own instance of this member variable?</p>
<p>The following code compiles successfully, and prints the right output, but I am still not sure that doing something like that is a good practice. <strong>In the following example, how can it work, if I explicitly define only one instance of s (by calling: string A::s;) but I actually use 2 instances?</strong></p>
<pre><code>class A
{
protected:
void SetS(string new_s){s = new_s;}
void PrintS(){cout << s << endl;};
private:
static string s;
};
class B : public A
{
public:
void foo(){ SetS("bbb"); PrintS();};
};
class C : public A
{
public:
void foo(){ SetS("ccc"); PrintS();};
};
string A::s;
int main()
{
B b;
b.foo(); // results in output: bbb
C c;
c.foo(); // results in output: ccc
b.foo(); // results in output: bbb
}
</code></pre>
| <p>A very odd use of inheritance indeed. The base class is supposed to define interfaces ideally and contain as little or no state at all if possible according to good OO design principle. </p>
<p>This works because your <code>foo()</code> resets the value of <code>A::s</code> everytime it is called. Try printing the address of <code>A::s</code>. There is one and only one object. This will not work if you don't set the value everytime and you have multiple objects using another member function <code>bar()</code> to read the value of A::s.</p>
<p>You may run into sync issues if <code>B</code> and <code>C</code> objects are created in separate threads as well. You will end up with UB.</p>
|
How to include() all PHP files from a directory? <p>Very quick n00b question, in PHP can I include a directory of scripts.</p>
<p>i.e. Instead of:</p>
<pre><code>include('classes/Class1.php');
include('classes/Class2.php');
</code></pre>
<p>is there something like:</p>
<pre><code>include('classes/*');
</code></pre>
<p>Couldn't seem to find a good way of including a collection of about 10 sub-classes for a particular class.</p>
| <pre><code>foreach (glob("classes/*.php") as $filename)
{
include $filename;
}
</code></pre>
|
Do i need one SocketAsyncEventArgs for each client connection made? <p>Please do i need a new SocketAsyncEventArgs for each client connection i make.</p>
<p>I'm making several client connections in a loop, filling in the UserToken for each clients state from a database.</p>
<p>Is there a way to reuse the SocketAsyncEventArgs and still maintain separate UserToken state for each connection.</p>
<p>Thanks.</p>
| <p>This question is slightly old but it's still relevant in my opinion. I suggest the following links for reference:</p>
<ul>
<li><a href="http://www.codeproject.com/KB/IP/socketasynceventargssampl.aspx" rel="nofollow">How to use the SocketAsyncEventArgs class</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.aspx" rel="nofollow">SocketAsyncEventArgs Class</a></li>
</ul>
<p>I do recommend the codeproject link as the server implements a SocketAsyncEventArgs pool (which answers your question). Do note however that that code has issues that need to be resolved.</p>
|
TransforMiiX (XML/XSLT) <p>If you have a look at <a href="http://www.polldaddy.com" rel="nofollow">www.PollDaddy.com</a> you will see that for every question you add a resulting xml and xslt file are requested and when recieved they are transformed. </p>
<p>Then when you save your page you will see that the adjusted xml file (your filled in question data) is send back to the server to be saved to the database.</p>
<p>I would like to make something similar like this technique but I cannot get my transformed xml to html back to its original xml format with adjusted data. Does anyone know how I could do this?</p>
| <p>I haven't used PollDaddy, but my guess is that they are not actually storing XML in the database. Most likely, it is being generated server-side for every request. The process would look something like this:</p>
<ol>
<li>Browser requests a specific question</li>
<li>Server retrieves question detials from database</li>
<li>Server generates XML based on question data</li>
<li>Server responds with XML and XSLT</li>
<li>User answers question</li>
<li>Browser posts raw answer data to server</li>
<li>Server updates database with answer data</li>
<li>Server generates XML based on question/answer data</li>
<li>Server responds with XML and XSLT</li>
</ol>
<p>It would be very inefficient to transform HTML to XML and push that up with requests.</p>
|
How to convert byte array to string in Common Lisp? <p>I'm calling a funny API that returns a byte array, but I want a text stream. Is there an easy way to get a text stream from a byte array? For now I just threw together:</p>
<pre><code>(defun bytearray-to-string (bytes)
(let ((str (make-string (length bytes))))
(loop for byte across bytes
for i from 0
do (setf (aref str i) (code-char byte)))
str))
</code></pre>
<p>and then wrap the result in with-input-from-string, but that can't be the best way. (Plus, it's horribly inefficient.)</p>
<p>In this case, I know it's always ASCII, so interpreting it as either ASCII or UTF-8 would be fine. I'm using Unicode-aware SBCL, but I'd prefer a portable (even ASCII-only) solution to a SBCL-Unicode-specific one.</p>
| <p>FLEXI-STREAMS (<a href="http://weitz.de/flexi-streams/">http://weitz.de/flexi-streams/</a>) has portable conversion function</p>
<pre><code>(flexi-streams:octets-to-string #(72 101 108 108 111) :external-format :utf-8)
=>
"Hello"
</code></pre>
<p>Or, if you want a stream:</p>
<pre><code>(flexi-streams:make-flexi-stream
(flexi-streams:make-in-memory-input-stream
#(72 101 108 108 111))
:external-format :utf-8)
</code></pre>
<p>will return a stream that reads the text from byte-vector</p>
|
OnMouseDown, OnMouseMove and a Custom Control <p>I'm developing an app for <strong>windows mobile</strong>. I have my own control that moves the picture inside it. I have overrided the <strong>OnMouseDown</strong> and <strong>OnMouseMove</strong> to redraw the picture where the user move it.</p>
<p>I only test it on Windows Mobile 6.1 Professional emulator. It works but I have a problem:</p>
<p>I click on the image, move it with the mouse, stop moving holding down the left button of the mouse, wait a seconds and the release the button without moving the mouse and the picture moves again. What it's happenning?</p>
<p>I think that the event <strong>OnMouseMove</strong> is fired with the event <strong>OnMouseUp</strong> but I'm not sure.</p>
<p>Thank you!</p>
| <p>I have never tryed some thing on windows mobile, but if your unsure of the events then make a multi line textbox and add some text to it each time a even is fired that way you should know when its fired..</p>
|
Python: Choosing between modules and classes <p>In my application I have to maintain some global application state and global application wide methods like currently connected users, total number of answers, create an application config file etc. There are two options:</p>
<ol>
<li><p>Make a separate appstate.py file with global variables with functions over them. It looks fine initially but it seems that I am missing <em>something</em> in clarity of my code.</p></li>
<li><p>Create a class AppState with class functions in a appstate.py file, all other modules have been defined by their specific jobs. This looks fine. But now I have to write longer line like appstate.AppState.get_user_list(). Moreover, the methods are not so much related to each other. I can create separate classes but that would be too many classes.</p></li>
</ol>
<p>EDIT: If I use classes I will be using classmethods. I don't think there is a need to instantiate the class to an object.</p>
| <p>Sounds like the classic conundrum :-) In Python, there's nothing dirty or shameful about choosing to use a module if that's the best approach. After all, modules, functions, and the like are, in fact, first-class citizens in the language, and offer introspection and other properties that many other languages use objects to obtain.</p>
<p>The way you've described your options, it kinda sounds like you're not too crazy about a class-based approach in this case.</p>
<p>I don't know if you've used the Django framework, but if not have a look at their documentation on how they handle settings. These are app-wide, they are defined in a module, and they are available gobally. The way they parse the options and expose them globally is quite elegant, and you may find such an approach inspiring for your needs.</p>
|
force firefox to get most current version of silverlight app <p>This question <a href="http://stackoverflow.com/questions/307709/how-do-you-force-firefox-to-not-cache-or-re-download-a-silverlight-xap-file">has been asked before</a> but 1) the user never accepted an answer 2) none of them stand out as better than the others (votes-wise) and 3) the asker seems to have forgotten about it. So I'm going to ask it again so I can get to an accepted answer. And some of the users in the thread have said that some of the solutions didn't work. Sorry for cluttering up the place, but I promise to get to the bottom of this. </p>
<p>I ran into this problem the other day when I was looking at my Silverlight app in Firefox. I made a change to the location of an image and it didn't move. I assumed I did it wrong, but then I looked at IE7 and the image was in the right place. Turns out Firefox was displaying a cached version of the file; the changes I made didn't show up. </p>
<p>This is a larger problem: if I change my app (let's say it's an urgent typo correction) how can I force the end user to see the most current version of my Silverlight app? Is <a href="http://timheuer.com/blog/archive/2008/09/24/silverlight-isolated-storage-caching.aspx" rel="nofollow">isolated storage (Heuer's blog)</a> really the only way to force an update from the server side? Clearing the Firefox cache is not going to work for a push update; I need the update to propagate without the end user doing anything. </p>
<p>Update: <a href="http://msdn.microsoft.com/en-us/magazine/2009.01.cuttingedge.aspx" rel="nofollow">Dino Esposito</a> has some ideas about controlling this, specifically using the Expires property of the Response object. Haven't had a chance to try this yet. </p>
| <p>Can you encode the version number or timestamp in the filename? That way, if the page changes, Firefox will notice that it points to a completely different resource and will reload it.</p>
|
Excessive static buildup <p>And here we go with my first not-directly-programming-related question on SO!</p>
<p>I seem to suffer from an excessive amount of static buildup (the electrical kind, not the type modifier). This, of course, manifests itself as getting the crap shocked out of me pretty much any time that I touch anything that even thinks it's grounded. No kidding, my days usually go like this:</p>
<p>Wake up, possibly get shocked hitting the snooze button. Touch the lightswitch in my bedroom, usually get shocked. Walk down the hall to my office, touch that lightswitch, get shocked. Sit down at the computer, touch the case to discharge (usually does). Walk out the door, get in the car (zap). Drive to work, get out of the car (zapped closing the door). Walk into the office, get zapped by the door frame...</p>
<p>It's not quite THAT bad, I suppose, but I easily get shocked 10-20 times daily, by everything from my chair to the dog to my wife (let me tell you how much she enjoys THAT). Just today, I fried my second mouse via zapping (but this time I had the replacement plan! Ha ha!). In the past, I have shorted out my cars entire electrical system simply by locking the doors. (The electric locks STILL don't work right). Of course, no one around me seems to have this issue, and it's gotten to be aggravating. I'm thinking of ditching programming and becoming a supervillan instead. (The Shocker!)</p>
<p>So here's my question(s):</p>
<p>1) What might I be doing that would cause me to build up excessive static? I realize this is a broad question, but I can't think of anything that I do that would provoke it. (I don't shuffle my feet as I walk or anything). I general, what are common causes of it?</p>
<p>2) Does the SO crew have any recommendations for how to manage it, ESPECIALLY around computer equipment. I suppose I could keep a static bracelet at my desk but the idea of constantly being tethered to an outlet while computing isn't really a happy thing...</p>
<p>Any suggestions? </p>
| <p>Remember that static electricity is usually produced by certain materials rubbing together. So you might want to look at the materials of the things around you and see if less-static inducing items could be used instead.</p>
<p>Humidity (or lack thereof) increases static buildup. Get a humidifier at home at least.</p>
<p>Learn to not approach metal objects with a finger extended. Go in with your palm out, and try to get a larger surface on the object. When successful, you'll notice the shock less because it will be spread over a larger area.</p>
<p>You might want to try to get (or have your employer get) an ESD mat for your desk. If you have electronics work in your building, they'll already know what you are talking about. This mat (when properly grounded) turns a surface into a high-resistance ground plane. This means any time your arm is on your desk, you're grounded, which would help you greatly.</p>
|
Database Structure & Hard drive seek time confusion <p>could some one help me out trying to understand how hard drive seeking works.</p>
<p>I have a small binary database file which read performance is absolutely essential. If I need to skip a few bytes in the file is it quicker to use seek() or to read() then discard the unwanted data.</p>
<p>If the average seek time of a hard drive is 10ms and the read speed is 300MB/s I calculated that it's quicker to read() than seek() with a value smaller than 3MB. Is true? Is there an overhead when performing a new seek, which reading an existing stream doesn't have?</p>
<p>Which do you think be a more suitable file structure for an index.</p>
<pre><code>Entry1:Value:PointerIntoToData
Entry2:Value:PointerIntoToData
Entry3:Value:PointerIntoToData
Data, Data, Data
Or
Entry1:Value:Data
Entry2:Value:Data
Entry3:Value:Data
</code></pre>
<p>When reading an entry if the value is not correct it will be ignored. So when streaming the file is it quicker to:
1. when an entry is not required use seek() to skip over it
2. when a entry is not needed read it then discard the data
3. or the use first structure, when an entry is required seek() into a data repository at the end.</p>
<p>Entry is 4 bytes, value is 8 bytes & data is 12KB</p>
<p>Cheers</p>
| <p>All <em>seek</em> system call does is changing a position in file where the next read will be. It does not move the drive head. Drive heads move when data is read or written and you don't have direct control over what OS will do next.</p>
<p>Reading lots of data you aren't going to need has impact because all read data needs space in OS buffers and causes older data to be discarded. So using seek over big files will mess with filesystem cache less.</p>
<p><hr /></p>
<p>All I write beneath assumes you cannot fit whole database in memory. If you can, just do that. Read everything and try to append new and changed data at the end of file. Don't worry about wasted space, just do some compacting once in a while.</p>
<p><hr /></p>
<p>If your database is too big:</p>
<p>Data is read and written to physical drive in blocks (or pages). Similarly the basic unit of disk IO in your OS is page. If OS caches data from disk it's also in whole pages. So thinking whether you need to move forward few bytes using seek or read makes little sense. If you want to make it fast, you need to take into account how disk IO really works.</p>
<p>First, already mentioned by nobugz, locality of reference. If the data you use in each operation is located close together in a file, your OS will need to read or write less pages. On the other hand, if you spread your data, many pages will need to be read or written at once, which will always be slow.</p>
<p>As to data structure for index. Typically they are organized as <a href="http://en.wikipedia.org/wiki/B-tree" rel="nofollow">B-trees</a>. It's a data structure made especially for effective searching of large quantities of data stored in memory with paged reads and writes.</p>
<p>And both strategies for organizing data is used in practice. For example, MS SQL Server by default stores data the first way: data is stored separately and indices only contain data from indexed columns and physical addresses of data rows in files. But if you define clustered index then all data will be stored within this index. All other indexes will point to the data via clustered index key instead of physical address. The first way is simpler but the other may be much more effective if you often do scans of ranges of data based on clustered index.</p>
|
Zend Framework PDF generation unicode issue <p>I have troubles using Zend Framework's PDF</p>
<p>When I create PDF file I need to use UTF-8 as encoding.
This is the code I am using to generate simple pdf file.
I always get this wrong displayed.
Instead of seeing 'Faktúra' in pdf file, it gives me 'Faktú'
Instead of seeing 'Dodávateľ:' in pdf file, it gives me 'Dodáva'</p>
<pre><code>$pdf = new Zend_Pdf();
$pdf->pages[] = ($page1 = $pdf->newPage('A4'));
$font = Zend_Pdf_Font::fontWithPath('C:\WINDOWS\Fonts\TIMES.TTF');
$page1->setFont($font, 20);
$page1->drawText('Faktúra', 40, 803, 'UTF-8');
$page1->drawText('Dodaváteľ:', $width_left, $height, 'UTF-8');
</code></pre>
<p>So I tried to load font from Windows directory</p>
<pre><code>$font = Zend_Pdf_Font::fontWithPath('C:\WINDOWS\Fonts\TIMES.TTF');
</code></pre>
<p>But it gives me the error:</p>
<blockquote>
<p>Fatal error: Uncaught exception
'Zend_Pdf_Exception' with message
'Insufficient data to read 2 bytes'</p>
</blockquote>
<p>It is really driving me crazy and I believe some of you would have little hints for me:)
Solving the error would be the best solution... </p>
<p>Thanks a lot in advance</p>
| <p>Did you save the php source file as UTF-8?</p>
|
How to open multiple files with Delphi program invoked via shell open <p>I am currently using:</p>
<pre><code>if ParamStr(1)<>'%1' then
begin
address.Text:=ParamStr(1);
autoconfigfile;
end;
</code></pre>
<p>to pick up the name of the file that was used to open the file with via file association.</p>
<p>I now want to develop the ability to operate on multiple files.
I.e. if I select 5 files and right click and select open with "EncryptionSystem".
I have the registry entry:</p>
<pre><code> reg.OpenKey('*\shell\Encrypt\command', true);
reg.WriteString('','C:\Program Files\EncryptionSystem\EncryptionSystem.exe "%1"');
reg.CloseKey;
</code></pre>
<p>To add a right click open ability to all files. I would then want the ability to detect </p>
<ol>
<li>how many files</li>
<li>the pathname of each file</li>
</ol>
| <p>Besides everything else, you should use %l instead of %1. That way your program will get a full (long) name of the file, not the short (DOS 8.3) one.</p>
<p>EDIT: An answer to Rob's question in comments</p>
<p>It seems that it's almost impossible to search for '%l' and '%1' (including percent sign) either using Google or MSDN search. :( However, I found a pretty good description in
<a href="http://blogs.msdn.com/oldnewthing/archive/2004/10/20/245072.aspx" rel="nofollow" title="where else?">The Old New Thing</a> - '%1' autodetects whether your program supports long file names and passes either short or long name. It seems that all modern systems pass long name <em>unless your exe cannot be found</em> (at least that's how I understand the Raymond's expose).</p>
<p>If you scroll further down in the comments (search for '%l' on the page) you'll find a list of all supported parameters, taken from some page that doesn't exist anymore (but I found an old copy in the <a href="http://web.archive.org/web/20020208233905/%68ttp://users.lia.net/chris/win32/explorer.asp" rel="nofollow">Internet Archive</a>). That page doesn't include no reference to Microsoft documentation either, so I can't give you an authoritative link :(</p>
<p>Rob, thank's for asking - I now know more about %1/%l than before :) +1 for that.</p>
|
Simple open source paint program <p>I am trying to experiment with expanding paint-like program adding custom features to it. Can you suggest a simple open source paint-like program written in C and using GTK+ library which I could expand? It should compile in Linux but also in Windows (using MinGW). Thanks.</p>
<p>EDIT:</p>
<p>I found <a href="http://mtpaint.sourceforge.net/" rel="nofollow">this</a> and it looks like something I was looking for, but I want something more simple if it exists.</p>
| <p>I never had this urge, but my 4 year old daughter loves <a href="http://www.tuxpaint.org/" rel="nofollow">TuxPaint</a>. I believe it uses GTK+.</p>
|
In the Eclipse JDT, how do I most efficiently find a typeroot in the workspace corresponding to a fully qualified name? <p>The JavaCore class includes a create method that allows me to get the ITypeRoot (representation of class file or compilation unit) given a handle identifier that embodies the location of the file.</p>
<p>However, I am trying to find the typeroot (if there is one) that corresponds to a specific fullname.</p>
<p>The only implementation that I can think of is to scan all the types in the system, get the type root on each of them (not even sure how to do that), and then compare FQNs.</p>
<p>Any help would be appreciated.</p>
| <p>From the JavaCore singleton, try:</p>
<pre><code>ITypeHierarchy myHierarchy = newTypeHierarchy(IRegion region, WorkingCopyOwner owner, IProgressMonitor monitor);
</code></pre>
<p>Once you have the hierarchy, you can traverse class file hierarchies as ITypes pretty easily.</p>
|
How do I Click a Table tag using watiN? <p>This is the table tag which i need to click . I guess this is invokes some JS function. I dont know howto resolve it .</p>
<p>table id="btnTbl_compose:send_message" class="buttonTable axsButton" cellpadding="0" title="Send this message (Ctrl+Enter) | Send this message and keep existing Draft (Shift+Click)" boid="messageToolbar_compose:send_message" cmd="compose:send_message" state="normal" style="" onmouseover="Uo.Z(event, this)" unselectable="on">
Send
</p>
| <p>I think (as far as I go your issue) this line will work for you:</p>
<pre><code>ie.Table("btnTbl_compose:send_message").Click()
</code></pre>
|
The file an IconRef comes from <p>Is there any way to find out the .icns file an IconRef refers to or has been loaded from? Or even the id of the containing bundle if there is one?</p>
<p>I understand that not all icons are loaded directly from a file (composite icons for example) so this wouldn't work all the time.</p>
<p>The question I'm trying to answer is "Where does the icon the Finder would display for file X originate?" Note that I'm interested in the origin of the icon in the file system, not the icon's image data. As far as I can tell, the workings behind going from file path to icon - eg. GetIconRefFromFileInfo and NSWorkspace.iconForFile - are fairly opaque.</p>
<p>I'm open to undocumented/private solutions if that's what it takes.</p>
<p>@millenomi:
Yes, avoiding Apple's icons is the point of the exercise.</p>
| <p>Launch Services has private APIs for traversing its bundle registration database, and you can find the .icns files that way. You can view this information using the lsregister tool inside LaunchServices.framework/Support; use lsregister -dump to view the complete database.</p>
<p>Obligatory UndocumentedGoodness warning: If you use these functions, your app will break sooner or later. (And parsing the output of lsregister -dump is an even worse idea!)</p>
<p>Also, you seem to be aware of this but I'll point it out anyway: Not all icons come from a .icns file. Some are in resource files, such as in an old-style Carbon application. Another case is custom (pasted into the Finder's Info window) icons, which are one or more resources of ID -16455. (Classical icons are in multiple resources of types 'icl8', 'ics8', etc., whereas modern icons are in a single resource of type 'icns'.)</p>
<p>Unfortunately, I haven't played with this private API, so I can't be more specific.</p>
|
Reposition Air NativeWindow when Maximized? <p>How can I set the native window position when maximized?</p>
<p>I've tried repositioning it upon the DISPLAY_STATE_CHANGE event which sort of works - but the window flashes at maximized size before repositioning, and more importantly the 'maximize' button of the window is still active.</p>
<p>What I'm trying to achieve is simply a fixed width window that is 'docked' to the right of the screen when maximized while still utilizing the restore/maximize native window button functionality.</p>
<p>I should note that I have set the maxSize and minSize and that is working fine.</p>
<p>Thanks in advance - b</p>
| <p>Try with NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING</p>
|
JQuery/Javascript Reordering rows <p>I have a aspx page that looks something like this:</p>
<pre><code><tr id="Row1">
<td>Some label</td>
<td>Some complex control</td>
</tr>
<tr id="Row2">
<td>Some label</td>
<td>Some complex control</td>
</tr>
<tr id="Row3">
<td>Some label</td>
<td>Some complex control</td>
</tr>
</code></pre>
<p>As soon as the page is loaded, I would want to reorder these rows based on the user's previously selected order (stored in a database)</p>
<p>How would I use JQuery/JS to accomplish this?</p>
<p>EDIT:</p>
<p>I have run into a performance issue with the appendTo code. It takes 400ms for a table of 10 rows which is really unacceptable. Can anyone help me tweak it for performance?</p>
<pre><code>function RearrangeTable(csvOrder, tableId)
{
var arrCSVOrder = csvOrder.split(',');
//No need to rearrange if array length is 1
if (arrCSVOrder.length > 1)
{
for (var i = 0; i < arrCSVOrder.length; i++)
{
$('#' + tableId).find('[fieldname = ' + arrCSVOrder[i] + ']').eq(0).parents('tr').eq(0).appendTo('#' + tableId);
}
}
}
</code></pre>
| <p>Why not order the rows on the server side? If you are going to reorder them with JQuery as soon as the page is loaded then it will be more efficient to do this job in server code, especially if the user's selected order is stored in a database.</p>
|
Should I save strings returned by NSLocalizedString()? <p>I'm working on an iPhone app that we're localizing in both English and Japanese for our initial release. We frequently call <code>NSLocalizedString()</code> to load the appropriate localized string for display. Is it generally better to save the localized strings in instance variables for the next time we need them, or am I micro-optimizing here and should I just reload the string each time it's needed?</p>
| <p>Micro-optimizing. First make it work, then make it right, then make it fast. And when you get to step 3, run Shark (or Instruments), then follow its guidance.</p>
|
divs collapsing around header <p>I have a few nested divs:</p>
<pre><code><div id="wrapper">
<div id="header">
<!-- a bunch of float divs here -->
</div>
<div id="body">
<div id="content">
<!-- a bunch of html controls here -->
</div>
</div>
</div>
</code></pre>
<ul>
<li>wrapper style: <code>width: 780px; margin:
20px auto; border: solid black 5px;</code></li>
<li>header style: <code>position: relative;
min-height: 125px;</code></li>
<li>body style: <code>position: relative;</code></li>
<li>content style: <code>position: absolute;
left: 50px; top: 0px;</code></li>
</ul>
<p>I have a bunch of html elements in the content div and for some reason the body div and the wrapper div are collapsing around the header and the content div hangs out on its own if I don't set a fixed height for the body div. The only float elements I have are in the header.</p>
<p><strong>EDIT</strong>:</p>
<p>If I remove the content div (and drop the html elements directly in body) the body div stops collapsing! Trying to understand why - guess it's due to the position: absolute of the content div.</p>
<p>Any clue why this is happening and how to solve?</p>
<p>I had a look at <a href="http://stackoverflow.com/questions/370432/div-collapse-after-float-css">this question</a> but It doesn't seem to work for me (or maybe I am clearing inthe wrong place...).</p>
| <p>Try this. Note: the overflow hidden on the header div solves the need for a clearing div. Note sure why you're using relative+absolute positioning for the content though. That's better handled with margins imho.</p>
<pre><code><html>
<head>
<title>Layout</title>
<style type="text/css">
#wrapper { width: 780px; margin: 20px auto; border: solid black 5px; }
#header { overflow: hidden; background-color: yellow; }
#header div { float: right; border: 2px solid red; }
#body { position: relative; }
#content { position: absolute; left: 50px; top: 0px; }
</style>
</head>
<body>
<div id="wrapper">
<div id="header">
<div>One</div>
<div>Two</div>
<div>Three</div>
</div>
<div id="body">
<div id="content">
<p>This is some text</p>
</div>
</div>
</div>
</body>
</html>
</code></pre>
|
Errors on non model fields in rails <p>What's the best way to report errors on form fields not associated with a particular model in Rails? As an example, I have a form for the batch creation of user accounts with random users / passwords. It takes as inputs the quantity of users to make, information about what attributes all users should have, and information about the batch which is stored in a user_batches model associated with the created users.</p>
<p>Ideally there would be some <code>errors_on</code> like way to list errors coming from the quantity field, which is associated with no model, the user information fields, associated with the user records that get created, and the user_batches model with minimal code.</p>
<p>This also applies to search forms and the like, which don't get run through AR validations. Any ideas?</p>
| <p>You can add your own errors manually to your model object like this.</p>
<pre><code>@user_batch.errors.add_to_base("Foo")
</code></pre>
|
Browser Version or Bug Detection <p>I've recently seen some information about avoiding coding to specific browsers an instead using feature/bug detection. It seems that John Resig, the creator of jQuery is a big fan of feature/bug detection (he has an excellent talk that includes a discussion of this on <a href="http://video.yahoo.com/watch/4403981/11812238" rel="nofollow">YUI Theater</a>). I'm curious if people are finding that this approach makes sense in practice? What if the bug no longer exists in the current version of the browser (It's an IE6 problem but not 7 or 8)?</p>
| <p>Object detection's greatest strength is that you only use the objects and features that are available to you by the client's browser. In other words given the following code:</p>
<pre><code>if (document.getFoo) {
// always put getFoo in here
} else {
// browsers who don't support getFoo go here
}
</code></pre>
<p>allows you to cleanly separate out the browsers without naming names. The reason this is cool is because as long as a browser supports <code>getFoo</code> you don't have to worry which one it is. This means that you may actually support browsers you have never heard of. If you target user agent strings find the browser then you only can support the browsers you know.</p>
<p>Also if a browser that previously did not support <code>getFoo</code> gets with the program and releases a new version that does, you don't have to change your code at all to allow the new browser to take advantage of the better code.</p>
|
Linq to SQL Updating through BLL issues - Best Practices <p><strong>The Setup:</strong></p>
<p>I have a large form with many fields that are collected to update a Product object. So in the ASPX page the user changes the fields that need updating and they hit submit. In the code behind I do something like this;</p>
<pre><code>Dim p as New MyCompany.Product()
p = p.GetProductById(ProductID)
</code></pre>
<p>I extend the Product partial class of Linq to SQL to add this method (GetProductById) to the object</p>
<pre><code>p.Name = txtName.Text
p.SKU = txtSKU.Text
p.Price = txtPrice.Text
...
p.Update()
</code></pre>
<p>This is an Update method in the extended Product partial class. I update the database, send emails and update history tables so i want this method to do all those things.</p>
<p>There are 50 more fields for the project so obviously it would be ridiculous to have a method that collects all 50 fields (and I don't want to go that route anyway bc it's harder to debug IMO)</p>
<p><strong>The Problem:</strong></p>
<p>If I get the Product via Linq to SQL using a DataContext then I can never update it again because it errors about not being able to attach and entity that's already attached to another DataContext.</p>
<p><strong>The Question:</strong></p>
<p>SO if I get an object through a method in my BLL, update it in the ASPX page and then try to send the updates through the BLL again to update the database, how should I go about doing this?</p>
| <p>Regardless of LINQ-to-SQL or not, here's what I do. Upon submission, I search for the item (it should be quick if it is a single item using the PK), my DAL returns a data object, and I use reflection to map each element in the page with corresponding properties in the data object. My DAL only updates items that changed. </p>
<p>I think what you have to do is the same, gathering all values and submitting them. If LinqToSql is not smart enough to determine what changed then it may not be the best alternative.</p>
|
why does printf show a 0 for vector size when cout shows the correct size? <p>I don't get why I get 0 when I use printf and %d to get the size of my vector:</p>
<pre><code>vector<long long> sieve;
int size;
...
//add stuff to vector
...
size = sieve.size();
printf("printf sieve size: %d \n", size); //prints "printf sieve size: 0"
std::cout << "cout sieve size: ";
std::cout << size;
std::cout << " \n ";
//prints "cout sieve size: 5 (or whatever the correct sieve size is)"
</code></pre>
<p>If I iterate through the vector via </p>
<pre><code>if(i=0;i<sieve.size();i++)
</code></pre>
<p>I get the correct number of iterations.</p>
<p>What am I doing wrong or what is up with printf? size() returns an int right??</p>
<p><hr /></p>
<p>Here's my entire little script:</p>
<pre><code>#include <iostream>
#include <vector>
#include <stack>
#include <math.h>
int main (int argc, char * const argv[]) {
unsigned long long answer = 0;
unsigned long long cur = 2;
std::vector<long long> sieve;
unsigned long long limit;
unsigned long long value;
unsigned int i;
int size;
bool isPrime;
std::cout << "Provide a value to find its largest prime factor: ";
std::cin >> value;
limit = ceil(sqrt(value));
sieve.push_back(2);
while(cur++ < limit){
isPrime = true;
sieve.begin();
for(i=0; i<sieve.size();i++){
if(!(cur % sieve[i])){
isPrime = false;
break;
}
}
if(isPrime){
if(!(value % cur)){
std::printf("Is prime factor: %d\n", cur);
sieve.push_back(cur);
answer = sieve[sieve.size() - 1];
size = sieve.size();
std::printf("current last: %d sieve size: %ld\n", answer, size);
for(i=0; i<sieve.size();i++){
std::printf("sieve iter: %d sieve val: %d\n", i, sieve[i]);
std::cout << size;
std::cout << " wtf\n";
}
}
}
}
answer = sieve[sieve.size() - 1];
size = sieve.size();
std::printf("Limit: %d Answer: %d sieve size: %ld\n", limit, answer, size);
return 0;
}
</code></pre>
| <p>Now, with the complete source, it is clear.</p>
<p>You declared:</p>
<pre><code>int size;
</code></pre>
<p>Then you used:</p>
<pre><code>std::printf("current last: %d sieve size: %ld\n", answer, size);
std::printf("Limit: %d Answer: %d sieve size: %ld\n", limit, answer, size);
</code></pre>
<p>If size is int, you should use "%d", not "%ld". A good compiler would have warned you about this. GCC gives these warnings for your original version:</p>
<pre><code>test.cpp: In function âint main(int, char* const*)â:
test.cpp:17: warning: converting to âlong long unsigned intâ from âdoubleâ
test.cpp:30: warning: format â%dâ expects type âintâ, but argument 2 has type âlong long unsigned intâ
test.cpp:34: warning: format â%dâ expects type âintâ, but argument 2 has type âlong long unsigned intâ
test.cpp:34: warning: format â%ldâ expects type âlong intâ, but argument 3 has type âintâ
test.cpp:36: warning: format â%dâ expects type âintâ, but argument 3 has type âlong long intâ
test.cpp:45: warning: format â%dâ expects type âintâ, but argument 2 has type âlong long unsigned intâ
test.cpp:45: warning: format â%dâ expects type âintâ, but argument 3 has type âlong long unsigned intâ
test.cpp:45: warning: format â%ldâ expects type âlong intâ, but argument 4 has type âintâ
</code></pre>
<p>This tells a lot.</p>
<p>You should declare size as: </p>
<pre><code>std::vector<long long>::size_type size;
</code></pre>
<p>Then you should use it as:</p>
<pre><code>std::printf("current last: %llu sieve size: %llu\n", (unsigned long long) answer, (unsigned long long) size);
std::printf("Limit: %llu Answer: %llu sieve size: %llu\n", (unsigned long long) limit, (unsigned long long) answer, (unsigned long long) size);
</code></pre>
<p>Of course, using iostream avoids you these problems, specially the ugly casting in printf() to transform size to a type known to printf.</p>
|
What is SQL injection? <blockquote>
<p><strong>Possible Duplicates:</strong></p>
<p><a href="http://stackoverflow.com/questions/332365/xkcd-sql-injection-please-explain">XKCD SQL injection - please explain</a><br />
<a href="http://stackoverflow.com/search?q=sql+injection">http://stackoverflow.com/search?q=sql+injection</a></p>
</blockquote>
<p>Can someone explain SQL injection? How does it cause vulnerabilities? Where exactly is the point where SQL is injected?</p>
| <p><strong>Can someone explain SQL injecton?</strong> </p>
<p>SQL injection happens when you interpolate some content into a SQL query string, and the result modifies the syntax of your query in ways you didn't intend.</p>
<p>It doesn't have to be malicious, it can be an accident. But accidental SQL injection is more likely to result in an error than in a vulnerability.</p>
<p>The harmful content doesn't have to come from a user, it could be content that your application gets from any source, or even generates itself in code.</p>
<p><strong>How does it cause vulnerabilities?</strong> </p>
<p>It can lead to vulnerabilities because attackers can send values to an application that they know will be interpolated into a SQL string. By being very clever, they can manipulate the result of queries, reading data or even changing data that they shouldn't be allowed to do.</p>
<p>Example in PHP:</p>
<pre><code>$password = $_POST['password'];
$id = $_POST['id'];
$sql = "UPDATE Accounts SET PASSWORD = '$password' WHERE account_id = $id";
</code></pre>
<p>Now suppose the attacker sets the POST request parameters to "<code>password=xyzzy</code>" and "<code>id=account_id</code>" resulting in the following SQL:</p>
<pre><code>UPDATE Accounts SET PASSWORD = 'xyzzy' WHERE account_id = account_id
</code></pre>
<p>Although I expected <code>$id</code> to be an integer, the attacker chose a string that is the name of the column. Of course now the condition is true on <em>every</em> row, so the attacker has just set the password for <em>every</em> account. Now the attacker can log in to anyone's account -- including privileged users.</p>
<p><strong>Where exactly is the point where SQL is injected?</strong></p>
<p>It isn't SQL that's injected, it's content that's interpolated ("injected") into a SQL string, resulting in a different kind of query than I intended. I trusted the dynamic content without verifying it, and executed the resulting SQL query blindly. That's where the trouble starts.</p>
<p>SQL injection is a fault in the application code, not typically in the database or in the database access library or framework. The remedy for SQL injection follows the <a href="http://shiflett.org/blog/2005/feb/my-top-two-php-security-practices">FIEO</a> practices:</p>
<ul>
<li><strong>Filter Input:</strong> verify that the content is in a format you expect, instead of assuming. For example, apply a regular expression, or use a data type coercion like the <code>intval()</code> function.</li>
<li><strong>Escape Output:</strong> in this case "output" is where the content is combined with the SQL string. When interpolating strings, avoid imbalanced quotes by using a function that escapes literal quote characters and any other characters that may be string boundaries.</li>
</ul>
|
WinForms data binding - Bind to objects in a list <p>I need some help/guidance on WinForms data binding and I can't seem to get Google to help me with this one.</p>
<p>Here is my scenario. Consider the following classes which is similar to what I need:</p>
<pre><code>public class Car
{
public string Name { get; set; }
public List<Tire> Tires { get; set; }
}
public class Tire
{
public double Pressure { get; set; }
}
</code></pre>
<p>My instances of this will be an object of class Car with a List with four Tire objects. Note that I will always have a known number of objects in the list here.</p>
<p>Now I want to data bind this to a Form containing five textboxes. One textbox with the name of the car and one textbox with each of the tires pressures.</p>
<p>Any idea on how to make this work? The designer in VS does not seem to allow me to set this up by assigning to list indexes like Tires[0].Pressure.</p>
<p>My current solution is to bind to a "BindableCar" which would be like:</p>
<pre><code>public class BindableCar
{
private Car _car;
public BindableCar(Car car)
{
_car = car;
}
public string Name
{
get { return _car.Name; }
set { _car.Name = value; }
}
public double Tire1Pressure
{
get { return _car.Tires[0].Pressure; }
set { _car.Tires[0].Pressure = value; }
}
public double Tire2Pressure
{
get { return _car.Tires[1].Pressure; }
set { _car.Tires[1].Pressure = value; }
}
public double Tire3Pressure
{
get { return _car.Tires[2].Pressure; }
set { _car.Tires[2].Pressure = value; }
}
public double Tire4Pressure
{
get { return _car.Tires[3].Pressure; }
set { _car.Tires[3].Pressure = value; }
}
}
</code></pre>
<p>but this becomes really ugly when my lists contains 20 instead of 4 objects, and for each of those objects I want to bind against 6 properties. That makes a huge "BindableObject"!</p>
| <p>You should note that you can bind controls to <em>any</em> object type that implements the interfaces <code>IList</code>, <code>ICollection</code> or <code>IEnumerable</code> or inherits from classes that implement these interfaces. Generic collections also qualify for this kind of binding.</p>
<p>These are internally converted to an <code>IBindingList</code> instance.</p>
<p>Check out the following links for more information:</p>
<ol>
<li><a href="http://support.microsoft.com/kb/313482">Roadmap for Windowsforms databinding</a> - Takes a very comprehensive look at the implementation and possibilities and provides a variety of links to other KB articles.</li>
<li><a href="http://www.15seconds.com/issue/040614.htm">Winforms Object binding</a> - Rockford Lhotka's article on the subject. Provides a Windows forms designer-oriented way of implementing databinding.</li>
<li><a href="http://www.informit.com/store/product.aspx?isbn=032126892X">Databinding with Windows forms 2.0</a> - This book by Brian Noyes explores various aspects of Databinding, both in complex and simple scenarios. </li>
</ol>
|
Which data type in c# is better suited for currency calculations? <p>And also the better counter part in sql server for mapping.</p>
| <p>Decimal and Decimal :)</p>
<ul>
<li>.Net: <a href="http://msdn.microsoft.com/en-us/library/system.decimal.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.decimal.aspx</a></li>
<li>SQL; <a href="http://msdn.microsoft.com/en-us/library/ms187746.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms187746.aspx</a></li>
</ul>
|
How do i get all Sunday dates in a particular year? <p><strong>Exact duplicate:</strong> <a href="http://stackoverflow.com/questions/590385/how-to-get-all-dates-of-sundays-in-a-particular-year-in-java">http://stackoverflow.com/questions/590385/how-to-get-all-dates-of-sundays-in-a-particular-year-in-java</a></p>
<p><hr /></p>
<pre><code>int year = 2009;
Calendar cal = new GregorianCalendar(year, Calendar.JANUARY, 1);
for (int i = 0, inc = 1; i < 366 && cal.get(Calendar.YEAR) == year; i+=inc) {
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
// this is a sunday
cal.add(Calendar.DAY_OF_MONTH, 7);
inc = 7;
} else {
cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
</code></pre>
<p>In <a href="http://stackoverflow.com/questions/590385/how-to-get-all-dates-of-sundays-in-a-particular-year-in-java/590447#590447">Miles D given code</a>, I am getting dates of all sundays from second sunday of frst month to frst sunday of next year. Actually I am looking for a particular year only, and its all sunday dates, plz miles can u see it once again.....</p>
<p>For instance, I need all sunday dates in 2009 from January 2009 to December 2009 only</p>
| <p>New to programming? Well, let's have a look at the code together!</p>
<p>The first thing that I see is the conditional inside the loop:</p>
<pre><code>if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
</code></pre>
<p>This checks if the current date stored in the Calendar <code>cal</code> has a <code>DAY_OF_WEEK</code> which is <code>SUNDAY</code>. If it is, it does one thing, and if it isn't, it does another.</p>
<p>Now that we know what the loop's "brain" is looking for, let's look at the loop's declaration:</p>
<pre><code>for (int i = 0, inc = 1; i < 366 && cal.get(Calendar.YEAR) == year; i+=inc)
</code></pre>
<p>The <code>for</code> loop is split into three parts: initialization, condition, and "increment".
The initialization, is run only once, before th loop starts running:</p>
<pre><code>int i = 0, inc = 1
</code></pre>
<p>Which, as I'm <em>sure</em> you know, creates two variables: <code>i</code> and <code>inc</code>. It sets <code>i</code> to 0, and <code>inc</code> to 1.</p>
<p>The condition of the loop gets checked before running each iteration of the loop. It is:</p>
<pre><code>i < 366 && cal.get(Calendar.YEAR) == year
</code></pre>
<p>Which checks whether <code>i</code> is still less than 366 and also that the date stored in <code>cal</code> has the <code>YEAR</code> of <code>year</code>. This, in effect, makes sure we are still in the same year we started with.</p>
<p>The last section of the for, is this:</p>
<pre><code>i+=inc
</code></pre>
<p>Which adds the value of <code>inc</code> to the value of <code>i</code> and stores it in <code>i</code>.</p>
<p>So what do we have so far in the loop?</p>
<ol>
<li>The loop starts with an <code>i</code> of 0 and an <code>inc</code> of 1</li>
<li>The loop keeps going as long as
<ul>
<li><code>i</code> is smaller than the length of a Gregorian year (366 on leap-years),</li>
<li>(AND) the date in <code>cal</code> still has the same year as the year in <code>year</code>.</li>
</ul></li>
<li><code>i</code> is advanced by <code>inc</code></li>
</ol>
<p>Let's have another look at the body of the loop:</p>
<pre><code>if (condition_that_checks_if_it_is_a_sunday) {
// this is a sunday
cal.add(Calendar.DAY_OF_MONTH, 7);
inc = 7;
} else {
cal.add(Calendar.DAY_OF_MONTH, 1);
}
</code></pre>
<p>As you can see, if it's a Sunday, two things happen: <code>inc</code> is set to 7, and 7 <code>DAY_OF_MONTH</code> are <code>add</code>ed to <code>cal</code>. This would mean that in the next iteration of the loop, the expression <code>i+=inc</code> will mean <code>i+=7</code> and not <code>i+=1</code> which is did when <code>inc</code> was 1 (like it was when the initialization was done.)</p>
<p>If it's not a Sunday, a single <code>DAY_OF_WEEK</code> is added to <code>cal</code>.</p>
<p>So what do we have in the body of the loop?</p>
<ul>
<li>Check if <code>cal</code> is a Sunday
<ul>
<li>If it is, advance <code>cal</code> by 7 days. And not only that, but keep advancing <code>i</code> by 7!</li>
<li>If <code>cal</code> isn't on a sunday, advance it to the next day of the week, and let <code>i</code> keep advancing by 1.</li>
</ul></li>
</ul>
<p>In other words, the loop will start at <code>cal</code>'s initial value, and move <code>cal</code> forward one day at a time until it finds a Sunday. Once it does that, it will move <code>cal</code> forward 7 days at a time, until it has gone over 366 days, or until <code>cal</code> is in another year!</p>
<p>Thus, from (<em>ahem</em>) briefly examining the code above, we an conclude it doesn't actually "get" the Sundays in a year. It simply iterates over them, and it's up to you to add the code that actually does something with the Sundays it finds.</p>
<p>And now that we've gone over the code together, I'm certain it's trivial to do that! It really is a matter of just adding a couple of lines. You just have to add a line that does [insert here whatever you want] every time the loop enters the part where it "knows" <code>cal</code> is a Sunday.</p>
<p>Simple, no?</p>
|
Multibyte character constants and bitmap file header type constants <p>I have some existing code that I've used to write out an image to a bitmap file. One of the lines of code looks like this:</p>
<pre><code>bfh.bfType='MB';
</code></pre>
<p>I think I probably copied that from somewhere. One of the other devs says to me "that doesn't look right, isn't it supposed to be 'BM'?" Anyway it does seem to work ok, but on code review it gets refactored to this:</p>
<pre><code>bfh.bfType=*(WORD*)"BM";
</code></pre>
<p>A google search indicates that most of the time, the first line seems to be used, while some of the time people will do this:</p>
<pre><code>bfh.bfType=0x4D42;
</code></pre>
<p>So what is the difference? How can they all give the correct result? What does the multi-byte character constant mean anyway? Are they the same really?</p>
| <p>All three are (probably) equivalent, but for different reasons. </p>
<pre><code>bfh.bfType=0x4D42;
</code></pre>
<p>This is the simplest to understand, it just loads bfType with a number that happens to represent ASCII 'M' in bits 8-15 and ASCII 'B' in bits 0-7. If you write this to a stream in little-endian format, then the stream will contain 'B', 'M'.</p>
<pre><code>bfh.bfType='MB';
</code></pre>
<p>This is essentially equivalent to the first statement -- it's just a different way of expressing an integer constant. It probably depends on the compiler exactly what it does with it, but it will probably generate a value according to the endian-ness of the machine you compile on. If you compile and execute on a machine of the same endian-ness, then when you write the value out on the stream you should get 'B', 'M'.</p>
<pre><code>bfh.bfType=*(WORD*)"BM";
</code></pre>
<p>Here, the "BM" causes the compiler to create a block of data that looks like 'B', 'M', '\0' and get a char* pointing to it. This is then cast to WORD* so that when it's dereferenced it will read the memory as a WORD. Hence it reads the 'B', 'M' into bfType in whatever endian-ness the machine has. Writing it out using the same endian-ness will obviously put 'B', 'M' on your stream. So long as you only use bfType to write out to the stream this is the most portable version. However, if you're doing any comparisons/etc with bfType then it's probably best to pick an endian-ness for it and convert as necessary when reading or writing the value.</p>
|
What is the limitation of PerlNet? <p>I've used PerlNet for a data extraction project. Perl is a powerful language for extracting data and text manipulation with a huge CPAN module. However, my program need some kind of UI, thread... which I decided to use .NET C#. With Perl Dev Kit, we have an option to wrap an Perl module to a .NET DLL and use this DLL directly from C#.</p>
<p>Everything was ok but I have one question about PerlNet architecture. As far as I know, PerlNet was a research project between ActiveState and Microsoft for running Perl code in .NET but I did not find any document for this. </p>
<p>What is limitation of PerlNet? How was PerlNet constructed? </p>
<p>Thanks,
Minh.</p>
| <p>There's a book "<a href="http://rads.stackoverflow.com/amzn/click/0130652067">Programming Perl in the .NET Environment</a>" that may help you.</p>
<p>ActiveState doesn't seem to have any publicly accessible documentation online that gives any kind of details about PerlNET. But I'd be very surprised if there wasn't some doc included with the Perl Dev Kit, even though it sounds like they aren't providing any support for it anymore.</p>
<p>You may find answers to your questions on the perl.net@listserv.activestate.com mailing list or in its <a href="http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/perl.net">archives</a>. </p>
|
What's the most irrational user behaviour you have witnessed? <p>While novice software designers expect their users to behave rationally, it's far from being the case ; I've seen many times the user perception being totally disconnected from reality, or it's feedback obviously irrational.</p>
<p>I think <em>we are the one who should adapt</em>, not the other way around.</p>
<p>There's only one way that I know of to achieve this : listen to users, especially about what they don't like in software they use.</p>
<p>If there's one thing I've learned so far ; they often complain about things one wouldn't expect</p>
<p>What unexpected things did you learn from your users?</p>
| <p>A few years ago, hospitals (at least French hospitals) were run using old win 3.11 softwareâs. Every single task was tedious; moving someone from one room to another would take 5 minutes to an expert user</p>
<p>A friend of mine was working on selling up-to-date software to those people. The same simple task would take 30s to a total beginner.</p>
<p>While most of the users were very happy with the new software, a handful were complaining, which wasnât a surprise (thereâs always a handful of users complaining). What was more unexpected was their reason: the software was damn slow. âThe same simple task was instantaneous, now it takes ages to achieve. Give me my old software backâ, they would say.</p>
<p>My friend decided to meet them, and asked them for a live demo of the slowness they were complaining about.</p>
<p>âLook, said the user, with my old software : I input the first name, enter, the name, enter, the admission number, enter, the old room number,[â¦insert 5 minutes hereâ¦] the new room number enter ⦠and itâs doneâ¦.. See⦠Everything is instantaneousâ</p>
<p>âNow, look at your software. I do a drag and drop, as you taught me. And I wait, I wait⦠look, itâs done..Iâve waited for almost 30sâ¦.â</p>
<p>Thatâs a real world example. It really happened. <strong>Iâm pretty sure that if the software had been modified to ask for useless information that it would have discarded afterwards during the 30s period, this user would have had a far better feeling with the new software</strong></p>
|
How to get the number of rows of the selected result from sqlite3? <p>I want to get the number of selected rows as well as the selected data. At the present I have to use two sql statements: </p>
<p>one is </p>
<pre><code>select * from XXX where XXX;
</code></pre>
<p>the other is </p>
<pre><code>select count(*) from XXX where XXX;
</code></pre>
<p>Can it be realised with a single sql string?</p>
<p>I've checked the source code of sqlite3, and I found the function of <code>sqlite3_changes()</code>. But the function is only useful when the database is changed (after <code>insert, delete or update</code>). </p>
<p>Can anyone help me with this problem? Thank you very much!</p>
| <p>try this way</p>
<pre><code>select (select count() from XXX) as count, *
from XXX;
</code></pre>
|
What's the best way to fork/thread in PHP on Win? <p>I have a php script that checks for updates on many (thousands) of sites.
On occasion (more frequently as the number of sites increases), I get an execution timeout on the update of one of these sites, and the whole script goes down the drain.</p>
<p>The best idea I could come up with is to fork each update, so if it dies, the overall update just continues.
From what I gathered, it seems PHP threading isn't something to rely on, especially on a windows platform (which I unfortunately have to work on).</p>
<p>I thought about using curl as a forking mechanism, but won't it be much more costly for the server (in time and processing power)?</p>
<p>I'd be happy to hear some ideas and experience about PHP forking/threading...</p>
<p>thanks,
Omer.</p>
| <p>If you're going to use cURL look into the multi* family of methods which allows you to streamline cURL and interacting with a set of sites. That being said, you could also set your max execution time (via ini_set) to some arbitrarily high number and/or keep your own watchdog counter so that you never let it get too high. </p>
<p>But yeah, ultimately are going to run into issues and the lack of full thread support in PHP. So your best bet is to look at other alternatives, e.g. other languages/platforms that provide native threading support.</p>
|
"Bus error" accessing a set<int> from a struct <p>Searched for a while, but I can't figure out why this would raise a bus error.</p>
<p>Any help would be much appreciated.</p>
<pre><code>typedef struct {
set<int> pages;
} someStruct;
...
void someFunction() {
...
someStruct *a = createSomeStruct(); // just mallocs and returns
a->pages.insert(5);
...
}
</code></pre>
| <p>malloc doesn't initialize the memory it allocates. try with new.</p>
|
Oolong, SIO2 or commercial Game engine for 3D iPhone Games newbie? <p>I'm trying to pick between the <a href="http://code.google.com/p/oolongengine/">Oolong</a> and <a href="http://sio2interactive.com/store.php">SIO2</a> iPhone game engines for my first game programming project. I have some Cocoa experience and many years of C++ including relatively low level 2D graphics and developing <a href="http://www.google.com/search?hl=en&client=safari&rls=en-us&q=opticboom+3d+quicktime&btnG=Search">Quicktime plugins</a> but only minor OpenGL exposure. <strong>Which engine would be easiest to learn and most productive for someone with my background and limited time?</strong></p>
<p>Both include the Bullet physics engine. I lean towards Oolong because of its C++ source and optimisation for the PowerVR graphics. However, the Lua interpreter and additional sound goodies in SIO2 are appealing. SIO2 also seems to have a good range of <a href="http://sio2interactive.com/TECHNOLOGY.html">tutorials</a>. </p>
<p>I'm also willing to spend money on <a href="http://unity3d.com/unity/features/iphone-publishing">Unity</a> or <a href="http://www.garagegames.com/products/consoles">Torque Game Environment</a> if they will save me significant time. The pricing gets interesting though - the Unity Indie license only applies to companies with turnover (not revenue!) of under USD 100,000 so you're easily out of that category and up for USD 3,000 per seat. I'd want a lot of convincing it will save time to justify that investment over just using SIO2! The Torque 3D product doesn't seem to be released yet but looks like costing about USD 500 on top of a USD 150 Indie license (their income threshold is USD 250,000).</p>
<p>*<em>Edit Dec 2011 - SIO2 is no longer free *</em></p>
| <p>I started my first SIO2 app last night and it was easy to get up & running from the tutorials (the tutorials include a full XCode project that you can load and start hacking on). The tutorial projects are also very well commented - this makes it quicker to pick up.</p>
<p>The interfaces to SIO2 are mostly in C, so your C++ background should make that transition pretty easy.</p>
<p>Even if you don't use it, download SIO2 and open one of the tutorials and check out the comments & code. You'll be able to tell pretty quickly if it's a toolkit & style you like.</p>
<p>Not directly related to speed of uptake, but a big plus for me was the Blender integration. It lets me use a free 3d toolkit to make & export models and then go from there. I saw that Oolong uses 3DS and I'm not sure if Blender exports that format or not so I could be wrong.</p>
<p>If you're curious: SIO2 provides a python script that exports the Blender scene to a zip file. Then, from inside the SIO2 code you reference your objects from the scene and pull them in to your iPhone app.</p>
|
Minimize browser window using javascript <p>Is there a javascript or jQuery method to minimize the current browser window?</p>
| <p>There is no way to minimize the browser window within javascript.</p>
<p>There are ways to change the size of the window, but no true minimization (nice word)</p>
|
For loop with non-contiguous range <p>I have a loop that runs through each column and sets the value to an R1C1 sum of a few rows above it. I'm using a for loop, but I want to skip a few columns, as they contain formulae already in the cell. How can I set up a loop that only cycles through a non-contiguous set or numbers? </p>
<p>For reference, I want it to cycle through columns 1 to 80, but skip cols 25, 36, 37, 44, 60, 63, 64, 67, 68, 73, 75 and 76.</p>
<p>Edit: thanks guys, but I;ve already got it working as you described; I was looking for a shorter and more elegant method.</p>
<p>Edit 2: Is that even VBA?!</p>
| <p>A VBA version of Learning's C# answer:-</p>
<pre><code>Dim col As Integer: For col = 1 To 70
Select Case col
Case 25, 36, 37, 44, 60, 63, 64, 67, 68, 73, 75, 76
'do nothing'
Case Else
'do something'
End Select
Next col
</code></pre>
|
When to buy Visual Studio Team System? <p>We use Visual Studio Professional and we are quite pleased with it. We use Tortoise SVN, Visual VSN, NUnit and resharper. A combination that works very well for us. </p>
<p>Now we need to run load tests.</p>
<p>We looked at Visual Studio Team System, but frankly the pricing seems a bit lofty (obvious understatement). We are with a team of 6 developers.</p>
<p>I do want to 'get the best tools money can buy', still... Any advice? Are there alternatives?</p>
<p>EDIT: We develop a web application written in C#. We have been in business for more than three years thus we unfortunately cannot enroll in bizspark.</p>
| <p>I don't really see how VSTS will help you with load testing.</p>
<p>Also, a 6 developer team is too small to benefit from VSTS.</p>
|
Data Binding POCO Properties <p>Are there any data binding frameworks (BCL or otherwise) that allow binding between <em>any two CLR properties</em> that implement <code>INotifyPropertyChanged</code> and <code>INotifyCollectionChanged</code>? It seems to be it should be possible to do something like this:</p>
<pre><code>var binding = new Binding();
binding.Source = someSourceObject;
binding.SourcePath = "Customer.Name";
binding.Target = someTargetObject;
binding.TargetPath = "Client.Name";
BindingManager.Bind(binding);
</code></pre>
<p>Where <code>someSourceObject</code> and <code>someTargetObject</code> are just POCOs that implement <code>INotifyPropertyChanged</code>. However, I am unaware of any BCL support for this, and am not sure if there are existing frameworks that permit this.</p>
<p><strong>UPDATE</strong>: Given that there is no existing library available, I have taken it upon myself to write my own. It is available <a href="http://truss.codeplex.com/">here</a>.</p>
<p>Thanks</p>
| <p>I wrote <a href="http://truss.codeplex.com/" rel="nofollow">Truss</a> to fill the void.</p>
|
How to write meaningful docstrings? <p>What, in Your opinion is a meaningful docstring? What do You expect to be described there?</p>
<p>For example, consider this Python class's <code>__init__</code>:</p>
<pre><code>def __init__(self, name, value, displayName=None, matchingRule="strict"):
"""
name - field name
value - field value
displayName - nice display name, if empty will be set to field name
matchingRule - I have no idea what this does, set to strict by default
"""
</code></pre>
<p>Do you find this meaningful? Post Your good/bad examples for all to know (and a general answer so it can be accepted).</p>
| <p>I agree with "Anything that you can't tell from the method's signature". It might also mean to explain what a method/function returns.</p>
<p>You might also want to use <a href="http://sphinx.pocoo.org/">Sphinx</a> (and reStructuredText syntax) for documentation purposes inside your docstrings. That way you can include this in your documentation easily. For an example check out e.g. <a href="http://svn.repoze.org/repoze.bfg/trunk">repoze.bfg</a> which uses this extensively (<a href="http://svn.repoze.org/repoze.bfg/trunk/repoze/bfg/location.py">example file</a>, <a href="http://svn.repoze.org/repoze.bfg/trunk/docs/">documentation example</a>).</p>
<p>Another thing one can put in docstrings is also <a href="http://docs.python.org/library/doctest.html">doctests</a>. This might make sense esp. for module or class docstrings as you can also show that way how to use it and have this testable at the same time.</p>
|
Ajax Modal Popup Display Issue <p>On the web page, there is gridview control contains product ID's. bind to a link button.</p>
<p>On ItemCommand event of gridview, I fetch the product information and display in the ajax modal popup extender control. The popup is programatically show on ItemCommand of gridview and also hide programatically.</p>
<p>Now the problem is that, when i close popup after showing first product details and try to see next 1 by clicking on other product ID.., sometimes details are displaye dand sometimes not.</p>
<p>The data comes from database is fetched as well for each product.</p>
<p>Plz help.</p>
| <p>I do the same but i have no such problem. So i am pasting code here that may b help full to u.<br>
<strong>CODE:</strong></p>
<pre><code>protected void GVallusers_RowEditing(object sender, GridViewEditEventArgs e)
{
try
{
GridViewRow gvRow = ((GridView)sender).Rows[e.NewEditIndex];
populatepanel(gvRow);
ModalPopupExtender1.Show();
}
catch (Exception exc)
{
lblinfo.Text = exc.Message;
}
}
public void populatepanel(GridViewRow gvrow)
{
string userid = gvrow.Cells[0].Text;
lblSite.Text=gvrow.Cells[1].Text;
lblemail.Text = gvrow.Cells[3].Text;
}
</code></pre>
|
How do I utilise all the cores for nmake? <p>I just got a new quad core computer and noticed that nmake is only using 1 process.</p>
<p>I used to use make which had the switch -j4 for launching 4 processes. What is the nmake equivalent?</p>
<p>[edit]
Based on the information below I have been able to add a command to my qmake project file:</p>
<p>QMAKE_CXXFLAGS += /MP</p>
<p>Which effectively did it for me. Many thanks.</p>
| <p>QT have tool supposed for this
<a href="http://qt.gitorious.org/qt-labs/jom">http://qt.gitorious.org/qt-labs/jom</a></p>
|
How to create a string or char from an ASCII value in JavaScript? <p>In JavaScript, how to get a string representation of an ASCII value, e.g. how to turn <code>65</code> into <code>A</code>?</p>
| <p>The <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode">fromCharCode</a> method converts ASCII to a string: </p>
<pre><code><script type="text/javascript">
document.write(String.fromCharCode(65,66,67)); // ABC
</script>
</code></pre>
<p>Hope this helps!</p>
|
Store last created model's row in memory <p>I am working on ajax-game. The abstract: 2+ gamers(browsers) change a variable which is saved to DB through json. All gamers are synchronized by javascript-timer+json - periodically reading that variable from DB. </p>
<p>In general, all changes are stored in DB as history, but I want the recent change duplicated in memory. </p>
<p>So the problem is: i want one variable to be stored in memory instead of DB.</p>
| <p>You can use the cache system:</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/cache/#topics-cache" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/cache/#topics-cache</a></p>
|
Eclipse on the Mac... using Windows keyboard shortcuts? <p>I'm a power Eclipse user on Linux/Windows, and the keyboard shortcuts are practically muscle memory. Just recently started developing on a Mac (love it!), using Eclipse, but was really tripped up by the use of the <code>command</code> key... and not all the shortcuts map over consistently.</p>
<p>I've already re-mapped all my common shortcuts to use <code>Ctrl</code>, but was wondering if anyone's found a more efficient and complete way to do this? Has some kind soul gone through all the shortcuts and posted a preferences file ready for import?</p>
| <p>Instead of using the command key, </p>
<p><img src="http://www.pajbam.com/wp-content/uploads/2008/01/organize%5Fimports-menu%5Fitem.png" alt="alt text" /></p>
<p>, may be this <a href="http://www.martinkahr.com/2006/02/13/mac-keys-for-eclipse/">article <strong>Mac Keys for Eclipse</strong></a> might contains a <a href="http://www.martinkahr.com/wp-content/uploads/2006/02/eclipse-mac-keys.epf.zip">preference file</a> (to be imported) with interesting shortcuts.</p>
<p>(Save your current preferences first ;) )</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.