input
stringlengths
51
42.3k
output
stringlengths
18
55k
How to select only the records with the highest date in LINQ <p>I have a table, 'lasttraces', with the following fields.</p> <pre><code>Id, AccountId, Version, DownloadNo, Date </code></pre> <p>The data looks like this:</p> <pre><code>28092|15240000|1.0.7.1782|2009040004731|2009-01-20 13:10:22.000 28094|61615000|1.0.7.1782|2009040007696|2009-01-20 13:11:38.000 28095|95317000|1.0.7.1782|2009040007695|2009-01-20 13:10:18.000 28101|15240000|1.0.7.1782|2009040004740|2009-01-20 14:10:22.000 28103|61615000|1.0.7.1782|2009040007690|2009-01-20 14:11:38.000 28104|95317000|1.0.7.1782|2009040007710|2009-01-20 14:10:18.000 </code></pre> <p>How can I, in <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_SQL">LINQ&nbsp;to&nbsp;SQL</a>, only get the last lasttrace of every AccountId (the one with the highest date)?</p>
<p>If you just want the last date for each account, you'd use this:</p> <pre><code>var q = from n in table group n by n.AccountId into g select new {AccountId = g.Key, Date = g.Max(t=&gt;t.Date)}; </code></pre> <p>If you want the whole record:</p> <pre><code>var q = from n in table group n by n.AccountId into g select g.OrderByDescending(t=&gt;t.Date).FirstOrDefault(); </code></pre>
What are good cross-platform Game API? <p>I am in the process of designing/building a cross-platform game engine in C++. I would like to use an game API that has 2D/3D graphics, input, networking, audio, etc. One API I found that meets many of these requirements except for Audio is <a href="http://home.gna.org/amaltheia/">Amaltheia</a>. Can anyone suggest an API that meets all my requirements or one that meets most of the requirements that is better than <a href="http://home.gna.org/amaltheia/">Amaltheia</a>. </p>
<p>You could look at <a href="http://www.libsdl.org/" rel="nofollow">SDL</a>, it's a popular cross-platform multimedia library used in many games.</p> <p>Also the <a href="http://web.archive.org/web/20090301052144/http://gpwiki.org/" rel="nofollow">Game Programming Wiki</a> is a good source for lists of game programming <a href="http://web.archive.org/web/20090301053452/http://gpwiki.org/index.php/Libraries" rel="nofollow">libraries</a> and <a href="http://web.archive.org/web/20090301042508/http://gpwiki.org/index.php/Game_Engines" rel="nofollow">engines</a></p>
XmlSerializer and InternalsVisibleTo attribute <p>Is it possible to make <code>XmlSerializer</code> serialize internal class members by using <code>InternalsVisibleTo</code> attribute? </p> <p>If it is, what assembly should I make my internals visible to. In other words, what assembly name and public key should I provide to the <code>InternalsVisibleTo</code> attribute.</p>
<p>This is a common question, please see this post:</p> <p><a href="http://stackoverflow.com/questions/420662/can-an-internal-setter-of-a-property-be-serialized">http://stackoverflow.com/questions/420662/can-an-internal-setter-of-a-property-be-serialized</a></p> <p>The <code>DataContractSerializer</code> will let you serialize any members you want. As it is an opt-in method of serialization you will need to annotate the class as needed.</p> <h3>Edit</h3> <p>After re-reading your question, <code>DataContractSerializer</code> may work but that may not be what you want to do. The XMLSerializer will work with <code>InternalsVisibleTo</code> as it will be able to see those members but I would recommend that you look at <code>DataContractSerializer</code> as it is (in my opinion) a better serializer.</p>
How to automatically generate N "distinct" colors? <p>I wrote the two methods below to automatically select N distinct colors. It works by defining a piecewise linear function on the RGB cube. The benefit of this is you can also get a progressive scale if that's what you want, but when N gets large the colors can start to look similar. I can also imagine evenly subdividing the RGB cube into a lattice and then drawing points. Does anyone know any other methods? I'm ruling out defining a list and then just cycling through it. I should also say I don't generally care if they clash or don't look nice, they just have to be visually distinct.</p> <pre><code>public static List&lt;Color&gt; pick(int num) { List&lt;Color&gt; colors = new ArrayList&lt;Color&gt;(); if (num &lt; 2) return colors; float dx = 1.0f / (float) (num - 1); for (int i = 0; i &lt; num; i++) { colors.add(get(i * dx)); } return colors; } public static Color get(float x) { float r = 0.0f; float g = 0.0f; float b = 1.0f; if (x &gt;= 0.0f &amp;&amp; x &lt; 0.2f) { x = x / 0.2f; r = 0.0f; g = x; b = 1.0f; } else if (x &gt;= 0.2f &amp;&amp; x &lt; 0.4f) { x = (x - 0.2f) / 0.2f; r = 0.0f; g = 1.0f; b = 1.0f - x; } else if (x &gt;= 0.4f &amp;&amp; x &lt; 0.6f) { x = (x - 0.4f) / 0.2f; r = x; g = 1.0f; b = 0.0f; } else if (x &gt;= 0.6f &amp;&amp; x &lt; 0.8f) { x = (x - 0.6f) / 0.2f; r = 1.0f; g = 1.0f - x; b = 0.0f; } else if (x &gt;= 0.8f &amp;&amp; x &lt;= 1.0f) { x = (x - 0.8f) / 0.2f; r = 1.0f; g = 0.0f; b = x; } return new Color(r, g, b); } </code></pre>
<p>This questions appears in quite a few SO discussions:</p> <ul> <li><a href="http://stackoverflow.com/questions/1168260/algorithm-for-generating-unique-colors">Algorithm For Generating Unique Colors</a></li> <li><a href="http://stackoverflow.com/questions/773226/generate-unique-colours">Generate unique colours</a></li> <li><a href="http://stackoverflow.com/questions/309149/generate-distinctly-different-rgb-colors-in-graphs">Generate distinctly different RGB colors in graphs</a></li> <li><a href="http://stackoverflow.com/questions/2328339/how-to-generate-n-different-colors-for-any-natural-number-n">How to generate n different colors for any natural number n?</a></li> </ul> <p>Different solutions are proposed, but none are optimal. Luckily, <em>science</em> comes to the rescue</p> <p><strong>Arbitrary N</strong></p> <ul> <li><a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.65.2790">Colour displays for categorical images</a> (free download)</li> <li><a href="http://icaci.org/documents/ICC_proceedings/ICC2009/html/nonref/13_18.pdf">A WEB SERVICE TO PERSONALISE MAP COLOURING</a> (free download, a webservice solution should be available by next month)</li> <li><a href="http://onlinelibrary.wiley.com/doi/10.1002/%28SICI%291520-6378%28199904%2924:2%3C132::AID-COL8%3E3.0.CO;2-B/abstract">An Algorithm for the Selection of High-Contrast Color Sets</a> (the authors offer a free C++ implementation)</li> <li><a href="http://www.opticsinfobase.org/abstract.cfm?URI=ao-21-16-2936">High-contrast sets of colors</a> (The first algorithm for the problem)</li> </ul> <p>The last 2 will be free via most university libraries / proxies. </p> <p><strong>N is finite and relatively small</strong></p> <p>In this case, one could go for a list solution. A very interesting article in the subject is freely available:</p> <ul> <li><a href="http://eleanormaclure.files.wordpress.com/2011/03/colour-coding.pdf">A Colour Alphabet and the Limits of Colour Coding</a></li> </ul> <p>There are several color lists to consider:</p> <ul> <li>Boynton's list of 11 colors that are almost never confused (available in the first paper of the previous section)</li> <li>Kelly's 22 colors of maximum contrast (available in the paper above)</li> </ul> <p>I also ran into <a href="http://web.media.mit.edu/~wad/color/palette.html">this</a> Palette by an MIT student. Lastly, The following links may be useful in converting between different color systems / coordinates (some colors in the articles are not specified in RGB, for instance):</p> <ul> <li><a href="http://chem8.org/uch/space-55036-do-blog-id-5333.html">http://chem8.org/uch/space-55036-do-blog-id-5333.html</a></li> <li><a href="https://metacpan.org/pod/Color::Library::Dictionary::NBS_ISCC">https://metacpan.org/pod/Color::Library::Dictionary::NBS_ISCC</a></li> <li><a href="http://stackoverflow.com/questions/3620663/color-theory-how-to-convert-munsell-hvc-to-rgb-hsb-hsl/4353544#4353544">Color Theory: How to convert Munsell HVC to RGB/HSB/HSL</a></li> </ul> <p>For Kelly's and Boynton's list, I've already made the conversion to RGB (with the exception of white and black, which should be obvious). Some C# code:</p> <pre class="lang-cs prettyprint-override"><code>public static ReadOnlyCollection&lt;Color&gt; KellysMaxContrastSet { get { return _kellysMaxContrastSet.AsReadOnly(); } } private static readonly List&lt;Color&gt; _kellysMaxContrastSet = new List&lt;Color&gt; { UIntToColor(0xFFFFB300), //Vivid Yellow UIntToColor(0xFF803E75), //Strong Purple UIntToColor(0xFFFF6800), //Vivid Orange UIntToColor(0xFFA6BDD7), //Very Light Blue UIntToColor(0xFFC10020), //Vivid Red UIntToColor(0xFFCEA262), //Grayish Yellow UIntToColor(0xFF817066), //Medium Gray //The following will not be good for people with defective color vision UIntToColor(0xFF007D34), //Vivid Green UIntToColor(0xFFF6768E), //Strong Purplish Pink UIntToColor(0xFF00538A), //Strong Blue UIntToColor(0xFFFF7A5C), //Strong Yellowish Pink UIntToColor(0xFF53377A), //Strong Violet UIntToColor(0xFFFF8E00), //Vivid Orange Yellow UIntToColor(0xFFB32851), //Strong Purplish Red UIntToColor(0xFFF4C800), //Vivid Greenish Yellow UIntToColor(0xFF7F180D), //Strong Reddish Brown UIntToColor(0xFF93AA00), //Vivid Yellowish Green UIntToColor(0xFF593315), //Deep Yellowish Brown UIntToColor(0xFFF13A13), //Vivid Reddish Orange UIntToColor(0xFF232C16), //Dark Olive Green }; public static ReadOnlyCollection&lt;Color&gt; BoyntonOptimized { get { return _boyntonOptimized.AsReadOnly(); } } private static readonly List&lt;Color&gt; _boyntonOptimized = new List&lt;Color&gt; { Color.FromArgb(0, 0, 255), //Blue Color.FromArgb(255, 0, 0), //Red Color.FromArgb(0, 255, 0), //Green Color.FromArgb(255, 255, 0), //Yellow Color.FromArgb(255, 0, 255), //Magenta Color.FromArgb(255, 128, 128), //Pink Color.FromArgb(128, 128, 128), //Gray Color.FromArgb(128, 0, 0), //Brown Color.FromArgb(255, 128, 0), //Orange }; static public Color UIntToColor(uint color) { var a = (byte)(color &gt;&gt; 24); var r = (byte)(color &gt;&gt; 16); var g = (byte)(color &gt;&gt; 8); var b = (byte)(color &gt;&gt; 0); return Color.FromArgb(a, r, g, b); } </code></pre> <p>And here are the RGB values in hex and 8-bit-per-channel representations:</p> <pre class="lang-python prettyprint-override"><code>kelly_colors_hex = [ 0xFFB300, # Vivid Yellow 0x803E75, # Strong Purple 0xFF6800, # Vivid Orange 0xA6BDD7, # Very Light Blue 0xC10020, # Vivid Red 0xCEA262, # Grayish Yellow 0x817066, # Medium Gray # The following don't work well for people with defective color vision 0x007D34, # Vivid Green 0xF6768E, # Strong Purplish Pink 0x00538A, # Strong Blue 0xFF7A5C, # Strong Yellowish Pink 0x53377A, # Strong Violet 0xFF8E00, # Vivid Orange Yellow 0xB32851, # Strong Purplish Red 0xF4C800, # Vivid Greenish Yellow 0x7F180D, # Strong Reddish Brown 0x93AA00, # Vivid Yellowish Green 0x593315, # Deep Yellowish Brown 0xF13A13, # Vivid Reddish Orange 0x232C16, # Dark Olive Green ] kelly_colors = dict(vivid_yellow=(255, 179, 0), strong_purple=(128, 62, 117), vivid_orange=(255, 104, 0), very_light_blue=(166, 189, 215), vivid_red=(193, 0, 32), grayish_yellow=(206, 162, 98), medium_gray=(129, 112, 102), # these aren't good for people with defective color vision: vivid_green=(0, 125, 52), strong_purplish_pink=(246, 118, 142), strong_blue=(0, 83, 138), strong_yellowish_pink=(255, 122, 92), strong_violet=(83, 55, 122), vivid_orange_yellow=(255, 142, 0), strong_purplish_red=(179, 40, 81), vivid_greenish_yellow=(244, 200, 0), strong_reddish_brown=(127, 24, 13), vivid_yellowish_green=(147, 170, 0), deep_yellowish_brown=(89, 51, 21), vivid_reddish_orange=(241, 58, 19), dark_olive_green=(35, 44, 22)) </code></pre> <p>For all you Java developers, here are the JavaFX colors:</p> <pre class="lang-java prettyprint-override"><code>// Don't forget to import javafx.scene.paint.Color; private static final Color[] KELLY_COLORS = { Color.web("0xFFB300"), // Vivid Yellow Color.web("0x803E75"), // Strong Purple Color.web("0xFF6800"), // Vivid Orange Color.web("0xA6BDD7"), // Very Light Blue Color.web("0xC10020"), // Vivid Red Color.web("0xCEA262"), // Grayish Yellow Color.web("0x817066"), // Medium Gray Color.web("0x007D34"), // Vivid Green Color.web("0xF6768E"), // Strong Purplish Pink Color.web("0x00538A"), // Strong Blue Color.web("0xFF7A5C"), // Strong Yellowish Pink Color.web("0x53377A"), // Strong Violet Color.web("0xFF8E00"), // Vivid Orange Yellow Color.web("0xB32851"), // Strong Purplish Red Color.web("0xF4C800"), // Vivid Greenish Yellow Color.web("0x7F180D"), // Strong Reddish Brown Color.web("0x93AA00"), // Vivid Yellowish Green Color.web("0x593315"), // Deep Yellowish Brown Color.web("0xF13A13"), // Vivid Reddish Orange Color.web("0x232C16"), // Dark Olive Green }; </code></pre> <p>the following is the unsorted kelly colors according to the order above.</p> <p><a href="http://i.stack.imgur.com/oIczY.png"><img src="http://i.stack.imgur.com/oIczY.png" alt="unsorted kelly colors"></a></p> <p>the following is the sorted kelly colors according to hues (note that some yellows are not very contrasting)</p> <p><a href="http://i.stack.imgur.com/3lb9t.png"><img src="http://i.stack.imgur.com/3lb9t.png" alt=" sorted kelly colors"></a></p>
Why do pages get slower as memory usage increases in Internet Explorer <p>I browse to a web page that has a javascript memory leak. If I refresh the page multiple times, it will eventually use up a significant amount of memory, and javascript on the page will slow down. On this particular page, I notice a very significant slow down when IE gets up to 100MB of RAM, even though I have multiple GB free. </p> <p>My question is why should leaked objects cause javascript to run slowly? Does anyone have any insight into how the JS interpreter in IE is designed, such that this happens?</p>
<p>Even without swapping,that's caused by the "stupid" implementation of the Garbage Collector for Javascript in IE. It uses some heuristics that call the GC more often, if there are more objects. </p> <p>There's not way you can avoid this, other than avoiding memory leaks like hell and also avoid creating too many Javascript objects. </p> <p>Regards, Markus </p>
How do I resolve LNK1104 error with Boost Filesystem Library in MSCV? <p>I am having trouble getting my project to link to the Boost (version 1.37.0) Filesystem lib file in Microsoft Visual C++ 2008 Express Edition. The Filesystem library is <b>not</b> a header-only library. I have been following the <i><a href="http://www.boost.org/doc/libs/1_37_0/more/getting_started/windows.html" rel="nofollow">Getting Started on Windows</a></i> guide posted on the official boost web page. Here are the steps I have taken:</p> <ol> <li><p>I used bjam to build the complete set of lib files using:</p> <pre><code>bjam --build-dir="C:\Program Files\boost\build-boost" --toolset=msvc --build-type=complete </code></pre></li> <li><p>I copied the <i>/libs</i> directory (located in <i>C:\Program Files\boost\build-boost\boost\bin.v2</i>) to <i>C:\Program Files\boost\boost_1_37_0\libs.</i></p></li> <li><p>In Visual C++, under <i>Project > Properties > Additional Library Directories</i> I added these paths:</p> <ul> <li><i>C:\Program Files\boost\boost_1_37_0\libs</i></li> <li><i>C:\Program Files\boost\boost_1_37_0\libs\filesystem\build\msvc-9.0express\debug\link-static\threading-multi</i></li> </ul> <p>I added the second one out of desperation. It is the exact directory where <i>libboost_system-vc90-mt-gd-1_37.lib</i> resides.</p></li> <li><p>In <i>Configuration Properties > C/C++ > General > Additional Include Directories</i> I added the following path:</p> <ul> <li><i>C:\Program Files\boost\boost_1_37_0</i></li> </ul></li> <li><p>Then, to put the icing on the cake, under <i>Tools > Options VC++ Directories > Library files</i>, I added the same directories mentioned in step 3.</p></li> </ol> <p>Despite all this, when I build my project I get the following error:</p> <pre><code>fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_37.lib' </code></pre> <p>Additionally, here is the code that I am attempting to compile as well as a screen shot of the aformentioned directory where the (assumedly correct) lib file resides:</p> <pre><code>#include "boost/filesystem.hpp" // includes all needed Boost.Filesystem declarations #include &lt;iostream&gt; // for std::cout using boost::filesystem; // for ease of tutorial presentation; // a namespace alias is preferred practice in real code using namespace std; int main() { cout &lt;&lt; "Hello, world!" &lt;&lt; endl; return 0; } </code></pre>
<p>Ferruccio's answer contains most of the insight. However, Pukku made me realize my mistake. I am posting my own answer to give a full explanation. As Ferruccio explained, Filesystem relies on two libraries. For me, these are:</p> <ul> <li>libboost_system-vc90-mt-gd-1_37.lib</li> <li>libboost_filesystem-vc90-mt-gd-1_37.lib</li> </ul> <p>I must not have noticed that when I supplied the directory for <i>libboost_filesystem-vc90-mt-gd-1_37.lib</i>, the error output changed from</p> <pre><code>fatal error LNK1104: cannot open file 'libboost_filesystem-vc90-mt-gd-1_37.lib' </code></pre> <p>to</p> <pre><code>fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_37.lib' </code></pre> <p>Causing me to think that the error was persisting. This lead me to post some rather inaccurate information. Also, after reading that Filesystem requires two libraries, I now see the significance of the keyword <b>stage</b> for the bjam command. Supplying</p> <pre><code>bjam --build-dir="C:\Program Files\boost\build-boost" --toolset=msvc --build-type=complete stage </code></pre> <p>Causes bjam to place an additional directory, aptly named <i>stage</i>, in the <i>boost_1_37_0</i> directory. This folder contains a folder named <i>/lib</i>, which has copies of all of the lib files in one place. This is convenient for Visual C++ because you can supply it with this single directory and it will take care of all of the dependencies.</p>
RewriteRule checking file in rewriten file path exists <p>How can you use ModRewrite to check if a cache file exists, and if it does, rewrite to the cache file and otherwise rewrite to a dynamic file. </p> <p>For example I have the following folder structure:</p> <pre> pages.php cache/ pages/ 1.html 2.html textToo.html etc. </pre> <p>How would you setup the RewriteRules for this so request can be send like this:</p> <pre> example.com/pages/1 </pre> <p>And if the cache file exists rewrite tot the cache file, and if the cache file does not exists, rewrite to pages.php?p=1</p> <p>It should be something like this: (note that this does not work, otherwise I would not have asked this)</p> <pre> RewriteRule ^pages/([^/\.]+) cache/pages/$1.html [NC,QSA] RewriteCond %{REQUEST_FILENAME} -f [NC,OR] RewriteCond %{REQUEST_FILENAME} -d [NC] RewriteRule cache/pages/([^/\.]+).html pages.php?p=$1 [NC,QSA,L] </pre> <p>I can off coarse do this using PHP but I thought it had to be possible using mod_rewrite.</p>
<pre><code>RewriteRule ^pages/([^/\.]+) cache/pages/$1.html [NC,QSA] # At this point, we would have already re-written pages/4 to cache/pages/4.html RewriteCond %{REQUEST_FILENAME} !-f # If the above RewriteCond succeeded, we don't have a cache, so rewrite to # the pages.php URI, otherwise we fall off the end and go with the # cache/pages/4.html RewriteRule ^cache/pages/([^/\.]+).html pages.php?p=$1 [NC,QSA,L] </code></pre> <p>Turning off MultiViews is crucial (if you have them enabled) as well.</p> <pre><code>Options -MultiViews </code></pre> <p>Otherwise the initial request (/pages/...) will get automatically converted to /pages.php before mod_rewrite kicks in. You can also just rename pages.php to something else (and update the last rewrite rule as well) to avoid the MultiViews conflict.</p> <p>Edit: I initially included <code>RewriteCond ... !-d</code> but it is extraneous.</p>
How to validate this scenario in ASP.NET MVC? <p>First, a little bit of context (cause I know you all love it!):</p> <p>I have a model called <strong>Note</strong>. It has a field called <strong>Type</strong> which, in the database, is an integer value that designates which type of object this note belongs to (1 = Customer, 2 = Sales Lead, etc). A second field called <strong>Source</strong> designates the ID of the specific object that this note belongs to.</p> <p>For example, if I wanted to add a note to Customer #34, I would set <strong>Type</strong> to 1 and <strong>Source</strong> to 34.</p> <p>To help make things a little more readable, I have an Enum called <strong>DataObjectType</strong> that contains a mapping for each of the possible <strong>Type</strong> integer values to a friendly name. So, for example, <strong>DataObjectType.Customer</strong> is the same as a value of 1 in the <strong>Type</strong> field.</p> <p>Next, I have a custom route:</p> <pre><code>/Notes/New/{type}/{id} </code></pre> <p>and two controller actions to handle the creation of a new note:</p> <pre><code>[AcceptVerbs(HttpVerbs.Get)] public ActionResult New(DataObjectType type, int id) { Note note = new Note { Type = type, Source = id }; return View(note); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Note note) { // This is just an example note.Persist(); return View("New", note); } </code></pre> <p>First of all, I need to make sure that the value supplied to the <strong>{type}</strong> route value is valid for the <strong>DataObjectType</strong> enum. Can this be done with a route constraint? At the moment, the type argument of <strong>New()</strong> will accept any integer, whether it exists in <strong>DataObjectType</strong> or not.</p> <p>Second, I need to make sure that the object the user is trying to add the note to actually exists in the database before showing the New Note form at all. I could do this in the <strong>New()</strong> method easily, but there may come a time when a user posts the data directly to <strong>Create()</strong> without ever visiting <strong>New()</strong>. In such a case, I also need to verify that the object exists in the <strong>Create()</strong> method. What's the best way to do this in both methods without duplicating code?</p>
<p>When setting up your routes, there's a parameter you can use to specify constraints (done via Regex). You could use this to restrict the id there, but you would have to create a separate route for this scenario because you wouldn't want all "id"s to be filtered on that rule.</p> <p>Alternatively, you could just stick this check at the beginning of your controller action.</p> <p>As for ensuring that the note already exists in the db, I can't see any way around sticking a check at the beginning of the Create action.</p>
Is it possible, and what is the simplest way, to wrap events in jQuery <p><strong>Background</strong></p> <p>I would like to simulate the "active" behavior that most browsers support for links when they are clicked. For any element and event I would like to be able to add a css class to the element for the duration of the event. So in psuedo jQuery code I'd like to do this:</p> <pre><code>$(".button").click(function() { alert('clicked'); }); ..... $(".button").each( function() { var self = $(this); var innerClick = self.click; self.click( function() { self.addClass('active'); innerClick(); self.removeClass('active'); }); }); </code></pre> <p>Bonus points for anyone that can suggest a solution that is robust enough to maintain the wrapping if I bind further handlers to 'click'.</p>
<p>The problem is there is no general way to determine when an asynchronous call is done. You would need to set some kind of flag after the AJAX call (for example) is done and poll it with setInterval.</p> <p>With synchronous functions, the browser probably won't update the display until the click handler is done anyways, so you would never see the active state. You can get around that by using setTimeout to remove the active class after 1/10 of a second. For this case, you could write a function like this:</p> <pre><code>function makeClickHandler(innerFunction) { return function(event) { var self = this; $(self).addClass('active'); innerFunction.call(self, event); window.setTimeout(function() { $(self).removeClass('active'); }, 100); } } </code></pre> <p>You could then wrap any click handlers in the makeClickHandler function:</p> <pre><code>$(".button").click(makeClickHandler(function() { alert('clicked'); })); </code></pre> <p>Here's an example of how you could handle asynchronous events, but at this point, it might just be easier to add/remove the class in the individual event handlers.</p> <pre><code>function makeAsyncClickHandler(innerFunction) { return function(event) { var self = this; $(self).addClass('active').data("done", false); innerFunction.call(self, event); var intervalID = window.setInterval(function() { if ($(self).data("done")) { $(self).removeClass('active'); window.clearInterval(intervalID); } }, 100); } } </code></pre> <p>The inner function would have to call</p> <pre><code>$(this).data("done", true); </code></pre> <p>when the asynchronous part is finished.</p> <p>It would probably be easier to write "start" and "finish" functions that you can call on the element at the beginning of the function and after the event is finished.</p>
Jython and python modules <p>I've just started using the <code>PythonInterpreter</code> from within my Java classes, and it works great! However, if I try to include python modules (<code>re</code>, <code>HTMLParser</code>, etc.), I'm receiving the following exception (for <code>re</code>):</p> <pre> Exception in thread "main" Traceback (innermost last): File "", line 1, in ? ImportError: no module named re </pre> <p>How could I make the classes from the jython jar "see" the modules python has available?</p>
<p>You embed jython and you will use some Python-Modules somewere:</p> <p>if you want to set the path (sys.path) in your Java-Code :</p> <pre><code>public void init() { interp = new PythonInterpreter(null, new PySystemState()); PySystemState sys = Py.getSystemState(); sys.path.append(new PyString(rootPath)); sys.path.append(new PyString(modulesDir)); } </code></pre> <p>Py is in org.python.core.</p> <p>rootPath and modulesDir is where YOU want !</p> <p>let rootPath point where you located the standard-jython-lib</p> <p>Have a look at src/org/python/util/PyServlet.java in the Jython-Source-Code for example</p>
How do I remove VSS hooks from a VS Web Site? <p>I have a Visual Studio 2008 solution with 7 various projects included with it. 3 of these 'projects' are Web Sites (the kind of project without a project file).</p> <p>I have stripped all the various Visual Sourcesafe files from all the directories, removed the Scc references in the SLN file and all the project files that exist. I deleted the SUO file and all the USER files also. Visual Studio still thinks that 2 of the Web Sites are still under source control, and it adds the Scc entries back into the SLN file for me.</p> <p><strong>Does anybody know <em>how</em> VS still knows about the old source control?</strong></p> <p><em>Edit:</em> Another thing that I didn't mention is that the files I'm trying to remove VSS hooks from has been copied outside of VSS's known working directories, the python script run and manual edits to files made before the solution is opened in VS 2008 or VS 2005 (I had the problem with both).</p> <p>Here is a python script that I used to weed out these files and let me know which files needed manually edited.</p> <pre><code>import os, stat from os.path import join def main(): startDir = r"C:\Documents and Settings\user\Desktop\project" manualEdits = [] for root, dirs, files in os.walk(startDir, topdown=False): if '.svn' in dirs: dirs.remove('.svn') for name in files: os.chmod(join(root,name), stat.S_IWRITE) if name.endswith(".vssscc") or name.endswith(".scc") or name.endswith(".vspscc") or name.endswith(".suo") or name.endswith(".user"): print "Deleting:", join(root, name) os.remove(join(root,name)) if name.endswith("sln") or name.endswith("dbp") or name.endswith("vbproj") or name.endswith("csproj"): manualEdits.append(join(root, name)) print "Manual Edits are needed for these files:" for name in manualEdits: print name if __name__ == "__main__": main() </code></pre>
<p>It probably is only trying to add it on your instance of VS. You have to remove the cache so VS thinks its no longer under SS</p> <ol> <li>under file -> SourceControl -> Workspaces</li> <li>Select the SS location</li> <li>Edit</li> <li>Choose the working folder</li> <li>Remove!</li> </ol>
How can I reference a popup window from two different pages? <p>I need to allow a user to click a link in "page-1.htm" and open a popup window. Then, when the user browses to "page-2.htm" in the main browser window I need to be able to reference the popup window.</p> <p><strong>JavaScript in "page-1.htm"</strong></p> <pre><code>var playerWin = window.open("player.htm", "playerWin", "width=300,height=130"); playerWin.play("song.mp3"); // play() is a function in player.htm </code></pre> <p><strong>JavaScript in "page-2.htm"</strong></p> <pre><code>playerWin.play("tune.mp3"); </code></pre> <p>This code in page-2.htm generates an error "playerWin is not defined". That is understandable because no variable named <em>playerWin</em> has been defined on page-2.htm. </p> <p>My question is: Am I able to reference the popup window from page-2.htm?</p>
<p>I just did a quick test even after you leave the opener page, the popup still have 'opener' object and you can access it. So either poll the opener and reset the reference, or add a timer after you leave the page to wait and then relink.</p> <p>1.htm</p> <pre><code>&lt;script&gt; var w = window.open("p.htm", "playerWin", "width=300,height=130"); &lt;/script&gt; &lt;a href="2.htm"&gt;2&lt;/a&gt; </code></pre> <p>p.htm</p> <pre><code>&lt;a href="javascript:opener.w=this;"&gt;re-link&lt;/a&gt; </code></pre> <p>2.htm</p> <pre><code>&lt;script&gt; var w; &lt;/script&gt; &lt;a href="javascript:alert(w);"&gt;check&lt;/a&gt; </code></pre>
Custom Control events not firing <p>I have a custom control with a LinkButton on it. When I click the LinkButton, its click event does not fire.</p> <pre><code>[ToolboxData("&lt;{0}:View runat=server&gt;&lt;/{0}:View&gt;")] public class View : Control { private LinkButton lbNextPage; protected override void CreateChildControls() { lbNextPage = new LinkButton() { ID = "lbNextPage", Text = "Next Page" }; lbNextPage.Click += delegate(object sender, EventArgs e) { Page.Response.Write("Event Fires!"); }; Controls.Add(lbNextPage); } } </code></pre> <p>I have extracted only the code responsible for the rendering of the LinkButton and its event (which is what is included above), so as to remove all other factors. </p> <p>Any idea why the event is not firing? Am I missing something?</p>
<p>It is essentially because the control is created too late in the page life cycle. As per the <a href="http://msdn.microsoft.com/en-us/library/ms178472.aspx" rel="nofollow">MSDN Lifecycle document</a>, you need to create any dynamic controls in PreInit and not in CreateChildControls. If you're developing a custom control as you are, all your dynamic controls need to be created in an Init override and the events hooked up there.</p> <p>Hope this helps! :)</p>
git: switch branch without detaching head <p>I have a repository on github with a main branch (master) and a branch for some experimental work. I made some commits and pushed to the experimental branch and everything was fine.</p> <p>Now, on a different machine, I try to clone my repository (git clone <em>repository</em>) and then switch to the experimental branch (git checkout <em>branchname</em>) but every time I do this my head gets detached and I can't push my changes. What am I doing wrong? I get the feeling I'm missing a fundamental git concept someplace but reading random git man pages isn't giving me any clues.</p> <p>I'm new to git so I'm sorry if I'm being an idiot but I can't find anything in the docs that will help me reattach my head.</p> <p><strong>EDIT</strong></p> <p>The concept of a tracking branch is what I was missing. Now that I grok that concept everything is clear. Personally, I find the <code>git branch --track</code> syntax to be much more intuitive than <code>git checkout -b branch-name origin/branch-name</code>.</p> <p>Thanks for the help!</p>
<pre class="lang-bash prettyprint-override"><code># first time: make origin/branchname locally available as localname git checkout -b localname origin/branchname # othertimes git checkout localname git push origin </code></pre> <p>For convenience, you may use the same string for localname &amp; branchname<br> When you checked out <code>origin/branchname</code> you weren't really checking out a branch. <code>origin/branchname</code> is a "remote" name, and you can get a list of them with </p> <pre><code>branch -a </code></pre> <p>If you have colours enabled, local branches will be one colour, and remote another. </p> <p>You have to first make a remote branch tracked locally in order to be able to switch-to and work on it.</p>
Use reflection to set a property value to Nothing (Null) <p>Edit: Based on the answer from LoveMeSomeCode, I believe this issue only appears in VB.Net.</p> <p>I'm trying to revert a class to a previous state by saving the old values of changed properties in a dictionary and setting them via reflection when I need to revert. I'm having a problem where if the old value is Nothing (null) I get a null reference exception when trying to set the property. Here's what I've tried.</p> <p>Assume a for each loop like this:</p> <pre><code>For Each pair As KeyValuePair(Of String, Object) In myOldValues ... Next </code></pre> <p>Method 1:</p> <pre><code>CallByName(Me, pair.Key, CallType.Set, pair.Value) </code></pre> <p>Method 2:</p> <pre><code>Me.GetType().InvokeMember(pair.Key, Reflection.BindingFlags.SetProperty, Nothing, Me, pair.Value) </code></pre> <p>Method 3:</p> <pre><code>Dim propInfo As System.Reflection.PropertyInfo = Me.GetType.GetProperty(pair.Key) propInfo.SetValue(Me, Convert.ChangeType(pair.Value, propInfo.PropertyType), Nothing) </code></pre> <p>For each of these methods I get a null reference exception when pair.Value is null. The setter is capable of holding a null value (frequently the property is a string). What am I doing wrong or how can I work around it?</p> <p><strong>Edit:</strong> Each method fails if I pass it null directly as well.</p> <p><strong>Edit:</strong> Here are the stack traces if they help anyone:</p> <p><strong>Method 1</strong> System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.VisualBasic.CompilerServices.Symbols.Container.InvokeMethod(Method TargetProcedure, Object[] Arguments, Boolean[] CopyBack, BindingFlags Flags) at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean OptimisticSet, Boolean RValueBase, CallType CallType) at Microsoft.VisualBasic.CompilerServices.Versioned.CallByName(Object Instance, String MethodName, CallType UseCallType, Object[] Arguments) at <em>myProject</em>.Presenter.CustomerDetailPresenter.RevertCustomer() in <em>myfile</em>:line 378</p> <p><strong>Method 2</strong> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object. at <em>myProject</em>.Presenter.CustomerDetailPresenter.set_City(String value) --- End of inner exception stack trace --- at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct&amp; sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args) at <em>myProject</em>.Presenter.CustomerDetailPresenter.RevertCustomer()</p> <p><strong>Method 3</strong> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object. at <em>myProject</em>.Presenter.CustomerDetailPresenter.set_City(String value) --- End of inner exception stack trace --- at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct&amp; sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)</p> <p>at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args) at <em>myProject</em>.Presenter.CustomerDetailPresenter.RevertCustomer()</p>
<p>The fact that you are seeing this in the 2nd and 3rd option stack traces</p> <blockquote> <p>System.NullReferenceException: Object reference not set to an instance of an object. at myProject.Presenter.CustomerDetailPresenter.set_City(String value)</p> </blockquote> <p>makes me think that there is something in your CustomerDetailPresenter.City property setter that is not handling the null value. What is the implementation of your property setter? Is that any validation or auditing code that could be failing?</p> <p>Update 03-24-2009: A quick test in VB, and this code works as intended. I tried to capture the scenario you describe. </p> <p>My test class that has its property set (in part):</p> <pre><code>Public Class MyObject Private mId As Integer Private mName As String Private mDOB As Date ....... ....... Public Property Name() As String Get Return mName End Get Set(ByVal Value As String) mName = Value End Set End Property </code></pre> <p>I have created a PropertyState class that will hold the property name, value and type. And the code to set the property dynamically is:</p> <pre><code>Private Sub SetValues() 'get object that we are working with Dim ty As Type = mObjectInstance.GetType 'create our property name/value info Dim info As New PropertyState With info .PropName = "Name" .OriginalValue = Nothing .ValueType = GetType(String) End With 'now use reflection to set value on object Dim prop As PropertyInfo = ty.GetProperty("Name", BindingFlags.Instance Or BindingFlags.Public) 'use Convert.ChangeType to duplicate problem scenario Dim newValue = Convert.ChangeType(Nothing, GetType(String)) 'prop.SetValue(mObjectInstance, newValue, BindingFlags.Instance Or BindingFlags.Public, Nothing, Nothing, Globalization.CultureInfo.CurrentUICulture) prop.SetValue(mObjectInstance, Convert.ChangeType(info.OriginalValue, info.ValueType), Nothing) DisplayValues(CType(mObjectInstance, MyObject)) End Sub </code></pre> <p>I used two different overloads of the SetValue method, I have found that not explicity setting the BindingFlags can cause reflection issues at times. However, in this case, both overlaods work fine.</p> <p>So, I look back to the stack trace you posted in your question:</p> <blockquote> <p>System.NullReferenceException: Object reference not set to an instance of an object. at myProject.Presenter.CustomerDetailPresenter.set_City(String value)</p> </blockquote> <p>the fact that the set_City() setter is what is throwing the exception indicates that the method is being found and called successfully. The null(nothing) value is being passed in as requested. So, the bug is not in the reflection but in what is happening as a result of the property setter being called. You probably have already tried this, but setting a break point in the setter or setting the IDE to break on all managed exceptions to see if you can capture the actual cause? Or, is the state of the stored property info what is expected? Name, type and value all in sync? </p> <p>Hope this helps.</p>
Hide text using css <p>I have a tag in my html like this:</p> <pre><code>&lt;h1&gt;My Website Title Here&lt;/h1&gt; </code></pre> <p>Using css I want to replace the text with my actual logo. I've got the logo there no problem via resizing the tag and putting a background image in via css. However, I can't figure out how to get rid of the text. I've seen it done before basically by pushing the text off the screen. The problem is I can't remember where I saw it. </p>
<p>This is one way:</p> <pre class="lang-css prettyprint-override"><code>h1 { text-indent: -9999px; /* sends the text off-screen */ background-image: url(/the_img.png); /* shows image */ height: 100px; /* be sure to set height &amp; width */ width: 600px; white-space: nowrap; /* because only the first line is indented */ } h1 a { outline: none; /* prevents dotted line when link is active */ } </code></pre> <p>Here is <a href="http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/">another way</a> to hide the text while avoiding the huge 9999 pixel box that the browser will create:</p> <pre class="lang-css prettyprint-override"><code>h1 { background-image: url(/the_img.png); /* shows image */ height: 100px; /* be sure to set height &amp; width */ width: 600px; /* Hide the text. */ text-indent: 100%; white-space: nowrap; overflow: hidden; } </code></pre>
Customizing an Admin form in Django while also using autodiscover <p>I want to modify a few tiny details of Django's built-in <code>django.contrib.auth</code> module. Specifically, I want a different form that makes username an email field (and email an alternate email address. (I'd rather not modify <code>auth</code> any more than necessary -- a simple form change <em>seems</em> to be all that's needed.)</p> <p>When I use <code>autodiscover</code> with a customized <code>ModelAdmin</code> for <code>auth</code> I wind up conflicting with <code>auth</code>'s own admin interface and get an "already registered" error.</p> <p>It looks like I have to create my own admin site, enumerating all of my Models. It's only 18 classes, but it seems like a DRY problem -- every change requires both adding to the Model <strong>and</strong> adding to the customized admin site.</p> <p>Or, should I write my own version of "<code>autodiscover</code> with exclusions" to essentially import all the <code>admin</code> modules <strong>except</strong> <code>auth</code>?</p>
<p>None of the above. Just use admin.site.unregister(). Here's how I recently added filtering Users on is_active in the admin (<strong>n.b.</strong> is_active filtering is now on the User model by default in Django core; still works here as an example), all DRY as can be:</p> <pre><code>from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User class MyUserAdmin(UserAdmin): list_filter = UserAdmin.list_filter + ('is_active',) admin.site.unregister(User) admin.site.register(User, MyUserAdmin) </code></pre>
Managing Reusable Components <p>I have projects A and B. Both projects use component C (a graphical library for example). I get a issue ticket reporting that A has a bug. I determine that really the bug is in the C component. I create a branch for C, fix it, check back in, retag it, change the dependencies on A and create a new A install. </p> <p>Question: How can I make B aware of the change in its C component so it can benefit of the bug fix detected in A? What would be a good tool/script to control such configuration management scenarios? I tried with Jira but I could not find a good way of making two projects dependent of one or more components.</p>
<p>Configuration management always seems to be more 'hand-wavy' than it should be. In short, it really depends on you local policies.</p> <p>My suggestion would be to use a Continuous Integration server like Hudson or Bamboo. I know that Hudson allows you to create project dependencies so that the latest build of component C will automatically be imported into both A and B.</p> <p>However from a configuration management point of view, you really want control over which version of C is used in which build of A and/or B, so you might want to dig a bit deeper.</p>
Best way to integrate two ASP.NET sites <p>I have two ASP.NET sites that are used for managing patient information. One application allows entry/edit of the patient demographics and the other allows different types of assessments to be completed for each patient. The two sites each have a distinct look and feel and both use SSL.</p> <p>One of our analysts wants to have a "launch page" (a third application, basically) that will allow the user to lookup a patient record on the launch page and then after choosing a patient, click on a button to launch them either into the data entry application or into the assessment application.</p> <p>I'm hesitant to do this for a number of reasons... 1) these are two separate applications and were designed to be separate apps and will always be used as separate applications by most users. 2) Because the apps have a different look/feel, the user will know they are being shuffled around two applications. 3) Being separate apps, how difficult will it be to pass my login credentials from the launch page to the other two apps? 4) Are there any SSL implications when bouncing between separate apps with different URLs?</p> <p>Ideally we would combine the two apps into one and turn features on and off based on the user's needs, but that is not an option at this time.</p> <p>Any advice and/or insight will be appreciated! </p> <p>Thanks much...DL</p>
<p>Have you considered exposing the elements you need as web services?</p>
Python/Twisted multiuser server - what is more efficient? <p>In Python, if I want my server to scale well CPU-wise, I obviously need to spawn multiple processes. I was wondering which is better (using Twisted):</p> <p>A) The manager process (the one who holds the actual socket connections) puts received packets into a shared queue (the one from the multiprocessing module), and worker processes pull the packets out of the queue, process them and send the results back to the client.</p> <p>B) The manager process (the one who holds the actual socket connections) launches a deferred thread and then calls the apply() function on the process pool. Once the result returns from the worker process, the manager sends the result back to the client.</p> <p>In both implementations, the worker processes use thread pools so they can work on more than one packet at once (since there will be a lot of database querying).</p>
<p>I think that B is problematic. The thread would only run on one CPU, and even if it runs a process, the thread is still running. A may be better.</p> <p>It is best to try and measure both in terms of time and see which one is faster and which one scales well. However, I'll reiterate that I highly doubt that B will scale well.</p>
How do you give a junior developer a shot on a big project with tight deadlines? <p>I'm looking for advice on how to give a junior developer a chance to gain experience on a big project with tight deadlines without hurting the timeline. If we all know it will take a little longer with the developer because of less experience, then what is the best way to give them a portion of the project and spread the risk? Giving these developers the ability to learn on the job on real projects instead of handing down maintenance work all the time is important to me, and I want to find a way to make it work.</p>
<p>You need to know if they grasp the problem you are handing down. When I have to do this here is my approach:</p> <ul> <li>Give them a piece I think is a stretch for them but doable.</li> <li>Explain the importance of the piece, how it fits into the larger picture, and how they will contribute to the project success.</li> <li>Ask them to go away, take some time to think about it and then write up several possible solutions with pros and cons of each. This shows me if they have grasped the problem and if they can design a solution.</li> <li>If they come up with something that looks reasonable, then let them at it. If not, we meet and discuss the problem some more and I give them another shot.</li> </ul> <p>Giving them a chance to design the solution gives them ownership and lets them prove themselves. Having them communicate the design to you first with pros and cons gives you the confidence that they can complete the solution on time.</p> <p>If they can not think of any possible solutions and possible outcomes of each solution then they are not ready to step up to this problem. They will need closer mentoring and smaller problems which have been designed by another more skilled developer first.</p>
Database update after inserting rows into Dataset <p>I am a newbie to Database programming. After inserting a couple of rows into a DataSet object, I am trying to write back the updated DataSet to the Database but cannot figure out how to do it.</p> <p>Can you give an example for the following please?</p> <ul> <li>what SQL insert command to use if DataSet is already updated with new rows</li> <li>Databinding example - especially considering an initially empty table in the DB</li> </ul> <p>I am using SQLExpress 2008 &amp; its C# WinForms application.</p> <p>thanks</p> <p>ps: I have already looked at the related questions here. This one is different in that I am first adding my new data into a DataSet and want to update the DB then.</p>
<p>What you need to do is configure a DataAdapter or TableAdapter object that contains the proper Update command. Then when you are done updating the rows in your DataSet, you can call DataAdapter.Update(DataSet) and it will do all the hard work for you.</p> <p>Since you're starting out, I'd suggest looking at the TableAdapter objects that are built using the XSD schema tool. They allow you to simply drop your tables into the XSD to create a schema, and then let the wizard generate the appropriate SQL commands (it'll even do Stored Procedures for you) to handle all the CRUD work. I've been using these for a while and love them.</p> <p>EDIT: In response to Sesh's request, Scott Gu has a great tutorial series on using the Table Adapters <a href="http://weblogs.asp.net/scottgu/archive/2006/06/22/454436.aspx" rel="nofollow">here</a>. I wanted to post this in the answer so others can find it easily.</p>
asp.net http server push to client <p>What's the best way to push info from a server to a web client? I know it's possible to setup sockets with Silverlight and Flash but I want to stay way from those two technologies.</p> <p>Gmail seems to do a great job of polling the servers for updated emails and even their chat programs work great (all working in my web browser). Any ideas on the best way to do something like this but using asp.net?</p> <p>Edit: If I have to poll, i'd like to poll the server every 2 or 3 seconds. So I'm not sure how to do this without bringing the web server to it's knees under heavy usage.</p>
<p>Since you mention <code>ASP.NET</code> you should be using <code>SignalR</code>. See my other answer here: <a href="http://stackoverflow.com/questions/11409563/instant-notifications-like-facebook/11410184#11410184">Instant notifications like Facebook</a></p>
How I do to force the browser to not store the html form field data? <p>When typing in html forms, browsers like firefox or ie store the values, sometimes quietly. So when typing in another webforms, the browser smartly suggest the same information. Another method to show the dropdown list is double-clicking an empty textbox.</p> <p>In a e-commerce website, the customer type the credit card number, and another sensitive information. How I do to avoid or block the browser to store that sensitive information?</p> <p>Another worry is about tampered form data stored (by a malware, by example). Then the customer can select this contaminated data and compromise the site.</p> <p>Regards.</p>
<p>Try with the atribute <code>autocomplete="off"</code></p> <p>It should work for single input elements:</p> <pre><code>&lt;input type="text" autocomplete="off" name="text1" /&gt; </code></pre> <p>or to the entire form:</p> <pre><code>&lt;form name="form1" id="form1" method="post" autocomplete="off" action="http://www.example.com/action"&gt; [...] &lt;/form&gt; </code></pre> <p>And specifically for <strong>ASP .NET</strong> you can set it like this:</p> <p>The WebForms form:</p> <pre><code>&lt;form id="Form1" method="post" runat="server" autocomplete="off"&gt; </code></pre> <p>Textboxes:</p> <pre><code>&lt;asp:TextBox Runat="server" ID="Textbox1" autocomplete="off"&gt;&lt;/asp:TextBox&gt; </code></pre> <p>or at runtime:</p> <pre><code>Textbox1.Attributes.Add("autocomplete", "off"); </code></pre>
Best Practices - set jQuery property from Code-Behind <p>I need to set a single property in a jQuery command using a value that is calculated in the code-behind. My initial thought was to just use <code>&lt;%= %&gt;</code> to access it like this:</p> <p>.aspx</p> <pre><code>&lt;script type="text/javascript" language="javascript"&gt; $('.sparklines').sparkline('html', { fillColor: 'transparent', normalRangeMin: '0', normalRangeMax: &lt;%= NormalRangeMax() %&gt; }); &lt;/script&gt; </code></pre> <p>.aspx.cs</p> <pre><code>protected string NormalRangeMax() { // Calculate the value. } </code></pre> <p>It smells odd to have to call from the ASPX page to just get a single value though. Not to mention I have an entire method that does a small calculation just to populate a single property.</p> <p>One alternative would be to create the entire <code>&lt;script&gt;</code> block in the code-behind using <code>clientScriptManager.RegisterClientScriptBlock</code>. But I really don't like putting entire chunks of JavaScript in the code-behind since its, well, JavaScript.</p> <p>Maybe if I end up having many of these methods I can just put then in a partial class so at least they are physically separate from the rest of the code.</p> <p>What method would you recommend as being easy to understand and easy to maintain?</p>
<p>The &lt;% %> works fine. One thing that I do is set a value in a hidden field on the page (then writing the necessary javascript to extract that value), this is nice because I can change that hidden field via javascript and when/if the page posts back I can get that new value from code behind as well.</p> <p>If you need to call the method on demand, you could do an jQuery AJAX call to a ASP.NET WebMethod to grab the data and re-populate the various options. You can find a good tutorial on how to do that here: <a href="http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/" rel="nofollow">http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/</a></p> <p>Below is some sample code using the hidden field method (using the datepicker control, but you'll get the idea):</p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head runat="server"&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;asp:TextBox ID="txtCalendar" runat="server" /&gt; &lt;asp:HiddenField ID="hfTest" runat="server" /&gt; &lt;/div&gt; &lt;/form&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://ui.jquery.com/latest/ui/ui.datepicker.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var dateMinimum = new Date($("#&lt;%= hfTest.ClientID %&gt;").val()); $(function() { $("#&lt;%= txtCalendar.ClientID %&gt;") .datepicker({ minDate: dateMinimum }); }); &lt;/script&gt; &lt;/body&gt; </code></pre> <p></p> <p>And the code behind Page_Load method:</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { // Set Value of Hidden Field to the first day of the current month. this.hfTest.Value = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).ToString("MM/dd/yyyy"); } </code></pre>
Why NSUserDefaults failed to save NSMutableDictionary in iPhone SDK? <p>I'd like to save an <code>NSMutableDictionary</code> object in <code>NSUserDefaults</code>. The key type in <code>NSMutableDictionary</code> is <code>NSString</code>, the value type is <code>NSArray</code>, which contains a list of object which implements <code>NSCoding</code>. Per document, <code>NSString</code> and <code>NSArray</code> both are conform to <code>NSCoding</code>.</p> <p>I am getting this error: </p> <blockquote> <p>[NSUserDefaults setObject: forKey:]: Attempt to insert non-property value.... of class NSCFDictionary.</p> </blockquote> <p>Any solution for this?</p>
<p>I found out one alternative, before save, I encode the root object (<code>NSArray</code> object) using <code>NSKeyedArchiver</code>, which ends with <code>NSData</code>. Then use UserDefaults save the <code>NSData</code>. </p> <p>When I need the data, I read out the <code>NSData</code>, and use <code>NSKeyedUnarchiver</code> to convert <code>NSData</code> back to the object. </p> <p>It is a little cumbersome, because i need to convert to/from <code>NSData</code> everytime, but it just works.</p> <p>Here is one example per request:</p> <p>Save:</p> <pre><code>NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSMutableArray *arr = ... ; // set value NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arr]; [defaults setObject:data forKey:@"theKey"]; [defaults synchronize]; </code></pre> <p>Load:</p> <pre><code>NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSData *data = [defaults objectForKey:@"theKey"]; NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithData:data]; </code></pre> <p>The element in the array implements </p> <pre><code>@interface CommentItem : NSObject&lt;NSCoding&gt; { NSString *value; } </code></pre> <p>Then in the implementation of <code>CommentItem</code>, provides two methods:</p> <pre><code>-(void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:value forKey:@"Value"]; } -(id)initWithCoder:(NSCoder *)decoder { self.value = [decoder decodeObjectForKey:@"Value"]; return self; } </code></pre> <p>Anyone has better solution?</p> <p>Thanks everyone. </p>
mod_rewrite generating errors in log <p>On my site I have mod_rewrite rules to make the URLs more search engine friendly, and it all works fine on the frontend, but I'm getting errors in the error log like this</p> <pre><code>[Thu Jan 22 22:51:36 2009] [error] [client {IP ADDRESS HERE}] File does not exist: /{some rewritten directory} </code></pre> <p>The rules I'm using are rather simple, along the lines of</p> <pre><code>RewriteRule ^pages/(.*)_(.*).html$ page.php?id=$2 </code></pre> <p>Is there a way to avoid these errors?</p>
<p><a href="http://httpd.apache.org/docs/2.2/mod/core.html#options" rel="nofollow"><code>MultiViews</code></a> could cause this. If it is enabled, Apache tries to find a file similar to the requested URI before passing the request along to mod_rewrite. So try to disable it:</p> <pre><code>Options -MultiViews </code></pre>
examples of both good and bad application user interface design? <p>I'm a blind student who's taking a required UI class. One of the assignments is to take screen shots of both a good and bad application user interface and comment on what's good and bad about it. I'll have a reader help describe the interface to me but would like pointers on applications to check out. They must be windows apps. In answers I'd like a link to the application as well as brief comments on what to focus on in the UI, for example color scheme is horrible, badly labeled controls, cluttered layout, etc.</p>
<p>An interface experience for a Blind person is a relevant aspect of UI design. If I were in your position I wouldn't focus so much on the visual aspect of user interfaces. Go from your personal experience. What is an application that you, as a blind person had a great degree of difficulty using? What applications are a joy to use?</p> <p>If I were in your teacher's position, I would find such descriptions far more valuable than an attempt at pretending as though you can see, and that things like colors or fonts are relevant to you. (unless you are only partially blind, in which case font size may indeed be a relevant factor)</p> <p>There are a great many people in my field that are keenly and constantly interested in such testimonials and evaluations from blind people. Not just in an academic context. I work for a government organisation that is required to make its resources accessible to disabled people. Don't sell your own perspective short, just because of a poorly worded assignment.</p>
ASP.NET MVC and Automatic RESTful Features <p>Does ASP.NET MVC have anything like the RESTful out-of-the-box features like Ruby on Rails 2.0?<br /> For example: <a href="http://www.viget.com/extend/curl-and-your-rails-2-app/" rel="nofollow">cURL and Your Rails 2 App</a></p> <p>I think this is the built in REST access to your Models. Since models can be implemented in different ways in ASP.NET MVC is there a feature like this?</p>
<p>I think the closest you'll come to this that I know of right now is some of the work Rob Conery is doing like this:</p> <p><a href="http://blog.wekeroad.com/blog/subsonic-mvc-scaffold-addin/" rel="nofollow">http://blog.wekeroad.com/blog/subsonic-mvc-scaffold-addin/</a></p> <p>It's not exactly what you're asking for, but it provides what you want via scaffolding instead of the cURL type implementation.</p>
Java and unix <p>I want to delete the old log files in log directory. To delete the log files which are more than 6 months, I have written the script like</p> <p>find /dnbusr1/ghmil/BDELogs/import -type f -mtime +120 -exec rm -f {} \;</p> <p>By using this script i can able to delete the old files. But how to invoke this script by using java? please any one help me...</p>
<p>If portability is an issue, preventing you from running with Runtime.exec(), this code is quite trivial to write in Java using File and a FilenameFilter.</p> <p>Edit: Here is a static method to delete a directory tree... you can add in the filtering logic easily enough:</p> <pre><code>static public int deleteDirectory(File dir, boolean slf) { File[] dc; // directory contents String dp; // directory path int oc=0; // object count if(dir.exists()) { dir=dir.getAbsoluteFile(); if(!dir.canWrite()) { throw new IoEscape(IoEscape.NOTAUT,"Not authorized to delete directory '"+dir+"'."); } dp=dir.getPath(); if(dp.equals("/") || dp.equals("\\") || (dp.length()==3 &amp;&amp; dp.charAt(1)==':' &amp;&amp; (dp.charAt(2)=='/' || dp.charAt(2)=='\\'))) { // Prevent deletion of the root directory just as a basic restriction throw new IoEscape(IoEscape.GENERAL,"Cannot delete root directory '"+dp+"' using IoUtil.deleteDirectory()."); } if((dc=dir.listFiles())!=null) { for(int xa=0; xa&lt;dc.length; xa++) { if(dc[xa].isDirectory()) { oc+=deleteDirectory(dc[xa]); if(!dc[xa].delete()) { throw new IoEscape(IoEscape.GENERAL,"Unable to delete directory '"+dc[xa]+"' - it may not be empty, may be in use as a current directory, or may have restricted access."); } } else { if(!dc[xa].delete()) { throw new IoEscape(IoEscape.GENERAL,"Unable to delete file '"+dc[xa]+"' - it may be currently in use by a program, or have restricted access."); } } oc++; } } if(slf) { if(!dir.delete()) { throw new IoEscape(IoEscape.GENERAL,"Unable to delete directory '"+dir+"' - it may not be empty, may be in use as a current directory, or may have restricted access."); } oc++; } } return oc; } </code></pre>
How to read or capture Ctrl+some key or Alt+some key in C? <p>For example I want to do some thing when some combination of <kbd>Ctrl</kbd> key with any other key is pressed (or it may be <kbd>Alt</kbd> key).Then from the standard input how to read that key combination in C program as an input. <p>I tried with simple <code>getchar()</code> to know the ASCII values of these combinations. But it was some 1 to 25 and some other values for some key combinations. Is there any standard library function to read them. Dont ask me why do you want to do that. <p><strong>Edit</strong>: My platform is Turbo C on Windows.</p>
<p>The short answer: In a platform specific way.</p> <p>The long answer: C's Input/Output concept is that of the streams standard output and standard input. The getchar() function that you mentioned above simply reads from the standard input stream. C doesn't have any notion of keyboards, despite keyboards being a common input method. There are normally several layers of abstraction between your keyboard and what gets passed through to standard input in your C program. The mechanism to do this is implementation defined, and not part of C at all. You mentioned ASCII, but C doesn't require ASCII despite it being extremely common.</p> <p>Some libraries attempt to provide portable keyboard input facilities, such as <a href="http://www.libsdl.org/" rel="nofollow">SDL</a> and <a href="http://en.wikipedia.org/wiki/Curses_(programming_library)" rel="nofollow">curses</a>.</p> <p>See also the <a href="http://c-faq.com/osdep/index.html" rel="nofollow">comp.lang.c FAQ</a> on system dependencies, particularly 19.5.</p>
Can anybody provide XMLTextReader Custom Logic to read large XML fast...? <p>I want a help that i need a custom logic to read large XML of size 1GB.</p> <p>Thanks sivaram</p>
<p>the following code snippet might help you:</p> <pre><code>private void readXML() { XmlReaderSettings settings = new XmlReaderSettings(); //configure xml reader settings... using(XmlReader reader = XmlReader.Create("file.xml", settings)){ while (reader.Read()){ //read xml content.. } reader.Close(); } } </code></pre>
Usage of __slots__? <p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
<p>Quoting <a href="http://code.activestate.com/lists/python-list/531365/">Jacob Hallen</a>:</p> <blockquote> <p>The proper use of <code>__slots__</code> is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. This saves the overhead of one dict for every object that uses slots. While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.</p> <p>Unfortunately there is a side effect to slots. They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies. This is bad, because the control freaks should be abusing the metaclasses and the static typing weenies should be abusing decorators, since in Python, there should be only one obvious way of doing something.</p> <p>Making CPython smart enough to handle saving space without <code>__slots__</code> is a major undertaking, which is probably why it is not on the list of changes for P3k (yet).</p> </blockquote>
Ruby on rails application root <p>How do I change a rails app so that a controller foo appears as the application root? </p> <p>In other words, right now all the urls look like host.com/foo/... and I'd like to get rid of the foo and have simply host.com/... </p>
<p>In routes.rb, add:</p> <pre><code>map.root :controller =&gt; 'foo' </code></pre> <p>Full details in the <a href="http://api.rubyonrails.org/" rel="nofollow">API</a>.</p>
cool project to use a genetic algorithm for? <p>I'm looking for a practical application to use a genetic algorithm for. Some things that have thought of are:</p> <ul> <li>Website interface optimization</li> <li>Vehicle optimization with a physics simulator</li> <li>Genetic programming</li> <li>Automatic test case generation</li> </ul> <p>But none have really popped out at me. So if you had some free time (a few months) to spend on a genetic algorithms project, what would you choose to tackle?</p>
<p>One topic with lots of possibilities is to use evolutionary algorithms to evolve strategies for game playing. People have used evolution to generate strategies for poker, checkers/draughts, Go and many other games. The <a href="http://jgap.sourceforge.net/">J-GAP</a> people have used genetic programming to evolve bots for <a href="http://robocode.sourceforge.net/">Robocode</a>.</p> <p>I recently posted an <a href="http://blog.uncommons.org/2009/01/20/practical-evolutionary-computation-an-introduction/">introductory article</a> about evolutionary computation. It includes details of some of the things evolutionary algorithms have been used for. <a href="http://www.talkorigins.org/faqs/genalg/genalg.html">Adam Marczyk</a> has also written an excellent article with lots of examples. The <a href="http://geneticargonaut.blogspot.com/">Genetic Argonaut blog</a> contains dozens of links to interesting evolutionary projects.</p> <p>A less common type of evolutionary algorithm is the <a href="http://en.wikipedia.org/wiki/Learning_classifier_system">learning classifier system</a>. This evolves a set of rules for classifying inputs. It can be applied to the same kind of problems that neural networks are used for. It could be interesting to develop an LCS for a particular problem, such as attempting to predict sports results based on form.</p>
Running a managed application 2nd time shows different performance than 1st <p>I have a benchmarking application to test out the performance of some APIs that I have written. In this benchmarking application, I am basically using the QueryPerformanceCounter and getting the timing by dividing the difference of QPC values after and before calling into the API, by the frequency. But the benchmarking results seems to vary If I run the application (same executable running on the same set of Dlls) from different drives. Also, on a particular drive, running the application for the 1st time, closing the application and re-running it again produces different benchmarking results. Can anyone explain this behavior? Am I missing something here?</p> <p>Some more useful information:</p> <p>The behavior is like this: Run the application, close it and rerun it again, the benchmarking results seems to improve on the 2nd run and thereafter remains same. This behavior more prominent in case of running from C drive. I would also like to mention that my benchmark app has an option to rerun/retest a particular API without having to close the app. I do understand that there is jitting involved, but what I dont understand is that on the 1st run of app, when u rerun an API multiple times without closing the app, the performance stabilizes after a couple of runs, then when you close and rerun the same test, the performance seems to improve.</p> <p>Also, how do you account for the performance change when run from different drives? </p> <p><strong>[INFORMATION UPDATE]</strong></p> <p>I did an <strong>ngen</strong> and now the performance difference between the different runs from same location is gone. i.e. If I open the benchmark app, run it once, close it and rerun it from same location, it shows same values.</p> <p>But I have encountered another problem now. When I launch the app from D drive and run it a couple of times (couple of iterations of APIs within the same launch of benchmark prog), and then from the 3rd iteration onwards, the performance of all APIs seems to fall by around 20%. Then If you close and relaunch the app and run it, for first 2 iterations, it gives correct values (same value as that obtained from C), then again performance falls beyond that. This behavior is not seen when run from C drive. From C drive, no matter how many runs you take, it is pretty consistent.</p> <p>I am using large double arrays to test my API performance. I was worried that the GC would kick in inbetween the tests so I am calling GC.Collect() &amp; GC.WaitForPendingFinalizers() explictly before and after each test. So I dont think it has anything to do with GC.</p> <p>I tried using AQ time to know whats happening from 3rd iteration onwards, but funny thing is that When I run the application with AQ time profiling it, the performance does not fall at all.</p> <p>The performance counter as does not suggest any funny IO activity.</p> <p>Thanks Niranjan</p>
<p>Running an application brings its executable and other files from the hard drive into the OS's disk cache (in RAM). If it is run again soon afterwards, many of these files are likely to still be in cache. RAM is much faster than disk.</p> <p>And of course one disk may be faster than another.</p>
How to remove the linefeed or newline from a text file or cdr file including the spaces? <p>This is my situation, I was able to remove the spaces using trim or replace. But it does not remove the linefeed or newline at the end of each file. How can I remove the spaces and linefeed in C#?</p> <p>Thanks in advance.</p>
<p>You can call Trim method with all characters that you want to be removed like:</p> <pre><code>line = line.Trim(' ','\r','\n'); </code></pre>
How do I set tab size in the WPF RichTextBox <p>The WPF RichTextBox can be set to accept tabs in its input. It renders the result as a 4 character indent. I'd like to change that size. How can I change the default?</p>
<p>There is currently no support for this, but they are considering it for future release. Frustrating answer - I know!</p> <p>Source: <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/c610a492-cae8-444a-a657-05559da61fe3/" rel="nofollow">http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/c610a492-cae8-444a-a657-05559da61fe3/</a> (Answer from LesterLobo - MSFT)</p>
Incorrect answer in dll import in Python <p>In my Python script I'm importing a dll written in VB.NET. I'm calling a function of initialisation in my script. It takes 2 arguments: a path to XML file and a string. It returns an integer - 0 for success, else error. The second argument is passed by reference. So if success, it will get updated with success message. Otherwise, get updated with error message.</p> <p>When my script receives the integer, I should print the message in the second variable. I'm not able to do that.</p>
<p>Python strings are immutable. There is no way the string can be changed inside the function.</p> <p>So what you really want is to pass a <em>char buffer</em> of some sort. You can create those in python using the <code>ctypes</code> module. </p> <p>Please edit the question and paste a minimal snippet of the code so we can test and give more information.</p>
How do I edit contacts from the front end in Joomla 1.5x? <p>I'd have thought this would be a native feature (seeing as joomla allows you to connect contacts with user accounts) but we can't find any way to do this! </p> <p>Does anyone know of any extensions/modules that would allow this?</p> <p>I'm not so hot on PHP so i'd really love to not have to code this by hand!</p>
<p>This is an old thread, but since it is still opened maybe you haven't found a solution yet. I faced the same problem myself and I think having the ability to manage contacts from the frontend is an essential feature for Joomla! to become more usable as a simple webapp creation tool.</p> <p>Anyway, there are a couple of extensions that might help you out. However, both are commercial and don't support Joomla! 1.6. Here they are:</p> <ol> <li><p><a href="http://b-elektro.no/index.php?option=com_content&amp;view=article&amp;id=19%3afront-edit-address-book-for-joomla-15x&amp;catid=6%3aextentions&amp;Itemid=8" rel="nofollow">Front-edit address book</a>: simple interface. Note, however, that there might be a security issue with it. Google "front-edit address book exploits" and you shall find it (sorry, stackoverflow lets me post a max of 2 links per thread since I'm a new user). I emailed the developer and he assured me that the problem was already fixed, though.</p></li> <li><p><a href="http://grumpyengineering.com/purchase/grumpycontacts" rel="nofollow">Grumpy contacts</a>: on the demo site (there's a link at the page I pointed you to), it looked a little messy to my taste. In the Joomla! Extensions Directory, however, it has good reviews.</p></li> </ol> <p>I never used any of those since all my projects are already migrated to Joomla! 1.6.</p> <p>If you found another alternative in the meantime or even developed something yourself, please let me know.</p>
How do I create email with css and images from Rails? <p>How do you create and send emails from Rails application, that contain images and proper formatting? like the ones you get from facebook and like.</p>
<p>Assuming you know how to send normal plain-text emails from Rails using ActionMailer, to get <code>HTML</code> emails working you need to set a content type for your email.</p> <p>For example, your notifer might look like this:</p> <pre><code>class MyMailer &lt; ActionMailer::Base def signup_notification(recipient) recipients recipient.email_address_with_name subject "New account information" from "system@example.com" body :user =&gt; recipient content_type "text/html" end end </code></pre> <p>Note the <code>content_type "text/html"</code> line. This tells ActionMailer to send an email with a content type of <code>text/html</code> instead of the default <code>text/plain</code>.</p> <p>Next you have to make your mailer views output <code>HTML</code>. For example, your view file <code>app/views/my_mailer/signup_notification.html.erb</code> might look like the following:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt; &lt;style type="text/css" media="screen"&gt; h3 { color: #f00; } ul { list-style: none; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h3&gt;Your account signup details are below&lt;/h3&gt; &lt;ul&gt; &lt;li&gt;Name: &lt;%= @user.name %&gt;&lt;/li&gt; &lt;li&gt;Login: &lt;%= @user.login %&gt;&lt;/li&gt; &lt;li&gt;E-mail: &lt;%= @user.email_address %&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>As you can see the <code>HTML</code> view can include a <code>&lt;style&gt;</code> tag to define basic styles. Not all <code>HTML</code> and <code>CSS</code> is supported, especially across all mail clients, but you should definitely have sufficient formatting control over text styles.</p> <p>Embedding images is a bit tricker if you plan to display attached emails. If you are simply including emails from external sites, you can use an <code>&lt;img /&gt;</code> tag as you usually would in <code>HTML</code>. However, many mail clients will block these images from being displayed until the user authorises it. If you need to display attached images, the Rails plug-in <a href="http://rubyforge.org/frs/?group_id=4569">Inline Attachments</a> might be worth a look.</p> <p>For more information on Rails mailing support, the <a href="http://api.rubyonrails.org/classes/ActionMailer/Base.html">ActionMailer documentation</a> is a great resource</p>
SQL 2005: Agent job step output file naming <p>Does anyone know, please, if there's a way to specify "this machine" in a file path that SQL Server will like?</p> <p>I have an Agent job I want to script onto all my servers. It outputs to a file on the local machine so I want to script the file name as </p> <pre><code>\\localhost\&lt;shared-folder-name&gt;\&lt;file-name&gt; </code></pre> <p>Another reason is I'm planning to use log shipping for disaster recovery and I want the jobs to work the same whichever server they're running on. The script sets the job up fine but when I run the job I get an error "Unable to open Step output file". I think I've eliminated share and folder permissions: it works fine with <code>C:\&lt;folder-name&gt;\&lt;file-name&gt;</code>.</p>
<p>have you tried @@SERVERNAME?</p> <pre><code>SELECT @@SERVERNAME </code></pre> <p>Or you can use this, the second one you can use if you have multiple instances of SQl server running</p> <pre><code>SELECT serverproperty('MachineName'),serverproperty('Instancename') </code></pre>
Javascript String.replace(/\$/,str) works weirdly in jsp file <p>For simplicity, i have the following file named test.jsp:</p> <pre><code>&lt;script language="javascript"&gt; alert("a$b".replace(/\$/g,"k")); &lt;/script&gt; </code></pre> <p>I put this file in my local server, then display it using firefox: <a href="http://localhost:8080/myproj/test.jsp" rel="nofollow">http://localhost:8080/myproj/test.jsp</a>. It works okay, the result alert string is:</p> <pre><code> akb </code></pre> <p>But when i put this file in a remote server and use the same firefox to display, it output is: a$bk which is incorrect for me.</p> <p>Then i change the test.jsp content to:</p> <pre><code>&lt;script language="javascript"&gt; alert("a$b".replace(/\\$/g,"k")); &lt;/script&gt; </code></pre> <p>Note here i add two slashes instead of one. In this case it works in the remote server but not in local one.</p> <p>Then i rename the file from test.jsp to test.html, but the content is the same as my first case, i.e.:</p> <pre><code>&lt;script language="javascript"&gt; alert("a$b".replace(/\$/g,"k")); &lt;/script&gt; </code></pre> <p>By using the same firefox, it works okay in both servers.</p> <p>But my file needs to embed the javascript in jsp file. it is not allowed to use .html suffix for my file. What should I do to write a portable javascript in this scenario?</p> <p>My local server uses tomcat-5.5.26; remote server uses tomcat-5.0.28. Firefox version is 3.0.4.</p>
<p>JSP 2.0 Spec says: "When EL evaluation is disabled, \$ will not be recognized as a quote, whereas when EL evaluation is enabled, \$ will be recognized as a quote for $." (JSP.3.3.2)</p> <p>Whether EL Evaluation is enabled or disabled depends on many things:</p> <ul> <li>if application server supports JSP 2.0 (Tomcat 5.0 and higher does)</li> <li>web.xml descriptor file... if declares (e.g. by not using web-app_2_4.xsd schema) that it uses Servet 2.3 spec or earlier, EL is disabled by default.</li> <li>JSP Configuration &lt;el-ignored&gt;</li> <li>Page directive isELIgnored (<code>&lt;%@ page isELIgnored=”true|false” %></code>)</li> </ul> <p>(See <a href="http://jcp.org/aboutJava/communityprocess/final/jsr152/" rel="nofollow">JSP Spec 2.0</a>, part JSP.3.3.2 for more details)</p> <p>Simple way to check if EL is enabled/disabled is to use ${request} on your page. If you see '${request}' in output, EL is disabled. If you see something different, it is enabled.</p> <p>You may want to change <code>\$</code> (one backslash) to <code>\\$</code> (two backslashes) to get <code>\$</code> in output if you also use EL on your page.</p> <p>If you see differences between local/remote server, their settings related to EL probably differ. Best what you can do is to 1) use JSP 2.0, Servlet 2.4 or later (enables EL), 2) run same web server on machines. (Btw, I suggest you upgrade Tomcat 5.0 to 5.5 at least).</p>
How to pass an array size as a template with template type? <p>My compiler behaves oddly when I try to pass a fixed-size array to a template function. The code looks as follows:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; template &lt;typename TSize, TSize N&gt; void f(TSize (&amp; array)[N]) { std::copy(array, array + N, std::ostream_iterator&lt;TSize&gt;(std::cout, " ")); std::cout &lt;&lt; std::endl; } int main() { int x[] = { 1, 2, 3, 4, 5 }; unsigned int y[] = { 1, 2, 3, 4, 5 }; f(x); f(y); //line 15 (see the error message) } </code></pre> <p>It produces the following compile error in GCC 4.1.2:</p> <blockquote> <pre><code>test.cpp|15| error: size of array has non-integral type ‘TSize’ test.cpp|15| error: invalid initialization of reference of type ‘unsigned int (&amp;)[1]’ from expression of type ‘unsigned int [5]’ test.cpp|6| error: in passing argument 1 of ‘void f(TSize (&amp;)[N]) [with TSize = unsigned int, TSize N = ((TSize)5)]’ </code></pre> </blockquote> <p>Note that the first call compiles and succeeds. This seems to imply that while <code>int</code> is integral, <code>unsigned int</code> isn't.</p> <p>However, if I change the declaration of my above function template to</p> <pre><code>template &lt;typename TSize, unsigned int N&gt; void f(TSize (&amp; array)[N]) </code></pre> <p>the problem just goes away! Notice that the only change here is from <code>TSize N</code> to <code>unsigned int N</code>.</p> <p>Section [<code>dcl.type.simple</code>] in the final draft ISO/IEC FDIS 14882:1998 seems to imply that an "integral type" is either signed or unsigned:</p> <blockquote> <p>The <code>signed</code> specifier forces <code>char</code> objects and bit-fields to be signed; it is redundant with other integral types.</p> </blockquote> <p>Regarding fixed-size array declarations, the draft says [<code>dcl.array</code>]:</p> <blockquote> <p>If the <em>constant-expression</em> (<code>expr.const</code>) is present, it shall be an integral constant expression and its value shall be greater than zero.</p> </blockquote> <p>So why does my code work with an explicit <code>unsigned</code> size type, with an inferred <code>signed</code> size type but not with an inferred <code>unsigned</code> size type?</p> <p><strong>EDIT</strong> Serge wants to know where I'd need the first version. First, this code example is obviously simplified. My real code is a bit more elaborate. The array is actually an array of indices/offsets in another array. <del>So, logically, the type of the array should be the same as its size type for maximum correctness.</del> Otherwise, I might get a type mismatch (e.g. between <code>unsigned int</code> and <code>std::size_t</code>). Admittedly, this shouldn't be a problem in practice since the compiler implicitly converts to the larger of the two types.</p> <p><strong>EDIT 2</strong> I stand corrected (thanks, litb): size and offset are of course logically different types, and offsets into C arrays in particular are of type <code>std::ptrdiff_t</code>.</p>
<p>Hmm, the Standard says in <code>14.8.2.4 / 15</code>:</p> <blockquote> <p>If, in the declaration of a function template with a non-type template-parameter, the non-type template-parameter is used in an expression in the function parameter-list and, if the corresponding template-argument is deduced, the template-argument type shall match the type of the template-parameter exactly, <em>except that a template-argument deduced from an array bound may be of any integral type.</em></p> </blockquote> <p>Providing this example:</p> <pre><code>template&lt;int i&gt; class A { /* ... */ }; template&lt;short s&gt; void f(A&lt;s&gt;); void k1() { A&lt;1&gt; a; f(a); // error: deduction fails for conversion from int to short f&lt;1&gt;(a); // OK } </code></pre> <p>That suggests that the compilers that fail to compile your code (apparently GCC and Digital Mars) do it wrong. I tested the code with Comeau, and it compiles your code fine. I don't think there is a different to whether the type of the non-type template parameter depends on the type of the type-parameter or not. <code>14.8.2.4/2</code> says the template arguments should be deduced independent from each other, and then combined into the type of the function-parameter. Combined with /15, which allows the type of the dimension to be of different integral type, i think your code is all fine. As always, i take the c++-is-complicated-so-i-may-be-wrong card :) </p> <p><strong>Update</strong>: I've looked into the passage in GCC where it spits out that error message:</p> <pre><code> ... type = TREE_TYPE (size); /* The array bound must be an integer type. */ if (!dependent_type_p (type) &amp;&amp; !INTEGRAL_TYPE_P (type)) { if (name) error ("size of array %qD has non-integral type %qT", name, type); else error ("size of array has non-integral type %qT", type); size = integer_one_node; type = TREE_TYPE (size); } ... </code></pre> <p>It seems to have missed to mark the type of the size as dependent in an earlier code block. As that type is a template parameter, it is a dependent type (see <code>14.6.2.1</code>).</p> <p><strong>Update:</strong> GCC developers fixed it: <a href="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=38950">Bug #38950</a></p>
Interface to a webservice? <p>I have two webservices that have exactly the same methods and signatures but point at different servers (specifically the Virtual Earth production and staging environments). I wish to switch between using the production and staging services on the basis of a config setting and don't want to repeat myself and replicate each method where I call one of the services.</p> <p>So what I need in effect is to create an interface which both of the services can implement and program against that. But I don't know if this is advisable or even possible.</p> <p>Or do I just need to reference one of the services and switch the url property depending on whether I want to use the production or staging environment?</p>
<p>If I understand you right, you have ONE webservice which is deployed in production and staging environments. In this case the only thing you have to do is to switch between them via the Url property.</p>
How to change the Auto Growth size? MS SQL Server 2005 <p>In MS Sql server 2005, by default 1MB Auto Growth is there, How can i change it to whatever i need.?</p> <p>Thanx, Ambanna</p>
<p>In SQL Server Management Studio, right click on the database.<br /> Go to Properties.<br /> Then go to the Files section.<br /> Click on either the data or log autogrowth column (Click the ...)<br /> Then change it to whatever you want it to be. </p>
What could possibly cause JQuery's selector to break? <p>I am trying to get an element using JQuery's selector, but it does not find it even though the element actually exists. Moreover, I can actually find the element using getElementById.</p> <p>For example:</p> <p>$('#outputDiv') gives me a null value. But document.getElementById("outputDiv") returns me the Div I was trying to access.</p> <p>Any idea?</p>
<p>Check that jQuery is actually loaded. Have you tested with Firebug or another debugger? Are javascript errors reported? Do you use another library that uses $ as an alias?</p>
Use of GetGuiResources <p>Is it a good idea to use <code>GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS)</code> at the start of <code>WinMain</code>, and before the last return to detect GDI leaks or, more specifically, objects I forgot to release?<br/>Also I'm currently wondering why the first call in my program returns <code>4</code> when there's no window yet.</p>
<p>In most situations, it's enough to use <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="nofollow">process explorer</a>. Keep the window open showing the GDI handles of your process (right-click on the columns, choose "Select Columns" and then check the "GDI Objects" checkbox in the "Process Memory" tab).</p> <p>While running your application, watch the number of GDI handles - if it increases and never goes back, you know you have a leak.</p>
making a constant heading - css problem <p>I have an AJAX application which has used CSS divs to create panels on the screen, which are loaded separately and in succession, depending on what was loaded before it. The bottom "panel" is a table showing a list or records from a database. At the top of the database is the name of the table, and I would like a way to have it be always above the list of records. I am unsure of how to do this, if it is with Javascript, or PHP, or css and html.</p> <p>edit: I tried wrapping the table header in a div and setting the css for this purpose, but the table header does not seem to be in its own header and does not stay on screen separate from the records.</p> <pre><code>.tableheader { position: absolute; } </code></pre> <p>and</p> <pre><code>$table = 'AUCTIONS'; $rows = getRowsByArticleSearch($query, $table); echo '&lt;div id="tableheader" class="tableheader"&gt;'; echo "&lt;h1&gt;{$query} Auctions&lt;/h1&gt;" . "\n"; echo "&lt;/div&gt;"; </code></pre> <p>Have I missed something fundamental here?</p>
<p>I assume you mean to be able to scroll the table without moving the header?</p> <p>I think your easiest option is the CSS <a href="http://www.w3schools.com/Css/pr_pos_overflow.asp" rel="nofollow"><code>overflow</code> property</a>.</p> <pre><code>&lt;style type="text/css"&gt; div#dblist { overflow: scroll; height: 400px; } &lt;/style&gt; &lt;!-- ... --&gt; &lt;div&gt;Database Title&lt;/div&gt; &lt;div id="dblist"&gt; &lt;table&gt; &lt;!-- ... --&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p><hr /></p> <p>@Joshxtothe4: It sounds like you've got scrolling set to the wrong element:</p> <pre><code>&lt;div&gt; &lt;!-- sounds like you have it set here --&gt; &lt;div&gt;&lt;h1&gt;Query Archive&lt;/h1&gt;&lt;/div&gt; &lt;div&gt; &lt;!-- and want it set here --&gt; &lt;table&gt; &lt;!-- ... --&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>You shouldn't need absolute positioning for this.</p>
Testing for a deadlock with nUnit <p>I'm new to unit testing and nUnit (2.48). I'd like to write a test method where the failure case is that it deadlocks. Is this possible? Obviously nUnit doesn't know by default how long the method should take to execute, so would I have to write code to do the work on a separate thread and then abort it and throw and exception if it took longer than some time I define? Is there a better way to do this?</p> <p>Thank you</p>
<p>Well its certainly possible to test for a deadlock by running your code on another thread and seeing if it returns in a timely fashion. Here's some (very basic) example code:</p> <pre><code>[TestFixture] public class DeadlockTests { [Test] public void TestForDeadlock() { Thread thread = new Thread(ThreadFunction); thread.Start(); if (!thread.Join(5000)) { Assert.Fail("Deadlock detected"); } } private void ThreadFunction() { // do something that causes a deadlock here Thread.Sleep(10000); } } </code></pre> <p>I wouldn't like to say that this is the "best way", but it is one I have found useful on occasions.</p>
Does IL Merge work with .NET Compact Framework <p>Does anyone have experience using IL Merge and the .NET CF? Does IL Merge work with CF? Are there any known problems?</p>
<p>Yes, IL merge does support the Compact Framework platform. By default it will attempt to target the desktop CLR. You must pass the path to the Compact framework install to the /targetplatform parameter though. </p> <p>For Example</p> <p>ilmerge /t:winexe /targetplatform:v2,"C:\Program Files\Microsoft.NET\SDK\CompactFramework\v2.0\Debugger\BCL"</p> <p>This blog post has an excellent breakdown of this process:</p> <p><a href="http://blog.opennetcf.com/ncowburn/2007/01/30/UsingILMergeOnCompactFrameworkApplications.aspx" rel="nofollow">http://blog.opennetcf.com/ncowburn/2007/01/30/UsingILMergeOnCompactFrameworkApplications.aspx</a></p>
Should I avoid Alternative Control Syntax? <p>As a mostly self-taught programmer, I have never really had anyone explain why certain things should or should not be used. One example (which I picked up years ago and use quite often) is the alternative control structure syntax:</p> <pre><code>x = (y == true) ? "foo" : "bar"; </code></pre> <p>I personally find this syntax easy to follow, especially for short, concise code, but I don't see it get a lot of use "in the wild" so I'd like to know if it's bad practice to use this over a more traditional <em>if ... else</em> structure?</p> <p>Thanks in advance.</p>
<p>As a fellow mostly self-taught programmer, I can only give you my opinion, without any special authority behind it.</p> <p>I find that the ternary conditional operator (?:) is perfectly acceptable when you're using it for an expression with no side-effects. As soon as you start using it to represent a decision to do something vs. do something else, you're (in my opinion) abusing it.</p> <p>In short, control constructs are for structuring the flow of the code and operators are for expressions. As long as one keeps things that way, the code remains readable.</p>
How to unit test library that relies on Session object <p>I have several asp.net mvc websites consuming the same controller and model.<br /> This common logic is put in seperate libraries. These libraries use the HttpContext.Current.Session. How can I make these unit testable? I read about the StateValue but can't completely grasp it. Where should I get this StateValue thing? Is it a lib I reference?</p>
<p>You can use mock helpers such as seen <a href="http://dotnetslackers.com/articles/aspnet/ASPNETMVCFrameworkPart2.aspx" rel="nofollow">here</a></p>
In JQuery is there way for slideDown() method to scroll the page down too? <p>The slideDown applied to a div does the slideDown but doesn't scroll the page down and the div slided down div remains hidden from view. Is there a way to scroll the page down as well so the user can view the div?</p>
<p>Quick demo <a href="http://jsbin.com/agahi">here</a></p> <p>Basically all you need is</p> <pre><code> $('html, body').animate({ scrollTop: $('#yourDiv').offset().top }, 3000); </code></pre>
ASP.Net Membership.DeleteUser <p>In testing, the user on a db i've used was a big jefe. In production, he only has Execute.</p> <p>When I called,</p> <pre><code>Membership.DeleteUser(user) </code></pre> <p>In testing, it worked. I try the same in production, and I get this:</p> <blockquote> <p>The DELETE statement conflicted with the REFERENCE constraint "FK__aspnet_Us__UserI__37703C52". The conflict occurred in database "Testing", table "dbo.aspnet_UsersInRoles", column 'UserId'.</p> </blockquote> <p>In my seargles (searches on Google), I came across this <a href="http://www.dougdossett.com/Details.aspx?Detail=35" rel="nofollow">link</a> where the dude was saying, </p> <blockquote> <p>Error: The DELETE statement conflicted with the REFERENCE constraint "FK__aspnet_Me__UserI__15502E78". The conflict occurred in database "YourDBName", table "dbo.aspnet_Membership", column 'UserId'.</p> <p>Took me a while to find a solution to this across multiple sites and options as the error and possible solutions were rather misleading. Turns out, at least in my case, it was a problem with permissions on the membership database. The user I'm using to connect had access to view the membership details within the database itself, but as part of the aspnet_Users_DeleteUser stored procedure it selects from the sysobjects table. The membership connection user apparently did not have sufficient rights to do that select so the overall delete failed. </p> <p>The fix for me was to add the user to the aspnet_Membership_FullAccess role for the membership database.</p> </blockquote> <p>But when I did that it didn't work. Anyone have any ideas on how to deal with this?</p>
<p>After a little inspection I found the issue is this line in the aspnet_Users_DeleteUser stored procedure:</p> <pre><code>IF ((@TablesToDeleteFrom &amp; 1) &lt;&gt; 0 AND (EXISTS (SELECT name FROM sysobjects WHERE (name = N'vw_aspnet_MembershipUsers') AND (type = 'V')))) </code></pre> <p>There are 3 other similar lines for 3 other tables. The issue is that if the user executing the stored proc doesn't have access to vw_aspnet_MembershipUsers it won't turn up when selecting from sysobjects. I'm curious to know why that whole EXISTS statement is necessary.</p> <p>Regardless, the following discussion, "<a href="http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.sqlserver.security&amp;tid=f6f57505-7e3f-4a95-97bf-38cb6d86780e&amp;cat=en_US_a36f2156-9287-4116-9521-b0c8ee543ba8&amp;lang=en&amp;cr=US&amp;sloc=&amp;p=1">Access to sysobjects to view user tables without having access to the user tables directly in SQL Server Security</a>", has the answer. By granting "VIEW DEFINITION" on the views in question, the EXISTS statements will now succeed and you don't have to grant unneeded, unwanted, or excessive permissions to the user in your application's connection string.</p>
How can I set the focus of a ListBox in XAML? <p>I have this ListBox:</p> <pre><code>&lt;ListBox Name="lbColor"&gt; &lt;ListBoxItem Content="Blue"/&gt; &lt;ListBoxItem Content="Red"/&gt; &lt;ListBoxItem Content="Orange"/&gt; &lt;/ListBox&gt; </code></pre> <p>This code pre-selects the choice alright, but doesn't set the focus, how can I do that?</p> <pre><code>public Window1() { InitializeComponent(); lbColor.SelectedIndex = 1; lbColor.Focus = 1; } </code></pre>
<p>You can use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.uielement.focus.aspx" rel="nofollow">Focus</a> method:</p> <pre><code>public Window1() { InitializeComponent(); lbColor.SelectedIndex = 1; lbColor.Focus(); } </code></pre>
Partial Classes, LINQ, Interfaces and VB.NET <p>Okay, I have ran in to a problem with VB.NET. So all those defenders of VB.NET please can you help me out? Here is my issue: I am using LINQ to Entities, it also works with LINQ to SQL, I build my edmx file I then create a Partial Publc Class of the same name as one of the entities All fine up to now, so here comes the problem. </p> <p>I need the Partial class to implement an Interface Implements Interfaces.IAsset But VB.NET want to place "Implements Interfaces.IAsset.ID" at the end of the property, which of course is in the generated code section of the Partial class, which I can not do as the edmx file is auto generated and will change in the future. </p> <p>Here is the line of code that needs sorting: </p> <p>Public Property ID1() As Integer Implements Interfaces.IAsset.ID </p> <p>In C# it is fine and works wonders. So why can't VB.NET implement an interface that is in the code generated class?</p>
<p>A little bit of indirection in the partial class should do the trick...</p> <pre><code>Public Property AssetId() As Int32 Implements IAsset.AssetId Get Return Id1 End Get Set(ByVal value As Int32) Id1 = value End Set End Property </code></pre> <p>The property that implements the interface calls the actual property generated by the dbml. The class will essentially have two id properties, which is not very elegant but when accessed through the interface you won't know the difference.</p>
SORTING Hierarchical Queries in SQL Server 2005 <p>I have following issue: I have a table for maintaining the hierarchical data. I'd like to use CTE from SQL 2005.</p> <pre><code>WITH tree (id, parentid, code, name) AS ( SELECT id, ofs.ParentID, ofs.code, ofs.name FROM OrganizationFeatures ofs WHERE ofs.ParentID IS NULL UNION ALL SELECT ofs.id, ofs.ParentID, ofs.code, ofs.name FROM OrganizationFeatures ofs JOIN tree ON tree.ID = ofs.ParentID ) select * from tree </code></pre> <p>But I'd like to sort by code and the result shold be as following:</p> <pre><code>1 1/1 1/1/1 1/1/2 1/2/1 1/2/2 2 4/1 </code></pre> <p>etc. Any ideas? </p>
<p>To get the concatenated values, you need to do it in the with.</p> <p>To sort, you need to add an order by in the last select.</p> <pre><code>WITH tree (id, parentid, code, name) AS ( SELECT id, ofs.ParentID, ofs.code, ofs.name FROM OrganizationFeatures ofs WHERE ofs.ParentID IS NULL UNION ALL SELECT ofs.id, ofs.ParentID, tree.code+'/'+ofs.code, ofs.name FROM OrganizationFeatures ofs JOIN tree ON tree.ID = ofs.ParentID ) select * from tree order by code </code></pre> <p>Also, if code is not a varchar, you will have to convert the code columns in this bit of code (<code>tree.code+'/'+ofs.code</code>) for it to work.</p>
How to transfer databases and site contents <p>I own a website with 20 GB data on it Now I decided to change the Hosting compnay . I'm Moving to Russian VPS so is there a way to transfer the contents of my website to the Russian VPS without uploading them again .</p> <p>Is there a service that does this. I heard that there is a way to do this using shell access (BUT what is shell access and how it works) thanx in advance guys</p>
<p>You can log in to one of your old host using an SSH connection, then connect from there to your new host, again using an SSH connection, and then upload all files from your first server to the second. For databases, do a data dump on your first server, and through the SSH connection, run the data dump against a database on your new server.</p> <p>Depending on the hosts, how you connect via SSH will differ, but there should be instruction available from the providers. If you can't find the directions, just e-mail the provider's support and ask.</p>
Ruby string mutability <p>This may be a bit of a nooby question, I have been trying to get better at ruby recently, and started reading the fantastic <a href="http://oreilly.com/catalog/9780596516178/">The Ruby Programming Language</a>. Something that was mentioned is that string literals are considered mutable, so in a loop it is better to use a variable then a literal, as a new string will get instantiated at every iteration.</p> <p>My question is why? At first I thought it was because of interpolation, but symbols are immutable and they support interpolation. Coming from a static background, it doesn't really make much sense to me.</p> <p>EDIT:</p> <p>After reading <a href="http://stackoverflow.com/users/210/thenduks">thenduks</a> answer, I think I may have it. AFAIK, languages like Java or C# don't have destructive string methods (they use upcase, but not upcase!). Because of things like upcase! or &lt;&lt;, the literal cannot be immutable.</p> <p>Not 100% sure on that, the other possibility is that it is a compile-time interning that happens, which is something that just doesn't happen in a scripting language.</p>
<p>Not really sure what exactly your question is, but consider the following code:</p> <pre><code>10.times { puts "abc".object_id } </code></pre> <p>This prints out 10 different id's. Why? Just because you know this string wont change doesn't mean Ruby does. If you think that <code>"abc"</code> should only be created once then what happens if you do:</p> <pre><code>10.times { puts "abc".upcase! } </code></pre> <p>The <code>upcase!</code> method mutates the string to be upper case, on the next iteration the string created in the first iteration isn't the same anymore.</p> <p>Perhaps post a code example that is confusing to you?</p>
ASP.NET TempData persists between requests <p>I am using temp data as follow in my controllers - very simple, when there is a problem:</p> <pre><code>TempData("StatusMessage") = "You have no items set to Auto-Ship." </code></pre> <p>Then on every page I have a user control as follows:</p> <pre><code>&lt;div class="error-container"&gt; &lt;% If TempData.ContainsKey("ErrorMessage") Then%&gt; &lt;script&gt; $('div.error-container').show();&lt;/script&gt; &lt;div class="msg-error"&gt;&lt;p&gt;&lt;%=TempData("ErrorMessage") %&gt;&lt;/p&gt;&lt;/div&gt; &lt;% End If%&gt; &lt;% If TempData.ContainsKey("StatusMessage") Then%&gt; &lt;script&gt; $('div.error-container').show();&lt;/script&gt; &lt;div class="msg-status"&gt;&lt;p&gt;&lt;%=TempData("StatusMessage")%&gt;&lt;/p&gt;&lt;/div&gt; &lt;% End If%&gt; &lt;ul&gt;&lt;/ul&gt; &lt;/div&gt; </code></pre> <p>Problem is when I do have an error added to tempdata it shows up properly on the first request but ALSO shows up again on the next request as well - which is obviously very confusing and not a desired behavior.</p> <p>I am not using any IoC, I did see the post with the same problems when using that.</p>
<p>The <em>sole purpose</em> of TempData is to persist until the next request. Stuff you do not want to persist until the next request should go into ViewData, instead.</p> <p>Realistically, this means that TempData is only safe to use when redirecting. When not redirecting, the "next request" could be anything.</p>
Correct way to use Actions to create menus, toolbars, and other components in Java <p>The naive way of writing building a menu in a Java Swing app is to do something like:</p> <pre><code>JMenu fileMenu = new JMenu("File"); JMenuItem openItem = new JMenuItem("Open..."); openItem.addActionListener(new ActionListener() { /* action listener stuff */ } ) fileMenu.addMenuItem(openItem); </code></pre> <p>A more experienced developer will recognize that actions can be accessed through a variety of mechanisms - menus, toolbar buttons, maybe even other workflows in the system. That person is more likely to write:</p> <pre><code>Action openAction = new AbstractAction(); openAction.setName("Open..."); openAction.addActionListener(new ActionListener() { /* action listener stuff */ } ) ... JMenuItem openItem = new JMenuItem(openAction); </code></pre> <p>My question is, <b>what is the best way to manage these Action objects so they can be used across menus, toolbars, etc?</b> </p> <ul> <li>Create a factory class that returns specific actions? </li> <li>Declare all of the actions as <code>private static final Action</code> in some utility class? </li> <li>Take advantage of a Java application framework? </li> <li>Something else?</li> </ul>
<p>Applications that I have developed that need to use that same actions across menus, toolbars, and other buttons have been done using Swing Application Framework.</p> <p><a href="https://appframework.dev.java.net/" rel="nofollow">Swing Application Framework</a></p> <p>This framework will allow you to have a resource file where you can define all menu text, tooltips, and ICONS. I think the icons are the key, you do not have to load them yourself. Also, if you have any actions that you need to enable/disable you can override the method to control its state. </p> <p>The website is worth the read.</p>
Possible to Geo-tag Photos using iPhone ImagePicker? <p>When calling the ImagePicker to take a picture the user is not prompted to allow their location to be used to geo-tag the photo as with the native Camera app. Is it possible to turn on or build geo-tagging into the ImagePicker?</p>
<p>Well, you could simply get the photo via the ImagePicker, then prompt the user to approve getting their location (something you have to do anyway) and then store both image and location in your own object.</p> <p>I don't believe the Picker by itself embeds lat/long in the image. That's likely something happening elsewhere in the Camera app.</p> <p>You could check using this lib though:</p> <p><a href="http://code.google.com/p/iphone-exif/downloads/list" rel="nofollow">http://code.google.com/p/iphone-exif/downloads/list</a></p> <p>Good Luck!</p>
Export Excel range/sheet to formatted text file <p>I have been tasked with creating a reusable process for our Finance Dept to upload our payroll to the State(WI) for reporting. I need to create something that takes a sheet or range in Excel and creates a specifically formatted text file.</p> <p><strong><em>THE FORMAT</em></strong></p> <ul> <li>Column 1 - A Static Number, never changes, position 1-10</li> <li>Column 2 - A Dynamic Param filled at runtime for Quarter/Year, position 11-13</li> <li>Column 3 - SSN, no hyphens or spaces, filled from column A, position 14-22</li> <li>Column 4 - Last Name, filled from column B, Truncated at 10, Left Justify &amp; fill with blanks, position 23-32</li> <li>Column 5 - First Name, filled from C, Truncate at 8, Left Justify &amp; fill with blanks, position 33-40</li> <li>Column 6 - Total Gross Wages/Quarter, filled from D, strip all formatting, Right Justify Zero Fill, position 41-49</li> <li>Column 7 - A Static Code, never changes, position 50-51</li> <li>Column 8 - BLANKS, Fill with blanks, position 52-80</li> </ul> <p>I have, I assume, 3 options:</p> <ol> <li>VBA</li> <li>.NET</li> <li>SQL</li> </ol> <p>I had explored the .NET method first but I just couldn't find decent documentation to get me going. I still like this one but I digress.</p> <p>Next I have some VBA that will dump a Sheet to a fixed width Text. I am currently pursuing this which leads, finally, to my actual question.</p> <p>How do I transform a Range of text in Excel? Do I need to coy it over to another sheet and then pass over that data with the neccesarry formatting functions the run my Dump to text routine? I currently had planned to have a function for each column but I am having trouble figuring out how to take the next step. I am fairly new at Office programming and developing in general so any insight will be greatly appreciated.</p> <p>The SQL option would be my fall back as I have done similar exports from SQL in the past. I just prefer the other two on the, <em>"I don't want to be responsible for running this,"</em> principle.</p> <p>Thanks in advance for any time given.</p>
<p>Using VBA seems like the way to go to me. This lets you write a macro that takes care of all of the various formatting options and should, hopefully, be simple enough for your finance people to run themselves.</p> <p>You said you need something that takes a sheet or range in Excel. The first column never changes so we can store that in the macro, columns 3-7 come from the spreadsheet and column 8 is just blank. That leaves column 2 (the quarter/year as QYY) as an issue. If the quarter/year is specified somewhere in the workbook (e.g. stored in a cell, as a worksheet name, as part of the workbook title) then we can just read it in. Otherwise you will need to find some method for specifying the quarter/year when the macro runs (e.g. pop up a dialog box and ask the user to input it)</p> <p>Some simple code (we'll worry about how to call this later):</p> <pre><code>Sub ProduceStatePayrollReportFile(rngPayrollData As Range, strCompanyNo As String, _ strQuarterYear As String, strRecordCode As String, strOutputFile As String) </code></pre> <p>The parameters are fairly obvious: the range that holds the data, the company number for column 1, the quarter/year for column 2, the fixed code for column 7 and the file we want to output the results to</p> <pre><code>' Store the file handle for the output file Dim fnOutPayrollReport As Integer ' Store each line of the output file Dim strPayrollReportLine As String ' Use to work through each row in the range Dim indexRow As Integer </code></pre> <p>To output to a file in VBA we need to get a file handle so we need a variable to store that in. We'll build up each line of the report in the report line string and use the row index to work through the range</p> <pre><code>' Store the raw SSN, last name, first name and wages data Dim strRawSSN As String Dim strRawLastName As String Dim strRawFirstName As String Dim strRawWages As String Dim currencyRawWages As Currency ' Store the corrected SSN, last name, first name and wages data Dim strCleanSSN As String Dim strCleanLastName As String Dim strCleanFirstName As String Dim strCleanWages As String </code></pre> <p>These sets of variables store the raw data from the worksheet and the cleaned data to be output to the file respectively. Naming them "raw" and "clean" makes it easier to spot errors where you accidentally output raw data instead of cleaned data. We will need to change the raw wages from a string value to a numeric value to help with the formatting</p> <pre><code>' Open up the output file fnOutPayrollReport = FreeFile() Open strOutputFile For Output As #fnOutPayrollReport </code></pre> <p>FreeFile() gets the next available file handle and we use that to link to the file</p> <pre><code>' Work through each row in the range For indexRow = 1 To rngPayrollData.Rows.Count ' Reset the output report line to be empty strPayrollReportLine = "" ' Add the company number to the report line (assumption: already correctly formatted) strPayrollReportLine = strPayrollReportLine &amp; strCompanyNo ' Add in the quarter/year (assumption: already correctly formatted) strPayrollReportLine = strPayrollReportLine &amp; strQuarterYear </code></pre> <p>In our loop to work through each row, we start by clearing out the output string and then adding in the values for columns 1 and 2</p> <pre><code>' Get the raw SSN data, clean it and append to the report line strRawSSN = rngPayrollData.Cells(indexRow, 1) strCleanSSN = cleanFromRawSSN(strRawSSN) strPayrollReportLine = strPayrollReportLine &amp; strCleanSSN </code></pre> <p>The <code>.Cells(indexRow, 1)</code> part just means the left-most column of the range at the row specified by indexRow. If the ranges starts in column A (which does not have to be the case) then this just means A. We'll need to write the <code>cleanFromRawSSN</code> function ourselves later</p> <pre><code>' Get the raw last and first names, clean them and append them strRawLastName = rngPayrollData.Cells(indexRow, 2) strCleanLastName = Format(Left$(strRawLastName, 10), "!@@@@@@@@@@") strPayrollReportLine = strPayrollReportLine &amp; strCleanLastName strRawFirstName = rngPayrollData.Cells(indexRow, 3) strCleanFirstName = Format(Left$(strRawFirstName, 8), "!@@@@@@@@") strPayrollReportLine = strPayrollReportLine &amp; strCleanFirstName </code></pre> <p><code>Left$(string, length)</code> truncates the string to the given length. The format picture <code>!@@@@@@@@@@</code> formats a string as exactly ten characters long, left justified (the ! signifies left justify) and padded with spaces</p> <pre><code>' Read in the wages data, convert to numeric data, lose the decimal, clean it and append it strRawWages = rngPayrollData.Cells(indexRow, 4) currencyRawWages = CCur(strRawWages) currencyRawWages = currencyRawWages * 100 strCleanWages = Format(currencyRawWages, "000000000") strPayrollReportLine = strPayrollReportLine &amp; strCleanWages </code></pre> <p>We convert it to currency so that we can multiply by 100 to move the cents value to the left of the decimal point. This makes it much easier to use <code>Format</code> to generate the correct value. This will not produce correct output for wages >= $10 million but that's a limitation of the file format used for reporting. The <code>0</code> in the format picture pads with 0s surprisingly enough</p> <pre><code>' Append the fixed code for column 7 and the spaces for column 8 strPayrollReportLine = strPayrollReportLine &amp; strRecordCode strPayrollReportLine = strPayrollReportLine &amp; CStr(String(29, " ")) ' Output the line to the file Print #fnOutPayrollReport, strPayrollReportLine </code></pre> <p>The <code>String(number, char)</code> function produces a Variant with a sequence of <code>number</code> of the specified <code>char</code>. <code>CStr</code> turns the Variant into a string. The <code>Print #</code> statement outputs to the file without any additional formatting</p> <pre><code>Next indexRow ' Close the file Close #fnOutPayrollReport End Sub </code></pre> <p>Loop round to the next row in the range and repeat. When we have processed all of the rows, close the file and end the macro</p> <p>We still need two things: a cleanFromRawSSN function and a way to call the macro with the relevant data.</p> <pre><code>Function cleanFromRawSSN(strRawSSN As String) As String ' Used to index the raw SSN so we can process it one character at a time Dim indexRawChar As Integer ' Set the return string to be empty cleanFromRawSSN = "" ' Loop through the raw data and extract the correct characters For indexRawChar = 1 To Len(strRawSSN) ' Check for hyphen If (Mid$(strRawSSN, indexRawChar, 1) = "-") Then ' do nothing ' Check for space ElseIf (Mid$(strRawSSN, indexRawChar, 1) = " ") Then ' do nothing Else ' Output character cleanFromRawSSN = cleanFromRawSSN &amp; Mid$(strRawSSN, indexRawChar, 1) End If Next indexRawChar ' Check for correct length and return empty string if incorrect If (Len(cleanFromRawSSN) &lt;&gt; 9) Then cleanFromRawSSN = "" End If End Function </code></pre> <p><code>Len</code> returns the length of a string and <code>Mid$(string, start, length)</code> returns <code>length</code> characters from <code>string</code> beginning at <code>start</code>. This function could be improved as it doesn't currently check for non-numeric data</p> <p>To call the macro:</p> <pre><code>Sub CallPayrollReport() ProduceStatePayrollReportFile Application.Selection, "1234560007", "109", "01", "C:\payroll109.txt" End Sub </code></pre> <p>This is the simplest way to call it. The Range is whatever the user has selected on the active worksheet in the active workbook and the other values are hard-coded. The user should select the range they want to output to the file then go Tools > Macro > Run and choose <code>CallPayrollReport</code>. For this to work, the macro would either need to be part of the workbook containg the data or in a different workbook which had been loaded before the user calls the macro.</p> <p>Someone would need to change the hard-coded value of the quarter/year before each quarter's report was generated. As stated earlier, if the quarter/year is already stored in the workbook somewhere then it's better to read that in rather than hard-coding it</p> <p>Hope that makes sense and is of some use</p>
How do you create a daemon in Python? <p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However, <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">another code sample</a>, whilst not containing so much documentation, includes sample code for passing commands such as start, stop and restart. It also creates a PID file which can be handy for checking if the daemon is already running etc.</p> <p>These samples both explain how to create the daemon. Are there any additional things that need to be considered? Is one sample better than the other, and why?</p>
<p>There are <strong>many fiddly things</strong> to take care of when becoming a <a href="http://www.python.org/dev/peps/pep-3143/#correct-daemon-behaviour">well-behaved daemon process</a>:</p> <ul> <li><p>prevent core dumps (many daemons run as root, and core dumps can contain sensitive information)</p></li> <li><p>behave correctly inside a <code>chroot</code> gaol</p></li> <li><p>set UID, GID, working directory, umask, and other process parameters appropriately for the use case</p></li> <li><p>relinquish elevated <code>suid</code>, <code>sgid</code> privileges</p></li> <li><p>close all open file descriptors, with exclusions depending on the use case</p></li> <li><p>behave correctly if started inside an already-detached context, such as <code>init</code>, <code>inetd</code>, etc.</p></li> <li><p>set up signal handlers for sensible daemon behaviour, but also with specific handlers determined by the use case</p></li> <li><p>redirect the standard streams <code>stdin</code>, <code>stdout</code>, <code>stderr</code> since a daemon process no longer has a controlling terminal</p></li> <li><p>handle a PID file as a cooperative advisory lock, which is a whole can of worms in itself with many contradictory but valid ways to behave</p></li> <li><p>allow proper cleanup when the process is terminated</p></li> <li><p>actually become a daemon process without leading to zombies</p></li> </ul> <p>Some of these are <strong>standard</strong>, as described in canonical Unix literature (<em>Advanced Programming in the UNIX Environment</em>, by the late W. Richard Stevens, Addison-Wesley, 1992). Others, such as stream redirection and <a href="http://stackoverflow.com/questions/688343/reference-for-proper-handling-of-pid-file-on-unix">PID file handling</a>, are <strong>conventional behaviour</strong> most daemon users would expect but that are less standardised.</p> <p>All of these are covered by the <strong><a href="http://www.python.org/dev/peps/pep-3143">PEP 3143</a> “Standard daemon process library” specification</strong>. The <a href="http://pypi.python.org/pypi/python-daemon/">python-daemon</a> reference implementation works on Python 2.7 or later, and Python 3.2 or later.</p>
How to Select Cell Based from Macro <p>This should be simple, not sure why I am having trouble with this..... In a data input range that a user is entering data there is a "left" and a "right" side of the form. Not all the data in any given row has to be filled in. I want to create a macro (and assign it to a hot key I.E. ctrl-z ) such that if it is hit it will position the active cell to be in the current row and in column "X". in other words hitting the ctrl-Z will cause the cursor to jump to column "X" </p>
<p>In this case column "x" is actually column E:</p> <pre><code>Sub ToColE() Const colE = 5 Dim offset As Integer offset = colE - ActiveCell.Column ActiveCell.offset(rowOffset:=0, columnOffset:=offset).Activate End Sub </code></pre>
Why is the destructor ignored in this code? <p>The following code demonstrates a weird problem I have in a Turbo C++ Explorer project. One of the three stack objects in D::D() is not destroyed after going out of scope. </p> <p>This only happens if compiled in release mode, the auto_ptrs a_ and b_ are of different types and the exception thrown doesn't inherit from std::exception. It appears to work just fine in VC++ 2005 and C++ Builder 2009. I did install the BDS2006 Update 2, the hotfix rollup and hotfix 12.</p> <p>Is it my code or the compiler? Do you know of a fix? Not being able to reliably use auto_ptr in a VCL project would be quite inconvenient. </p> <p><br></p> <pre><code>#include &lt;memory&gt; #include &lt;stdexcept&gt; #include &lt;iostream&gt; typedef std::exception my_error; // will work fine if replaced with line below //class my_error : public std::exception {}; class A {}; class B {}; class C { public: C(int id) : id_(id) { std::cout &lt;&lt; "C::C() " &lt;&lt; id_ &lt;&lt; std::endl; }; ~C() { std::cout &lt;&lt; "C::~C() " &lt;&lt; id_ &lt;&lt; std::endl; }; private: int id_; }; class D { public: D() { C c1(1); C c2(2); C c3(3); throw my_error(); }; private: std::auto_ptr&lt;A&gt; a_; std::auto_ptr&lt;B&gt; b_; // will work fine if replaced with line below // std::auto_ptr&lt;A&gt; b_; // std::auto_ptr&lt;C&gt; c_; // see expected output }; #pragma argsused int main(int argc, char* argv[]) { try { D d; } catch (...) { std::cout &lt;&lt; "caught exception" &lt;&lt; std::endl; } return 0; } </code></pre> <p><br> Expected:</p> <pre> C::C() 1 C::C() 2 C::C() 3 C::~C() 3 C::~C() 2 C::~C() 1 caught exception </pre> <p><br> Got:</p> <pre> C::C() 1 C::C() 2 C::C() 3 C::~C() 2 C::~C() 1 caught exception </pre> <p><br> Got (with line '<code>// std::auto_ptr&lt;C&gt; c_;</code>' uncommented):</p> <pre> C::C() 1 C::C() 2 C::C() 3 C::~C() 1 caught exception </pre> <p><br> <strong>Edit:</strong> Made suggested changes <br><br> <strong>Edit 2:</strong><br> I just tested it with C++ Builder 2007 (11.0.2902.10471), which shows the same problem. The release configuration works as soon as I check the "Debug information" box in Project -> Options -> C++ Compiler -> Debugging. It surprises me that the executable gets smaller with "Debug information" enabled (down to 31.5 KB from 39.5 KB ). <br><br> <strong>Edit 3:</strong><br> In Turbo C++ Explorer (C++ Builder 2006) (10.0.2288.42451) the release configuration works if I uncheck the "Inline function expansion (-vi)" box in Project -> Options -> C++ Compiler -> Debugging. Replacing the first line (<code>#include &lt;memory&gt;</code>) with the following code makes it work, too. </p> <pre><code>#pragma option push -vi- #include &lt;memory&gt; #pragma option pop </code></pre>
<p>This appears to be a compiler bug. I just ran the same sample in VS2008SP1 and got the expected output. </p>
Tool for diagnosing memory leaks in .NET (ASP.NET Application) <p>we need a tool to detect easily memory leaks in an ASP.NET Application. We have an application, which consumes lot of memory.</p> <p>Thanks</p>
<p>Using <a href="http://www.microsoft.com/whdc/devtools/debugging/default.mspx" rel="nofollow">WinDbg</a> is not as easy as using dotTrace but it can help you to discover lots of oddities in your application. Other than that you can find invaluable information about debugging ASP.Net applications on Tess Ferrandez's <a href="http://blogs.msdn.com/tess/" rel="nofollow">blog</a>.</p>
Replicating C++'s RAII in C# <p>I'm rolling my own logger class, and want to represent the heirarchy of logs as the app moves through different phases:</p> <pre><code>log start loading loaded 400 values processing couldn't process var "x" </code></pre> <p>etc.</p> <p>In C++ (yes I know), I'd use RAII classlets that pushed themselves on the log stack when created, and popped off when they left the scope. You could then leave functions at any point and still have consistent logging.</p> <p>Obviously in C# any variable has to be new'd, so it wouldn't be deleted until the next garbage collection cycle, and if you immediately create a new classlet, you could have an out-of-sync logger.</p> <p>How would people try to solve this problem in C#? I want the logger syntax to be as unobtrusive to the current function as possible, and still support functions with multiple exit points. </p> <p>The only solution I can think of off the top of my head involves closeHeirarchy() calls every return statement - and you know I'm going to miss one somewhere.</p> <hr> <p>Edit: I should make it clear I'm interested mainly in how you would replicate the RAII behaviour in c#. Is there a mechanism that provides identical behaviour?</p>
<p>You can get the behavior you are asking about if you use the <a href="http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx" rel="nofollow">using</a> statement with an IDisposable-class.</p> <p>Do something like this:</p> <pre><code>public class LogContext: IDisposable { private readonly Logger _logger; private readonly string _context; public LogContext(Logger logger, string context){ _logger = logger; _context = context; _logger.EnterContext(_context); } public void Dispose(){ _logger.LeaveContext(_context); } } //... public void Load(){ using(new LogContext(logger, "Loading")){ // perform load } } </code></pre>
Route files with vbscript from a .net handler back to asp.dll <p>We are migrating from asp classic to .net. Unfortunately they named all of the .asp files as .aspx so that they wouldn't lose page rank when they moved to .net. This means that IIS maps all .aspx files to asp.dll.</p> <p>After changing the mapping back I was going to try have a handler grab the request then check if there is any vbscript in the file and then hand it back to asp.dll if it otherwise proceed to handle the request normally.</p> <p>We are using IIS7.</p> <p>I think it may be possible to use a ISAPI filter to this too, but then i would have to learn how to make an ISAPI filter for IIS7 (which is fine if there isn't a way to this in .net)</p> <p>Ideas? Thanks!!</p>
<p>IMHO you would be better off to use the ATL Server support libraries and make an ISAPI filter.See: <a href="http://msdn.microsoft.com/en-us/library/2chz4bx6" rel="nofollow">http://msdn.microsoft.com/en-us/library/2chz4bx6</a>(VS.80).aspx</p> <p>Plus you really don't want to hit the aspnet_isapi.dll unless you know you need ASP.NET processing; why incur the hit?</p> <p>Although I may not understand your question correctly... Are you mixing classic ASP and ASP.NET in the same application? If you have to share session state between the two this can be rather challenging...</p>
Using Apache proxy to foward traffic to tinyproxy <p>I need to find a way to proxy some traffic on port 80 to tinyproxy running on a separate port. We have a client working behind a very strict firewall with only port 80 open (and cannot get to sites like meebo.com, etc). I was hoping I could create a CNAME to our domain and a virtual host on apache, catch the request for that new CNAME and forward the traffic right to tinyproxy running on the same box. </p> <p>I know tinyproxy is setup and working correctly, however, when I try to pass in my traffic through Apache, I don't even see any traffic. </p> <p>Does anyone have a proposed solution? Here is my VirtualHost entry:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerName sub.domain.com ProxyPass / http://127.0.0.1:50001/ ProxyPassReverse / http://127.0.0.1:50001/ &lt;/VirtualHost&gt; </code></pre> <p>where Tinyproxy is running on port 50001.</p>
<p>I don't think it's going to be possible.</p> <p>ProxyPass is for opaque proxying of web-servers - not redirecting to a proxy. But it might have worked except that AFAIK VirtualHost can only be identified by the Host: header in the http request - so only works for the real request.</p> <p>In other words - the clients will set a Host: header for the site they want to reach, so your virtualHost is never used.</p>
.NET Library to access the COM Port? <p>Is there a library that would allow me to send and receive data on a Serial COM port?</p>
<p>See <a href="http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx" rel="nofollow"><code>System.IO.Ports</code></a></p>
How to force ADO.NET Entity Framework to regenerate code? <p>I've run into a snag with a ADO.NET Entity Framework model and a ADO.NET Data Service that is making it available. The model and data service are compiling without any problems or warnings when they come out of source control. However when I run the service I get the following error: <img src="http://i42.tinypic.com/5lds8p.jpg" alt="Request Error - The server encountered an error processing the request. See server logs for more details." /></p> <p>Unfortunately there are no server logs (that I am aware of) since this is VS 2008 web dev server and there really isn't any code to debug..... Through some trial and error it would appear that the generated code (model.Designer.cs) is out of date in some manner. If I perform some trivial update to the EDM that forces it to regenerate the code file, when I rerun the service it works just fine.</p> <p>I've tried to delete the model.designer.cs file in the hopes that during the build the project/entity builder would detect the missing file and regenerate it for me. That didn't happen..... Does anyone know how to force this code to be regenerated? (It would also make me a bit happier about not having to keep generated code under source control.)</p> <p>Thanks</p>
<p>Right click on the EDMX file and select Run Custom Tool.</p> <p>There is also a command line code generation tool called <em>edmgen</em> (available from a VS Command Prompt).</p>
Should MVC Controller be in separate DLL? <p>I've created a .NET winforms MVC. The Controller and View are in the same EXE. Model is in a set of DLLs that get used by several groups. The MVC is very explicit. Model knows nothing of Controller and Controller knows nothing of View. I'm thinking to put the Controller in its own DLL so that it can be unit tested. Highly unlike someone will reuse the controller. Unit testing is the only reason <em>I have</em> for the move into a DLL.</p> <p>Conceptually, should the controller always be in the same assembly as the View? What are reasons for/against keeping them together?</p>
<p>Separation of controllers and views are an abstract concept. There's no strict rule that you should physically keep them separate (just like tiers in a three-tier application). However there might be some advantages in either approach.</p> <p>Separating assemblies has the following benefits:</p> <ul> <li>Reduces the possibility to accidentally couple views to controllers and breaking the separation.</li> <li>Makes it easier to edit views without recompiling controllers at all (which is great from a deployment perspective).</li> <li>Building views and controllers become separated, so you can test the one of them even if the other does not build at all.</li> </ul> <p>However, it might be unfeasible for small projects. For very small projects you might want to ship a single executable and nothing else along it. Also, you might not want to create 3 separate projects. </p> <p>Hey, you might not wanna unit test it at all ;) Ouch, my head is hurt, where did this big brick come from? :))</p>
What's the best way to trim whitespace from a string in Cocoa Touch? <p>I'm looking to determine whether a string value from a user input (UITextField) is "blank" if it's not nil. Checking if <code>[textField.text isEqualToString:""]</code> isn't quite enough because I want to avoid any blank/whitespace input (like say a few space characters).</p> <p>There does seem to be an indication of a good solution for my particular problem <a href="http://stackoverflow.com/questions/422242/simple-string-parsing-in-cocoa-objective-c-parsing-a-command-line-into-command">in this StOv post</a>.</p> <p>Basically it goes something like this, but I suspect there has to (or ought to) be a better way:</p> <pre><code>NSString *strResult; NSScanner* scanner = [NSScanner scannerWithString:textField.text]; BOOL hasValidChars = [scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet] intoString:&amp;strResult]; // if hasValidChars == YES, we've got nonwhite space chars collected into strResult </code></pre> <p>This clearly only works for my particular circumstance, and even then it would fail if the first character was a space but the data I wanted followed. So, I realize I've been a little spoiled by Ruby, but there must be a tried and true idiom for trimming strings in Cocoa.</p> <p><strong>Aaaand the answer is already out there, my apologies:</strong></p> <p>NSString's <code>-stringByTrimmingCharactersInSet:</code> would do it:</p> <blockquote> <p>Returns a new string made by removing from both ends of the receiver characters contained in a given character set.</p> </blockquote> <p>I'm still curious to hear if anybody has other/preferred ways of doing this.</p>
<p>You're using whitespaceAndNewlineCharacterSet, good. But instead of using scanUpToCharactersFromSet, why not use stringByTrimmingCharactersInSet? Something like this...</p> <pre><code>strResult = [strResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; </code></pre> <p>EDIT: Didn't realize you already found stringByTrimmingCharactersInSet until after I posted this.</p>
How do I get PropertyChanged events to bubble up? <p>I have a hierarchy of objects (objects A, B), each of which implements <code>INotifyPropertyChanged</code> such that...</p> <p>A has a member of type B, B has a member of C, C is of type bool</p> <p>When C changes, its <code>PropertyChanged</code> event gets fired, however this does not fire B's property changed event. And therefore A does not react to B's change.</p> <p>Is there a good way to bubble this up?</p>
<p>What you are looking for is a Routed Event see:-</p> <p><a href="http://www.silverlightshow.net/items/Routed-Events-in-Silverlight.aspx" rel="nofollow">http://www.silverlightshow.net/items/Routed-Events-in-Silverlight.aspx</a></p>
In Java, how can I construct a "proxy wrapper" around an object which invokes a method upon changing a property? <p>I'm looking for something similar to the <a href="http://en.wikipedia.org/wiki/Proxy_pattern" rel="nofollow">Proxy pattern</a> or the <a href="http://java.sun.com/j2se/1.3/docs/guide/reflection/proxy.html" rel="nofollow">Dynamic Proxy Classes</a>, only that I don't want to intercept method calls before they are invoked on the real object, but rather I'd like to intercept properties that are being changed. I'd like the proxy to be able to represent multiple objects with different sets of properties. Something like <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/Proxy.html" rel="nofollow">the Proxy class in Action Script 3</a> would be fine.</p> <p>Here's what I want to achieve in general:</p> <p>I have a thread running with an object that manages a list of values (numbers, strings, objects) which were handed over by other threads in the program, so the class can take care of creating regular persistent snapshots on disk for the purpose of checkpointing the application. This persistor object manages a "dirty" flag that signifies whether the list of values has changed since the last checkpoint and needs to lock the list while it's busy writing it to disk.</p> <p>The persistor and the other components identify a particular item via a common name, so that when recovering from a crash, the other components can first check if the persistor has their latest copy saved and continue working where they left off.</p> <p>During normal operation, in order to work with the objects they handed over to the persistor, I want them to receive a reference to a proxy object that looks as if it were the original one, but whenever they change some value on it, the persistor notices and acts accordingly, for example by marking the item or the list as dirty before actually setting the real value.</p> <p><hr /></p> <p><strong>Edit</strong>: Alternatively, are there generic setters (like in PHP 5) in Java, that is, a method that gets called if a property doesn't exist? Or is there a type of object that I can add properties to at runtime?</p>
<p>If with "properties" you mean JavaBean properties, i.e. represented bay a getter and/or a setter method, then you can use a dynamic proxy to intercept the set method.</p> <p>If you mean instance variables, then no can do - not on the Java level. Perhaps something could be done by <a href="http://java-source.net/open-source/bytecode-libraries" rel="nofollow">manipulations on the byte code level</a> though.</p> <p>Actually, the easiest way to do it is probably by using <a href="http://www.eclipse.org/aspectj/" rel="nofollow">AspectJ</a> and defining a set() pointcut (which will intercept the field access on the byte code level).</p>
Should Exception Messages be Globalized <p>I'm working on a project and I'm just starting to do all the work necessary to globalize the application. One thing that comes up quite often is whether to globalize the exception messages, but ensuring that string.Format uses CultureInfo.CurrentCulture instead of CultureInfo.InvariantCulture. Additionally this would mean that exception messages would be stored in resource files that can be marked as culture-specific.</p> <p>So the question is, should exception messages be globalized or should be be left in either the InvariantCulture or the author's country; in my case en-US.</p>
<p>Exception messages should rarely be displayed directly to the user. You need to think of the consumer for each string. Obviously pieces of text in the user interface need internationalizing, but if an exception message is <em>only</em> going to be seen by support (or is going to be visible to the user and then emailed to support when they click a button) then where's the benefit of translating it?</p> <p>If you go too far, you could not only waste time and effort (and i18n can take a <em>lot</em> of effort) but you'll also make your support life harder as well. You really don't want to have to read log files written in a foreign language and translate them back to your native tongue.</p> <p>It makes sense for Microsoft to internationalize <em>their</em> exception messages, because they will be read by <em>developers</em> from all over the world - but unless you're multinational with developers in multiple countries who don't share a common language, I wouldn't translate message which are really meant for dev/support.</p>
Best Practice for Subversion and Image Uploads <p>Running an ASP.Net website and using TinyMCE for content management. Users need to be able to upload images for content. The images will be shown in website content (news, articles, etc) but won't otherwise be referenced by anything aside from their content.</p> <p>Should these images be under version control (svn), or should the upload directory just be passed around when needed (backup, testing, etc)? If they should be versioned, what's the best way to do this?</p>
<p>The content is not a part of the application just the instance you have running so it should be added to your backup not your SVN repository. I only add images to SVN if there are apart of the application it self.</p>
What version of CE is Window Mobile 6.5 built on? <p>Windows Mobile 5 was based on CE 5.0.</p> <p>Windows Mobile 6 was based on CE 5.2.</p> <p>Does anyone know what version of CE is used by Windows Mobile 6.5?</p>
<p>This <a href="http://forum.xda-developers.com/showthread.php?p=3204746" rel="nofollow">source</a> indicate that WM6.5 is also based on CE 5.2 (specifically 5.2.21139).</p>
Convert Pixels to Inches and vice versa in C# <p>I am looking to convert pixes to inches and vice versa. I understand that I need DPI, but I am not sure how to get this information (e.g. I don't have the <code>Graphics</code> object, so that's not an option).</p> <p>Is there a way?</p>
<p>On a video device, any answer to this question is typically not very accurate. The easiest example to use to see why this is the case is a projector. The output resolution is, say, 1024x768, but the DPI varies by how far away the screen is from the projector apeture. WPF, for example, always assumes 96 DPI on a video device.</p> <p>Presuming you still need an answer, regardless of the accuracy, and you don't have a Graphics object, you can create one from the screen with some P/Invoke and get the answer from it.</p> <pre><code>Single xDpi, yDpi; IntPtr dc = GetDC(IntPtr.Zero); using(Graphics g = Graphics.FromHdc(dc)) { xDpi = g.DpiX; yDpi = g.DpiY; } if (ReleaseDC(IntPtr.Zero) != 0) { // GetLastError and handle... } [DllImport("user32.dll")] private static extern IntPtr GetDC(IntPtr hwnd); [DllImport("user32.dll")] private static extern Int32 ReleaseDC(IntPtr hwnd); </code></pre>
boost vs ACE C++ cross platform performance comparison? <p>I am involved in a venture that will port some communications, parsing, data handling functionality from Win32 to Linux and both will be supported. The problem domain is very sensitive to throughput and performance. </p> <p>I have very little experience with performance characteristics of boost and ACE. Specifically we want to understand which library provides the best performance for threading. </p> <p>Can anyone provide some data -- documented or word-of-mouth or perhaps some links -- about the relative performance between the two?</p> <p>EDIT</p> <p>Thanks all. Confirmed our initial thoughts - we'll most likely choose boost for system level cross-platform stuff.</p>
<p>Neither library should really have any overhead compared to using native OS threading facilities. You should be looking at which API is cleaner. In my opinion the boost thread API is significantly easier to use.</p> <p>ACE tends to be more "classic OO", while boost tends to draw from the design of the C++ standard library. For example, launching a thread in ACE requires creating a new class derived from ACE_Task, and overriding the virtual svc() function which is called when your thread runs. In boost, you create a thread and run whatever function you want, which is significantly less invasive.</p>
The best way to clean your plugins out of eclipse 3.2 <p>Since the configuration manager and update manager for eclipse 3.2 is devoid of nice options for REMOVING or DELETING all my plugins it can be cumbersome to deal with needing to get your plugins in order. Just getting your dependencies worked out can be a nightmare when you have installed one version too high than you needed depending on the jdk version you are developing for.</p> <p>Other than trashing the files in the plugins and features directory (which sometimes works) what other options do we have in a M$ environment?</p> <p>In the situation where you are using RAD 7 you have to deal with the shared SDP70Shared folder too which is a bit ethereal as well.</p> <p>I want to see a fool proof way to clean house for regular eclipse 3.x, RAD, or any all in one package that will work.</p>
<p>Eclipse 3.2 has "uninstall" feature for plugins under Help->Software updates->Manage configuration.</p> <p>Eclipse 3.4 has the same functionality under Help->Software updates->Installed software</p>
Web frameworks <p>Ruby On Rails, Django or ASP.NET MVC.</p> <p>Which is better? What are the pro's and con's?</p> <p>Just curious as to your opinion, please no flames.</p>
<p><strong>Disclaimer: These are only my opinions not facts</strong></p> <p>Depends on your Needs.</p> <p><strong><a href="http://onstartups.com/home/tabid/3339/bid/160/Reasons-Why-Your-Startup-Should-Use-Ruby-On-Rails-RoR.aspx" rel="nofollow">Rails +</a></strong></p> <ul> <li>big community </li> <li>quick to get up and running</li> <li>cheap to host</li> </ul> <p><strong>Rails -</strong></p> <ul> <li>slower and will need some "help" if you want to scale it(this will hardly be a problem for most people)</li> <li>harder sell to the boss</li> </ul> <p><strong><a href="http://www.cnblogs.com/xioxu/archive/2008/12/16/1356377.html" rel="nofollow">ASP.NET MVC +</a></strong></p> <ul> <li>Easy Sell</li> <li>Phil Hack(need I say more)</li> <li>Will be widely adopted(IMO)</li> <li>Lots of support</li> </ul> <p><strong>ASP.NET MVC -</strong></p> <ul> <li>More expensive(hosting)</li> <li>Still in Beta</li> </ul> <p><strong><a href="http://www.porcheron.info/why-django/" rel="nofollow">Django +</a></strong></p> <ul> <li>Python is one of google's choice of languages so right there it is worth a look</li> <li><a href="http://code.google.com/appengine/articles/django.html" rel="nofollow">Runs in google's cloud environment</a> (<a href="http://code.google.com/appengine/" rel="nofollow">app engine</a>)</li> <li>dynamic -easy to use cheap to run</li> </ul> <p><strong>Django -</strong></p> <ul> <li>No Function overloading(v2.5)</li> <li>Again slower then a compiled language</li> <li>not AS big of community(IMO) as some other languages</li> </ul> <p><em>I included some links of other people's positive options of all 3 options....</em> </p> <p>It is very very rare for a choice in language\technology to be the downfall of website, project or business.... IMO</p>
Defining an Entity Framework 1:1 association <p>I'm trying to define a 1:1 association between two entities (one maps to a table and the other to a view - using DefinedQuery) in an Entity Framework model. When trying to define the mapping for this in the designer, it makes me choose the (1) table or view to map the association to. What am I supposed to choose? I can choose either of the two tables but then I am forced to choose a column from that table (or view) for each end of the relationship. I would expect to be able to choose a column from one table for one end of the association and a column from the other table for the other end of the association, but there's no way to do this.</p> <p>Here I've chosen to map to the "DW_ WF_ClaimInfo" view and it is forcing me to choose two columns from that view - one for each end of the relationship.</p> <p>I've also tried defining the mapping manually in the XML as follows:</p> <pre><code>&lt;AssociationSetMapping Name="Entity1Entity2" TypeName="ClaimsModel.Entity1Entity2" StoreEntitySet="Entity1"&gt; &lt;EndProperty Name="Entity2"&gt; &lt;ScalarProperty Name="DOCUMENT" ColumnName="DOCUMENT" /&gt; &lt;/EndProperty&gt; &lt;EndProperty Name="Entity1"&gt; &lt;ScalarProperty Name="PK_DocumentId" ColumnName="PK_DocumentId" /&gt; &lt;/EndProperty&gt; &lt;/AssociationSetMapping&gt; </code></pre> <p>But this gives: Error 2010: The Column 'DOCUMENT' specified as part of this MSL does not exist in MetadataWorkspace. Seems like it still expects both columns to come from the same table, which doesn't make sense to me.</p> <p>Furthermore, if I select the same key for each end, e.g.:</p> <pre><code>&lt;AssociationSetMapping Name="Entity1Entity2" TypeName="ClaimsModel.Entity1Entity2" StoreEntitySet="Entity1"&gt; &lt;EndProperty Name="Entity2"&gt; &lt;ScalarProperty Name="DOCUMENT" ColumnName="PK_DocumentId" /&gt; &lt;/EndProperty&gt; &lt;EndProperty Name="Entity1"&gt; &lt;ScalarProperty Name="PK_DocumentId" ColumnName="PK_DocumentId" /&gt; &lt;/EndProperty&gt; &lt;/AssociationSetMapping&gt; </code></pre> <p>I then get:</p> <pre><code>Error 3021: Problem in Mapping Fragment starting at line 675: Each of the following columns in table AssignedClaims is mapped to multiple conceptual side properties: AssignedClaims.PK_DocumentId is mapped to &lt;AssignedClaimDW_WF_ClaimInfo.DW_WF_ClaimInfo.DOCUMENT, AssignedClaimDW_WF_ClaimInfo.AssignedClaim.PK_DocumentId&gt; </code></pre> <p>What am I not getting?</p>
<p>You have to select the table, that cotains the foreign key. The next step is to remove that foreign key from the entity, as it is already expressed using the relation you just created.</p> <p>Example:</p> <pre><code>table A ------- A_ID int B_ID int table B ------- B_ID int </code></pre> <p>In this case, you would select the table A in the designer, as it contains the foreign key. Also you'll need to remove B_ID from the A entity afterwards.</p>
Neural Network Structure <p>I am currently building a Neural Network library. I have constructed it as an object graph for simplicity. I am wondering if anyone can quantify the performance benefits of going to an array based approach. What I have now works very good for building networks of close to arbitrary complexity. Regular (backpropped) networks as well as recurrent networks are supported. I am considering having trained networks "compile" into some "simpler" form such as arrays. </p> <p>I just wanted to see if anyone out there had any practical advice or experience building neural networks that deployed well into production. Is there any benefit to having the final product be array based instead of object graph based?</p> <p>P.S Memory footprint is less important than speed.</p>
<p>People have started using GPGPU techniques in AI, and having your neural net in matrix form could leverage the much faster matrix ops in your typical graphics card.</p>
Visual Studio 2005 Search Memory <p>I don't think this exists, but I'll throw this out there anyway. Is it possible, while debugging, to search for a value in memory?</p> <p>For example, if I have a string "uniqueString" cached somewhere in memory, but I don't know under which variable it's stored--can I do a search for it? As in, find out which variable(s) have "uniqueString" as their value?</p> <p>This is for C# managed code.</p>
<p>windbg will let you do the search directly. 's' is the command you're looking for, here's a very good <a href="http://www.software.rkuster.com/windbg/cmd.htm" rel="nofollow">cheat sheet</a>. sos extension lets you scan for string objects too in managed code though the s command should find them too (must use unicode aware search).</p>
Halting in non-Turing-complete languages <p>The halting problem cannot be solved for Turing complete languages and it can be solved trivially for some non-TC languages like regexes where it always halts. </p> <p>I was wondering if there are any languages that has both the ability to halt and not halt but admits an algorithm that can determine whether it halts.</p>
<p>The <a href="http://en.wikipedia.org/wiki/Halting_problem">halting problem</a> does not act on languages. Rather, it acts on machines (i.e., programs): it asks whether a given program halts on a given input.</p> <p>Perhaps you meant to ask whether it can be solved for other models of computation (like regular expressions, which you mention, but also like <a href="http://en.wikipedia.org/wiki/Pushdown_automaton">push-down automata</a>).</p> <p>Halting can, in general, be detected in models with finite resources (like regular expressions or, equivalently, finite automata, which have a fixed number of states and no external storage). This is easily accomplished by enumerating all possible configurations and checking whether the machine enters the same configuration twice (indicating an infinite loop); with finite resources, we can put an upper bound on the amount of time before we <em>must</em> see a repeated configuration if the machine does not halt.</p> <p>Usually, models with infinite resources (unbounded TMs and PDAs, for instance), cannot be halt-checked, but it would be best to investigate the models and their open problems individually.</p> <p>(Sorry for all the Wikipedia links, but it actually is a very good resource for this kind of question.)</p>
What are the dimensions, file types, and ppi resolution of an iOS app icon? <p>What are the specifications for the icons required by Apple for a custom iPhone application published?</p> <blockquote> <p>57x57, PNG, No Transparency, No Layers, 72 PPI</p> <p>512x512, TIFF or JPEG, No Transparency, No Layers, 72 PPI</p> </blockquote> <p>Note: iPhone OS applies rounded corners, optionally shine, and other effects</p> <p>Also have a large version of your logo with the name of the application in case Apple contacts you needing a version for marketing purposes.</p>
<p>The icon should be a 57x57 pixel PNG. The PNGs generated by Apple have a PPI of 72.01 so I guess something in that range will work fine. Don't have a very high PPI else images are not rendered properly. </p> <p>If you want to use a custom icon and not let the iPhone to apply the gloss to your icon, add a key to info.plist called UIPrerenderedIcon (is a boolean value) and make it checked.</p> <p>When submitting the app to the app store, you will need a 512x512 pixel version of your app's icon (this one in jpeg or tiff format) and at least one screenshot of your app. You can have additional 4 screenshots of the app.</p> <p><strong>EDIT</strong> Now the specs for icon (to be submitted in iTunes connect) and the app icons have changed. The icon to be submitted to itunesconnect must be 1024x1024 px.</p> <p>For the app icons, you can find details here - <a href="http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/App-RelatedResources/App-RelatedResources.html#//apple_ref/doc/uid/TP40007072-CH6-SW1">http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/App-RelatedResources/App-RelatedResources.html#//apple_ref/doc/uid/TP40007072-CH6-SW1</a></p> <p>Also, make sure the icon files are NON-INTERLACED PNG files. Recently one of our apps' binary was marked invalid since one of the app icon files was an interlaced PNG.</p>
Shared Library Discovery <p>I am using C++ on Linux. I want to dynamically bind a collection of unknown shared libraries. I need my code to detect all the public functions exposed by the shared library and the string names of those functions. How do I accomplish this task?</p>
<p>AFAIK, there is no glibc function to enumerate all the public interface functions for a .so file. You can refer to libelf to read all symbols from a dynamic file. Libelf is here <a href="http://www.mr511.de/software/" rel="nofollow">http://www.mr511.de/software/</a>. After you find a symbol, you can use dlopen and dlsym to load it.</p>
Writing to an iframe from NSTextView <p>I have built a web based WYSIWYG editor, which Im accessing programatically from my cocoa application. At the moment I'm able to run scripts and retrieve the HTML from the iFrame in the editor, but I'm unable to send text from an NSTextView to the iFrame. Any ideas?</p> <p>The editor is here <a href="http://www.alexmillsdesign.com/Developer/FernEngine/" rel="nofollow">http://www.alexmillsdesign.com/Developer/FernEngine/</a></p> <p>Cheers Alex Mills</p>
<p>I'm not an expert in this area but I have written sample code in the past that did something similar to this. The approach I took was the following: in your Cocoa class where you want to update the text insert code similar to</p> <pre><code>WebScriptObject *webScriptObject = [_webView windowScriptObject]; id result = [webScriptObject callWebScriptMethod:@"setTableRows" withArguments:[NSArray arrayWithObject:fauxData]]; </code></pre> <p>where fauxData is whatever you want to pass to JS, and in the JS source have something similar to</p> <pre><code>var mytable = document.getElementById("myTable"); var mytbody = document.getElementById("myTbody"); var docFragment = document.createDocumentFragment(); var myNewtbody = document.createElement("tbody"); myNewtbody.id = "myTbody"; var trElem, tdElem, txtNode; for(var j = 0; j &lt; row_data.length; ++j) { trElem = document.createElement("tr"); trElem.className = "tr" + (j%2); tdElem = document.createElement("td"); tdElem.className = "col0"; txtNode = document.createTextNode(row_data[j].lastName); tdElem.appendChild(txtNode); trElem.appendChild(tdElem); tdElem = document.createElement("td"); tdElem.className = "col4"; txtNode = document.createTextNode(row_data[j].firstName); tdElem.appendChild(txtNode); trElem.appendChild(tdElem); docFragment.appendChild(trElem); } myNewtbody.appendChild(docFragment); mytable.replaceChild(myNewtbody, mytbody); </code></pre> <p>and of course your HTML should have something like</p> <pre><code>&lt;table id="myTable"&gt; &lt;thead id="myThead"&gt; &lt;tr&gt; &lt;th&gt;Last&lt;/th&gt; &lt;th&gt;First&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody id="myTbody"&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>Obviously this fills in rows of data in a table, but updating text would be similar.</p>
Operator overload <pre><code>class test { public: test &amp;operator=(const test &amp; other){} // 1 const test &amp; operator+(const test&amp; other) const {} // 2 const test &amp; operator+(int m) {} //3 private: int n; }; int main() { test t1 , t2, t3; // this works fine t1 = t2.operator+(t3) , calls 2 and 1 t1 = t2 + t3; // this works fine t1 = t2.operator+ (100). calls 3 and 1 t1 = t2 + 100; //this works fine t1 = (t2.operator+ (100)).operator+ (t3) t1 = t2 + 100 +t3; //why is the error in this one ???? // it should be t1 = (t2.operator+ (t3)).operator+ (100) t1 = t2 + t3 + 100; return 0; } </code></pre>
<p>Because object returned by t2+t3 is const, and you cannot call its non-const function (3).</p> <p>It works fine in case of "t1 = t2 + 100 +t3;", because object returned by t2+100 is const too, but you are calling its const function (2), which is ok.</p>
Changing the browser preference from JavaScript <p>I'm having a problem with cookies. If the browser has cookies disabled, the cookie gets rejected. Is there a way to enable cookies on the client's browser that is compatible with Internet&nbsp;Explorer, Firefox, Opera and Chrome?</p>
<p>If a user has chosen to disable cookies, who are you to override that choice?<br /> The best thing to do is notify the user that they need to enable cookies for your script/site to work and provide a link to some instructions on how to do so.<br /> Or find a different way to achieve what you are trying to do</p>
Converting UTF-8 to WIN1252 using C++Builder 5 <p>I have to import some UTF-8 encoded text-file into my C++Builder 5 program. Are there any components or code samples to accomplish that?</p>
<p>You are best off reading all the other questions on SO that are tagged unicode and c++. For starters you should probably look at <a href="http://stackoverflow.com/questions/433301/portable-and-simple-unicode-string-library-for-c-c">this one</a> and see whether library in the accepted answer (<a href="http://utfcpp.sourceforge.net/" rel="nofollow">UTF8-CPP</a>) works for you.</p> <p>I would however first think about what you're trying to achieve, as there is no way you can just import UTF-8-encoded strings into "Ansi" (what ever you mean by that, maybe something like ISO8859_1 or WIN1252 encoding?).</p>
directx mouse click simulation <p>How can I simulate the mouse click in a directx application? mouse_event and PostMessage with WM_LBUTTONDOWN don't work...</p> <p>so it must be something to do with the DirectInput</p> <p>I haven't found out nothing useful with google, so you may be knowing the answer...</p> <p>thanks in advance</p> <p>//update</p> <p>I wrote the text wrongly, what I want is to make the directx app believe that the mouse has just clicked, but without effectively using the mouse and without using SendInput or mouse_event, which need that the window must be focused</p>
<p>Try <a href="http://www.autoitscript.com/" rel="nofollow">AutoIt</a> it is perfect for sending a click to a particular control. The </p> <pre><code>ControlClick ( "title", "text", controlID [, button [, clicks [, x [, y ]]]] ) </code></pre> <p>command can do exactly what you want. The directx control will detect the click.</p>
ACL for a network device <p>I need to implement ACL based authentication mechanism for a device. This device can be accessed through various interfaces like web pages, TL1 (basically through some command prompt) etc.</p> <p>I need to keep ACL logic centralized so that request from any interface can be authenticated. </p> <p>ACL logic would basically check whether the logged in user can perform the operation he is trying to perform. For this I will create groups and add users to these groups. Each group would maintain list of operation allowed under that particular group.</p> <p>Can someone suggest be the best way to implement this?</p> <p>Is there any existing software/tool that allows me to achieve this? Any open source project?</p> <p>I am a C/C++ programmer and a newbie to the ACL concept. Above mentioned module is to be developed for Linux OS. Web interface will be in CGI.</p> <p>Thanks in advance.</p>
<p>Your question is misleading. What you ask, has in most cases nothing to do with the ACLs of the filesystem objects in linux.</p> <p>I'm assuming your cgi is a single file, written in c++.</p> <p>You will have to use some local data storage solution. In your place I used sqlite, or some other sql-based solution.</p> <p>I think, your acl lists - which aren't filesystem-based ACLs - should be stored in your local database.</p> <p>P.s. Further I suggest to use at least multithreaded fcgi, big cgi binaries are really highly suboptimal.</p>
Mercurial: multiline commit message on the command line? <p>How can I specify a multiline commit message for mercurial on the command line?</p> <pre><code>hg commit -m "* add foo\n* fix bar" </code></pre> <p>does not work. The log shows:</p> <pre><code>changeset: 13:f2c6526e5911 tag: tip date: Fri Jan 23 23:22:36 2009 +0100 files: foobar.cpp description: * add foo\n*fix bar </code></pre>
<blockquote> <p>Mercurial: multiline commit message on the command line?</p> </blockquote> <p>Hit enter.</p> <pre><code>$ hg commit -m "Did some work &gt; Now I'm done" </code></pre> <p>One of the things is that only the first line shows up in hg log:</p> <pre><code>$ hg log changeset: 0:d2dc019450a2 tag: tip user: Aaron Maenpaa &lt;zacherates@gmail.com&gt; date: Sat Jan 24 07:46:23 2009 -0500 summary: Did some work </code></pre> <p>... but if you fire up "hg view" you can see that the whole message is there.</p> <p>Edited to add:</p> <p>... but hg -v log shows the whole message:</p> <pre><code>$ hg -v log changeset: 0:d2dc019450a2 tag: tip user: Aaron Maenpaa &lt;zacherates@gmail.com&gt; date: Sat Jan 24 07:46:23 2009 -0500 files: work description: Did some work Now I'm done </code></pre>
Php By Reference <p>Can someone please explain what the "&amp;" does in the following:</p> <pre><code>class TEST { } $abc =&amp; new TEST(); </code></pre> <p>I know it is by reference. But can someone illustrate why and when I would need such a thing? Or point me to a url where this is explained well. I am unable to grasp the concept.</p> <p>Thank you very much.</p>
<p>As I understand it, you're not asking about PHP references in general, but about the <code>$foo =&amp; new Bar();</code> construction idiom.</p> <p>This is only seen in PHP4 as the usual <code>$foo = new Bar()</code> stores a <em>copy</em> of the object. This generally goes unnoticed unless the class stored a reference to $this in the constructor. When calling a method on the returned object later on, there would be two distinct copies of the object in existence when the intention was probably to have just one.</p> <p>Consider this code where the constructor stores a reference to $this in a global var</p> <pre><code>class Bar { function Bar(){ $GLOBALS['copy']=&amp;$this; $this-&gt;str="hello"; } } //store copy of constructed object $x=new Bar; $x-&gt;str="goodbye"; echo $copy-&gt;str."\n"; //hello echo $x-&gt;str."\n"; //goodbye //store reference to constructed object $x=&amp;new Bar; $x-&gt;str="au revoir"; echo $copy-&gt;str."\n"; //au revoir echo $x-&gt;str."\n"; //au revoir </code></pre> <p>In the first example, $x and $copy refer to different instances of Foo, but in the second they are the same.</p>
WPF databinding: database or objects? <p>I'm trying to create this:</p> <p>Tag1 has the ordered list of objects: O1, O3, O2. Tag2 has the ordered list of objects: O1, O4.</p> <p>Every time I click a tag, I want to see the list of objects. So clicking Tag1 would show in a listbox:</p> <ul> <li>O1</li> <li>O3</li> <li>O2</li> </ul> <p>But I would like to <strong>keep the auto update so every time I edit or add/delete an object</strong> it auto updates (I suppose I need to implement something like the interfaces <code>INotifyCollectionChanged</code> and <code>INotifyPropertyChanged</code>?).</p> <p>I could use a database and have the tables Tag, Object and TagObject, this last one with the TagID and ObjectID. But I also would like to avoid databases, since it's a desktop application.</p> <p>I could also use objects like <code>ObservableCollections</code>, but I have the problem of having duplicate objects. I can use references to the objects but it gets messy.</p> <p>Anyone has any suggestion on how to do this?</p> <p>Thank you.</p>
<p>One option would be to create an object that contains a dataset (System.Data namespace). Inside the dataset it would have 3 tables that would be linked using defined foreign keys the same as if it was in a database. These can later be stored to XML if need be.</p> <p>Your object would then have to expose a dataview which can be set as the datacontext and bound too.</p> <p>Editing the dataset in code then updates the screen and editing the screen will update the dataset.</p>
What do you suggest on how to stop hit counter for the same IP in asp.NET website? <p>As you can see on the question, what is your advice about stoping hit counter for the same ip in ASP.NET web site ?</p> <p>Im my real estate project i increase the view count of a property when it is viewed. But i just want to increase it only if the user has a different ip. If the user refresh the page, the hit counter shouldn't be increased.</p> <p>Thanks in advance</p>
<p>If it's a website you can be a little more accurate counting unique visitors by dropping a cookie containing the date &amp; time. Check the cookie, if it exists and the date is today don't add one to the counter.</p>