instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Is there a way (without installing any libraries) of validating XML using a custom DTD in PHP?</p>
<p>Take a look at <a href="http://us3.php.net/dom" rel="noreferrer">PHP's DOM</a>, especially <a href="http://us3.php.net/manual/en/domdocument.schemavalidate.php" rel="noreferrer">DOMDocument::schemaValidate</a> and <a href="http://us3.php.net/manual/en/domdocument.validate.php" rel="noreferrer">DOMDocument::validate</a>.</p> <p>The example for DOMDocument::validate is fairly simple:</p> <pre><code>&lt;?php $dom = new DOMDocument; $dom-&gt;Load('book.xml'); if ($dom-&gt;validate()) { echo "This document is valid!\n"; } ?&gt; </code></pre>
<h2>Trying to complete "owenmarshall" answer:</h2> <p><strong>in xml-validator.php:</strong></p> <p>add html, header, body, ...</p> <pre><code>&lt;?php $dom = new DOMDocument; &lt;br/&gt; $dom-&gt;Load('template-format.xml');&lt;br/&gt; if ($dom-&gt;validate()) { &lt;br/&gt; echo "This document is valid!\n"; &lt;br/&gt; } ?&gt; </code></pre> <p><strong>template-format.xml:</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;!-- DTD to Validate against (format example) --&gt; &lt;!DOCTYPE template-format [ &lt;br/&gt; &lt;!ELEMENT template-format (template)&gt; &lt;br/&gt; &lt;!ELEMENT template (background-color, color, font-size, header-image)&gt; &lt;br/&gt; &lt;!ELEMENT background-color (#PCDATA)&gt; &lt;br/&gt; &lt;!ELEMENT color (#PCDATA)&gt; &lt;br/&gt; &lt;!ELEMENT font-size (#PCDATA)&gt; &lt;br/&gt; &lt;!ELEMENT header-image (#PCDATA)&gt; &lt;br/&gt; ]&gt; &lt;!-- XML example --&gt; &lt;template-format&gt; &lt;template&gt; &lt;background-color&gt;&amp;lt;/background-color&gt; &lt;br/&gt; &lt;color&gt;&amp;lt;/color&gt; &lt;br/&gt; &lt;font-size&gt;&amp;lt;/font-size&gt; &lt;br/&gt; &lt;header-image&gt;&amp;lt;/header-image&gt; &lt;br/&gt; &lt;/template&gt; &lt;/template-format&gt; </code></pre>
12,744
<p>How do you implement an <strong>efficient and thread safe reference counting system</strong> on X86 CPUs in the C++ programming language? </p> <p>I always run into the problem that the <strong>critical operations not atomic</strong>, and the available X86 Interlock operations are not sufficient for implementing the ref counting system.</p> <p>The following article covers this topic, but requires special CPU instructions:</p> <p><a href="http://www.ddj.com/architect/184401888" rel="noreferrer">http://www.ddj.com/architect/184401888</a></p>
<p>Nowadays, you can use the Boost/TR1 shared_ptr&lt;> smart pointer to keep your reference counted references.</p> <p>Works great; no fuss, no muss. The shared_ptr&lt;> class takes care of all the locking needed on the refcount.</p>
<p>If the instruction itself is not atomic then you need to make the section of code that updates the appropriate variable a critical section.</p> <p><b>i.e.</b> You need to prevent other threads entering that section of code by using some locking scheme. Of course the locks need to be atomic, but you can find an atomic locking mechanism within the pthread_mutex class.</p> <p>The question of efficient: The pthread library is as efficient as it can be and still guarantee that mutex lock is atomic for your OS.</p> <p>Is it expensive: Probably. But for everything that requires a guarantee there is a cost.</p>
11,856
<p>I have a following SQL Server 2005 database schema:</p> <pre><code>CREATE TABLE Messages ( MessageID int, Subject varchar(500), Text varchar(max) NULL, UserID NULL ) </code></pre> <p>The column "UserID" - which can be null - is a foreign key and links to the table</p> <pre><code>CREATE TABLE Users ( UserID int, ... ) </code></pre> <p>Now I have several POCO classes with names Message, User etc. that I use in the following query:</p> <pre><code>public IList&lt;Message&gt; GetMessages(...) { var q = (from m in dataContext.Messages.Include("User") where ... select m); // could call ToList(), but... return (from m in q select new Message { ID = m.MessageID, User = new User { ID = m.User.UserID, FirstName = m.User.FirstName, ... } }).ToList(); } </code></pre> <p>Now note that I advise the entity framework - using Include("Users") - to load a user associated with a message, if any. Also note that I don't call ToList() after the first LINQ statement. By doing so only specified columns in the projection list - in this case MessageID, UserID, FirstName - will be returned from the database. </p> <p>Here lies the problem - as soon as Entity Framework encounters a message with UserID == NULL, it throws an exception, saying that it could not convert to Int32 because the DB value is NULL.</p> <p>If I change the last couple of lines to</p> <pre><code>return (from m in q select new Message { ID = m.MessageID, User = m.User == null ? null : new User { ID = m.User.UserID, ... } }).ToList() </code></pre> <p>then a run-time NotSupportedException is thrown telling that it can't create a constant User type and only primitives like int, string, guid are supported.</p> <p>Anybody has any idea how to handle it besides materializing the results just right after the first statement and using in-memory projection afterwards? Thanks.</p>
<p>You forgot to include the declaration of your "Message" class but I suspect that the UserID property in that class is not declared as a nullable type. If that is the case, change it from "int" to "int?" (nullable int).</p>
<p>I suspect your relationship is not 1 to 1.</p>
16,975
<p>I'm trying to build the example described at <a href="http://support.microsoft.com/kb/178749/EN-US/" rel="nofollow noreferrer">http://support.microsoft.com/kb/178749/EN-US/</a> in order to build an application that programatically accesses Excel using Automation. I have Visual C++ 2005/Visual Studio 2005. Some of the instructions don't exactly match up (classwizard, mostly), but the general idea seems to be the same.</p> <p>Problems: I don't end up with an excel.h file after using the "new class" to create my wrapper classes. So I can' t #include that file as it specifies in step 13. I do get a excel.tlh and an excel.tli in my windebug directory, but that doesn't seem to work. I tried all orders for </p> <pre><code>#include "stdafx.h" #include "debug/excel.tli" #include "debug/excel.tlh" </code></pre> <p>... including leaving one of those files out of the compile, but I still end up with a ton of compile errors.</p> <p>Here's the top 5 compile errors with the above #includes:</p> <pre><code>1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2653: 'Adjustments' : is not a class or namespace name 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2146: syntax error : missing ';' before identifier 'GetParent' 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2433: 'IDispatchPtr' : 'inline' not permitted on data declarations 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(16) : error C3861: 'get_Parent': identifier not found </code></pre> <p>Here's the top 5 errors with these includes:</p> <pre><code>#include "stdafx.h" #include "debug/excel.tlh" 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(550) : error C3121: cannot change GUID for class 'IFilter' 1&gt; c:\program files\microsoft sdks\windows\v6.0\include\comdef.h(483) : see declaration of 'IFilter' 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(1541) : error C2786: 'BOOL (__stdcall *)(HDC,int,int,int,int)' : invalid operand for __uuidof 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(1541) : error C2923: '_com_IIID' : 'Rectangle' is not a valid template type argument for parameter '_Interface' 1&gt; c:\program files\microsoft sdks\windows\v6.0\include\wingdi.h(3667) : see declaration of 'Rectangle' 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tlh(1541) : error C3203: '_com_IIID' : unspecialized class template can't be used as a template argument for template parameter '_IIID', expected a real type </code></pre> <p>Here's the top 5 errors with these includes:</p> <pre><code>#include "stdafx.h" #include "debug/excel.tli" 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2653: 'Adjustments' : is not a class or namespace name 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2146: syntax error : missing ';' before identifier 'GetParent' 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C2433: 'IDispatchPtr' : 'inline' not permitted on data declarations 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1&gt;c:\users\sniles\documents\visual studio 2005\source10\testole\testole\debug\excel.tli(14) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int </code></pre> <p>Thanks in advance.</p>
<p>I'm not familiar with the ClassWizard wrapper generator, but it looks like it may have #imported the Excel COM type library without a namespace, and you're getting conflicts with the SDK header files. Check the <code>.tlh</code> file and ensure there's a namespace around the definitions. If not, I'd look at importing it the more manual (but safer) way using #import.</p> <p>Check out using #import directly; it will generate the <code>.tlh</code> and <code>.tli</code> files in the build directory, which you can then use directory with <code>CComPtr&lt;&gt;</code> and the like. I've found that to be much more straightforward than using CW wrapper classes. That's my advice anyway.</p>
<p>I don't know if this helps but generally you <code>#import</code> the type library but you do NOT <code>#include</code> the .tli and .tlh files (the <code>#import</code> implicitly does this).</p> <p>Also, remember there are two ways of calling a COM server in MFC.</p> <ol> <li><p>Use <code>#import</code> which basically creates smart ATL pointers to create COM objects and call methods.</p></li> <li><p>Use the class wizard to create an <code>IDispatch</code> style class wrapper to create COM object and call the methods.</p></li> </ol>
22,440
<p>I've got some Java code using a servlet and Apache Commons FileUpload to upload a file to a set directory. It's working fine for character data (e.g. text files) but image files are coming out garbled. I can open them but the image doesn't look like it should. Here's my code:</p> <p>Servlet</p> <pre><code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String customerPath = "\\leetest\\"; // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { // Form field. Ignore for now } else { BufferedInputStream stream = new BufferedInputStream(item .openStream()); if (stream == null) { LOGGER .error("Something went wrong with fetching the stream for field " + name); } byte[] bytes = StreamUtils.getBytes(stream); FileManager.createFile(customerPath, item.getName(), bytes); stream.close(); } } } } catch (Exception e) { throw new UploadException("An error occured during upload: " + e.getMessage()); } } </code></pre> <p>StreamUtils.getBytes(stream) looks like:</p> <pre><code>public static byte[] getBytes(InputStream src, int buffsize) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); byte[] buff = new byte[buffsize]; while (true) { int nBytesRead = src.read(buff); if (nBytesRead &lt; 0) { break; } byteStream.write(buff); } byte[] result = byteStream.toByteArray(); byteStream.close(); return result; } </code></pre> <p>And finally FileManager.createFile looks like:</p> <pre><code>public static void createFile(String customerPath, String filename, byte[] fileData) throws IOException { customerPath = getFullPath(customerPath + filename); File newFile = new File(customerPath); if (!newFile.getParentFile().exists()) { newFile.getParentFile().mkdirs(); } FileOutputStream outputStream = new FileOutputStream(newFile); outputStream.write(fileData); outputStream.close(); } </code></pre> <p>Can anyone spot what I'm doing wrong?</p> <p>Cheers, Lee</p>
<p>One thing I don't like is here in this block from StreamUtils.getBytes():</p> <pre><code> 1 while (true) { 2 int nBytesRead = src.read(buff); 3 if (nBytesRead &lt; 0) { 4 break; 5 } 6 byteStream.write(buff); 7 } </code></pre> <p>At line 6, it writes the entire buffer, no matter how many bytes are read in. I am not convinced this will always be the case. It would be more correct like this:</p> <pre><code> 1 while (true) { 2 int nBytesRead = src.read(buff); 3 if (nBytesRead &lt; 0) { 4 break; 5 } else { 6 byteStream.write(buff, 0, nBytesRead); 7 } 8 } </code></pre> <p>Note the 'else' on line 5, along with the two additional parameters (array index start position and length to copy) on line 6.</p> <p>I could imagine that for larger files, like images, the buffer returns before it is filled (maybe it is waiting for more). That means you'd be unintentionally writing old data that was remaining in the tail end of the buffer. This is almost certainly happening most of the time at EoF, assuming a buffer > 1 byte, but extra data at EoF is probably not the cause of your corruption...it is just not desirable. </p>
<p>Are you sure that the image isn't coming through garbled or that you aren't dropping some packets on the way in. </p>
6,306
<p>Just started getting into jQuery and have an issue with a jQuery Post call working perfectly on my local dev box (VS 2008 built-in web server), but failing when I deploy to a windows 2003 server (IIS 6) box.</p> <p>The post works and the page being posted to process things correctly, but a response is never received by the calling Post function. The submitting page just reloads with no changes.</p> <p>Here is my Post function (it is enclosed in the <code>$(document).ready(function() {...</code></p> <p>The alert in the response function never fires:</p> <pre><code> $('.nextButton').click(function() { var idString = ''; $("div.dropZone &gt; div").each(function(n) { idString += this.id + '|'; }); $.post('CustomPostHandler.aspx?step=criteria', { selected: idString }, function(data) { alert(data); }); }); </code></pre> <p>The post handler page does receive the idString variable fine, after some processing it attempts to write back a response:</p> <pre><code> // Return dummy response to caller Response.Clear(); Response.ContentType = "text/plain"; Response.Write("success"); Response.End(); </code></pre> <p>I've checked the deployment server environment and don't see anything missing (this is running against the 3.5 SP1 framework). Anyone have any ideas or am I missing something?</p>
<p>The problem is probably due to caching.<br> Try adding a random number to the post URL</p> <pre><code>$.post('CustomPostHandler.aspx?step=criteria&amp;random=' + Math.random().toString(), { selected: idString }, </code></pre>
<p>I agree that is probably due to caching. The more general <code>$.ajax</code> function allows you to set the cache option to false in order to disable caching.</p> <p>Have a look at the <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options" rel="nofollow noreferrer">documentation</a>.</p>
38,314
<p>Besides the syntactic sugar and expressiveness power what are the differences in runtime efficiency. I mean, plpgsql can be faster than, lets say plpythonu or pljava? Or are they all approximately equals?</p> <p>We are using stored procedures for the task of detecting nearly-duplicates records of people in a moderately sized database (around 10M of records)</p>
<p>plpgsql provides greater type safety I believe, you have to perform explicit casts if you want to perform operations using two different columns of similar type, like varchar and text or int4 and int8. This is important because if you need to have your stored proc use indexes, postgres requires that the types match exactly between join conditions (edit: for equality checks too I think).</p> <p>There may be a facility for this in the other languages though, I haven't used them. In any case, I hope this gives you a better starting point for your investigation.</p>
<p>Without doing actual testing, I would expect plpgsql to be somewhat more efficient than other languages, because it's small. Having said that, remember that SQL functions are likely to be even faster than plpgsql, if a function is simple enough that you can write it in just SQL.</p>
30,716
<p>I have two branches : X and Y. I want to replace a Y's subdirectory (y1) by its equivalent from X (x1).</p> <p>For the time being, I do the following : copy x1 to Y, remove y1, rename (move) x1 to y1 :</p> <pre><code>a) svn copy https://path/to/branches/X/x1 https://path/to/branches/Y/ b) svn delete https://path/to/branches/Y/y1 c) svn move https://path/to/branches/Y/x1 https://path/to/branches/Y/y1 </code></pre> <p>I think it is quite ugly... </p> <p>How could I do it in a smarter way ? </p>
<p>If you really want to replace the directory, you can do that with two operations:</p> <pre><code>svn delete https://path/to/branches/Y/y1 svn copy https://path/to/branches/X/x1 https://path/to/branches/Y/y1 </code></pre> <p>If Y/y1 is really already an older copy of X/y1, you shouldn't replace it all the time, but instead merge all changes since the last merge into it.</p>
<p>Why not just two steps:</p> <pre><code>a) svn delete https://path/to/branches/Y/y1 b) svn copy https://path/to/branches/X/x1 https://path/to/branches/Y/y1 </code></pre>
48,908
<p>I need to get a list of all documents in a site collection, which I believe I can do with either the alldocs table or the alluserdata table (MOSS 2007 SP1) but do not see how I can get the author information for the document. I do not need the contents of the document (e.g. AllDocStreams content)</p> <p><strong>Something like this:</strong></p> <pre><code>SELECT tp_DirName, tp_LeafName, tp_Version, tp_Modified, tp_Created FROM AllUserData WHERE (tp_ContentType = 'Document') AND (tp_LeafName NOT LIKE '%.css') AND (tp_LeafName NOT LIKE '%.jpg') AND (tp_LeafName NOT LIKE '%.png') AND (tp_LeafName NOT LIKE '%.wmf') AND (tp_LeafName NOT LIKE '%.gif') AND (tp_DirName NOT LIKE '%Template%') AND (tp_IsCurrentVersion = 1) AND (tp_LeafName NOT LIKE '%.xsl') ORDER BY tp_SiteId, tp_ListId, tp_DirName, tp_LeafName, tp_IsCurrentVersion DESC </code></pre> <p><strong>Is there a better way to go about this?</strong></p>
<p>People that claim that you cannot query SharePoint databases because it is not supported are wrong. From reading the documentation, it is fine to query the database as long as you use the 'With(NoLock)' clause. It is clearly not supported to update, delete, or insert records.</p> <p>The below query is supported:</p> <pre><code>Select * From your_content_database.dbo.AllDocs With (NoLock) </code></pre> <p>I will post a query that provides the desired result in a few minutes.</p>
<p>MOSS provides many <a href="http://www.infoq.com/articles/swanson-moss-web-services" rel="nofollow noreferrer">webservices</a> out of the box which make life a little easier. They are always worth exploring.</p> <p>For this particular instance, I think the article, <a href="http://sqlblogcasts.com/blogs/drjohn/archive/2007/11/02/Getting-a-list-of-files-from-a-moss-document-library-using-a-SharePoint-web-service.aspx" rel="nofollow noreferrer"><em>Getting a list of files from a MOSS document library using a SharePoint web service</em></a>, will be of assistance. If this isn't your exact scenario, it will get you on the right track.</p> <p>If the Document service doesn't help you, the Search service will I'm sure. Check the documentation for usage. </p>
26,281
<p>I'm now to this point of my project that I need to design my database (Oracle). Usually for the status and countries tables I don’t use a numeric primary key, for example</p> <pre><code>STATUS (max 6) AC --&gt; Active DE --&gt; Deleted COUNTRIES (total 30) UK --&gt; United Kingdom IT --&gt; Italy GR --&gt; Greece </code></pre> <p>These tables are static, not updated through the application and it's not foreseen to be change in the future so there is no chance having update problems in tables that will use these values as foreign keys.</p> <p>The main table of the application will use status and country (more than once e.g. origin country, destination country) and it is foreseen that 600000 rows will be added per year</p> <p>So my question is, will these VARCHAR(2) keys will have an impact in the performance when querying the join of there 3 tables. Will the first be significantly slower than the second?</p> <pre><code>SELECT m.*, s.status_name, c.country_name FROM main m, status s, countries c WHERE m.status_cd = s.status_cd AND m.country_cd = c.country_cd AND m.status_cd = 'AC' AND m.country_cd = 'UK' SELECT m.*, s.status_name, c.country_name FROM main m, status s, countries c WHERE m.status_cd = s.status_cd AND m.country_cd = c.country_cd AND m.status_cd = 1 AND m.country_cd = 2 </code></pre> <hr> <p>Clarification:</p> <p>Status is not binary ("max 6" next to the table name). The values will probably be:</p> <pre><code>* active * deleted * draft * send * replaced </code></pre> <p>and we need to display the decoded values to the user, so we need the names.</p>
<p>Both the status and country tables are so small that they are going to be memory resident in practice, whether formally stated as such or not. Indeed, except that a foreign key normally requires an index on the referenced primary key field, you might be tempted not to bother with any indexes on the tables.</p> <p>The performance difference between the joins with different types is going to be negligible, and the numeric code will, if anything, be slower since there's 'more' data to store (but it is all so small that it is negligible, again).</p> <p>So, go with the natural codes. All else apart, the SQL in the first example is clearer; the 'UK' and 'AC' are much more meaningful than 1 and 2.</p> <p>In non-Oracle DBMS, you would probably use CHAR(2) for both the status and country code values. Oracle users tend to use VARCHAR2 for everything; I'm not sure whether there is a penalty for using a CHAR(2) column instead, especially since the column values are fixed length. (Under Informix, for instance, a VARCHAR(2) field - a field of up to two characters - would store as 3 bytes, a length (always 2 in your case) and the 2 data bytes. By contrast, a CHAR(2) field would occupy just 2 bytes.)</p>
<p>If 'status' is (and will always be?) a binary active/deleted field why bother with the table at all. It seems like normalization taken to an impractical extreme.</p> <p>It would <em>certainly</em> be quicker, not to mention easier, to simply use a tinyint(1) field and record the active/deleted state as a 1 or 0.</p> <p>This eliminates one of your joins entirely which has got to be a good thing.</p>
41,981
<p>I'm talking about an action game with no upper score limit and no way to verify the score on the server by replaying moves etc. </p> <p>What I really need is the strongest encryption possible in Flash/PHP, and a way to prevent people calling the PHP page other than through my Flash file. I have tried some simple methods in the past of making multiple calls for a single score and completing a checksum / fibonacci sequence etc, and also obfuscating the SWF with Amayeta SWF Encrypt, but they were all hacked eventually.</p> <p>Thanks to StackOverflow responses I have now found some more info from Adobe - <a href="http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_12.html" rel="noreferrer">http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_12.html</a> and <a href="https://github.com/mikechambers/as3corelib" rel="noreferrer">https://github.com/mikechambers/as3corelib</a> - which I think I can use for the encryption. Not sure this will get me around CheatEngine though.</p> <p>I need to know the best solutions for both AS2 and AS3, if they are different.</p> <p>The main problems seem to be things like TamperData and LiveHTTP headers, but I understand there are more advanced hacking tools as well - like CheatEngine (thanks Mark Webster)</p>
<p>This is a classic problem with Internet games and contests. Your Flash code works with users to decide a score for a game. But users aren't trusted, and the Flash code runs on the user's computer. You're SOL. There is nothing you can do to prevent an attacker from forging high scores:</p> <ul> <li><p>Flash is even easier to reverse engineer than you might think it is, since the bytecodes are well documented and describe a high-level language (Actionscript) --- when you publish a Flash game, you're publishing your source code, whether you know it or not.</p></li> <li><p>Attackers control the runtime memory of the Flash interpreter, so that anyone who knows how to use a programmable debugger can alter any variable (including the current score) at any time, or alter the program itself.</p></li> </ul> <p>The simplest possible attack against your system is to run the HTTP traffic for the game through a proxy, catch the high-score save, and replay it with a higher score.</p> <p>You can try to block this attack by binding each high score save to a single instance of the game, for instance by sending an encrypted token to the client at game startup, which might look like:</p> <pre><code>hex-encoding( AES(secret-key-stored-only-on-server, timestamp, user-id, random-number)) </code></pre> <p>(You could also use a session cookie to the same effect).</p> <p>The game code echoes this token back to the server with the high-score save. But an attacker can still just launch the game again, get a token, and then immediately paste that token into a replayed high-score save. </p> <p>So next you feed not only a token or session cookie, but also a high-score-encrypting session key. This will be a 128 bit AES key, itself encrypted with a key hardcoded into the Flash game:</p> <pre><code>hex-encoding( AES(key-hardcoded-in-flash-game, random-128-bit-key)) </code></pre> <p>Now before the game posts the high score, it decrypts the high-score-encrypting-session key, which it can do because you hardcoded the high-score-encrypting-session-key-decrypting-key into the Flash binary. You encrypt the high score with this decrypted key, along with the SHA1 hash of the high score:</p> <pre><code>hex-encoding( AES(random-128-bit-key-from-above, high-score, SHA1(high-score))) </code></pre> <p>The PHP code on the server checks the token to make sure the request came from a valid game instance, then decrypts the encrypted high score, checking to make sure the high-score matches the SHA1 of the high-score (if you skip this step, decryption will simply produce random, likely very high, high scores). </p> <p>So now the attacker decompiles your Flash code and quickly finds the AES code, which sticks out like a sore thumb, although even if it didn't it'd be tracked down in 15 minutes with a memory search and a tracer ("I know my score for this game is 666, so let's find 666 in memory, then catch any operation that touches that value --- oh look, the high score encryption code!"). With the session key, the attacker doesn't even have to run the Flash code; she grabs a game launch token and a session key and can send back an arbitrary high score.</p> <p>You're now at the point where most developers just give up --- give or take a couple months of messing with attackers by:</p> <ul> <li><p>Scrambling the AES keys with XOR operations</p></li> <li><p>Replacing key byte arrays with functions that calculate the key</p></li> <li><p>Scattering fake key encryptions and high score postings throughout the binary.</p></li> </ul> <p>This is all mostly a waste of time. It goes without saying, SSL isn't going to help you either; SSL can't protect you when one of the two SSL endpoints is evil.</p> <p>Here are some things that can actually reduce high score fraud:</p> <ul> <li><p>Require a login to play the game, have the login produce a session cookie, and don't allow multiple outstanding game launches on the same session, or multiple concurrent sessions for the same user.</p></li> <li><p>Reject high scores from game sessions that last less than the shortest real games ever played (for a more sophisticated approach, try "quarantining" high scores for game sessions that last less than 2 standard deviations below the mean game duration). Make sure you're tracking game durations serverside.</p></li> <li><p>Reject or quarantine high scores from logins that have only played the game once or twice, so that attackers have to produce a "paper trail" of reasonable looking game play for each login they create.</p></li> <li><p>"Heartbeat" scores during game play, so that your server sees the score growth over the lifetime of one game play. Reject high scores that don't follow reasonable score curves (for instance, jumping from 0 to 999999). </p></li> <li><p>"Snapshot" game state during game play (for instance, amount of ammunition, position in the level, etc), which you can later reconcile against recorded interim scores. You don't even have to have a way to detect anomalies in this data to start with; you just have to collect it, and then you can go back and analyze it if things look fishy.</p></li> <li><p>Disable the account of any user who fails one of your security checks (for instance, by ever submitting an encrypted high score that fails validation). </p></li> </ul> <p>Remember though that you're only deterring high score fraud here. There's <em>nothing</em> you can do to prevent if. If there's money on the line in your game, someone is going to defeat any system you come up with. The objective isn't to <em>stop</em> this attack; it's to make the attack more expensive than just getting really good at the game and beating it.</p>
<p>Whenever your highscore system is based on the fact that the Flash application sends unencrpyted/unsigned highscore data via the network, that can be intercepted and manipulated/replayed. The answer follows from that: encrypt (decently!) or cryptographically sign highscore data. This, at least, makes it harder for people to crack your highscore system because they'll need to extract the secret key from your SWF file. Many people will probably give up right there. On the other hand, all it takes is a singly person to extract the key and post it somewhere.</p> <p>Real solutions involve more communication between the Flash application and the highscore database so that the latter can verify that a given score is somewhat realistic. This is probably complicated depending on what kind of game you've got.</p>
9,965
<p>How do you calculate the least common multiple of multiple numbers?</p> <p>So far I've only been able to calculate it between two numbers. But have no idea how to expand it to calculate 3 or more numbers.</p> <p>So far this is how I did it </p> <pre><code>LCM = num1 * num2 / gcd ( num1 , num2 ) </code></pre> <p>With gcd is the function to calculate the greatest common divisor for the numbers. Using euclidean algorithm</p> <p>But I can't figure out how to calculate it for 3 or more numbers.</p>
<p>You can compute the LCM of more than two numbers by iteratively computing the LCM of two numbers, i.e.</p> <pre><code>lcm(a,b,c) = lcm(a,lcm(b,c)) </code></pre>
<p>If there's no time-constraint, this is fairly simple and straight-forward:</p> <pre><code>def lcm(a,b,c): for i in range(max(a,b,c), (a*b*c)+1, max(a,b,c)): if i%a == 0 and i%b == 0 and i%c == 0: return i </code></pre>
17,761
<p>I'm interested in finding out why this is used on some Web sites for processing user-initiated search submissions, how it affects the request and response flow, and programmatically why it would be necessary (or beneficial). In an MVC framework it seems difficult to execute since you are injecting another page into the middle of the flow.</p> <p>EDIT:</p> <p>Not advertising related. For instance, most travel sites used to do this, and there were no ads... some banking sites do it too, where there is just a loader that says something like "Please wait while we process your transaction...".</p>
<p>It is often used in long running requests to prevent the web server from timing out the request. With an interstitial page, you are able to continuously refresh the page until you get results back.</p> <p>EDIT:</p> <p>Also, for long running requests, it is beneficial to have a "Loading.." page in order to show the user that something is happening. Without the interstitial page, the request can appear to have hung up if it takes too long.</p>
<p>I believe the vast majority of interstitial pages are there to run advertising.</p>
25,596
<p>On SO 18 Joel mentioned an algorithm that would rank items based on their age and popularity and it's based on gravity. Could someone post this? C# would be lovely, but really any language (well, I can't do LISP) would be fine. </p>
<p>My understanding is that it is approximately the following from another <a href="https://stackoverflow.com/questions/24066/what-formula-should-be-used-to-determine-hot-questions">Jeff Atwood</a> post</p> <pre><code>t = (time of entry post) - (Dec 8, 2005) x = upvotes - downvotes y = {1 if x &gt; 0, 0 if x = 0, -1 if x &lt; 0) z = {1 if x &lt; 1, otherwise x} log(z) + (y * t)/45000 </code></pre>
<p><a href="http://www.mt-soft.com.ar/wordpress/wp-content/plugins/wp-o-matic/cache/0ad4d_reddit_cf_algorithm.png">alt text http://www.mt-soft.com.ar/wordpress/wp-content/plugins/wp-o-matic/cache/0ad4d_reddit_cf_algorithm.png</a></p>
5,232
<p>What is the best way to calculate Age using Flex?</p>
<p>I found an answer at <a href="http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&amp;file=08_Dates_and_times_164_2.html" rel="nofollow noreferrer">the bottom of this page in comments section (which is now offline)</a>. </p> <blockquote> <p><strong>jpwrunyan said on Apr 30, 2007 at 10:10 PM :</strong></p> <blockquote> <p>By the way, here is how to calculate age in years (only) from DOB without needing to account for leap years:</p> </blockquote> </blockquote> <p>With a slight correction by <a href="https://stackoverflow.com/users/210612/fine-wei-lin">Fine-Wei Lin</a>, the code reads</p> <pre><code>private function getYearsOld(dob:Date):uint { var now:Date = new Date(); var yearsOld:uint = Number(now.fullYear) - Number(dob.fullYear); if (dob.month &gt; now.month || (dob.month == now.month &amp;&amp; dob.date &gt; now.date)) { yearsOld--; } return yearsOld; } </code></pre> <blockquote> <blockquote> <p>This handles most situations where you need to calculate age. </p> </blockquote> </blockquote>
<p>You could also do it roughly the same as discussed <a href="https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c" title="Jeff Atwodd&#39;s Question about calculating age in C#">here</a>: (translated to AS3)</p> <pre><code>var age:int = (new Date()).fullYear - bDay.fullYear; if ((new Date()) &lt; (new Date((bDay.fullYear + age), bDay.month, bDay.date))) age--; </code></pre>
6,314
<p>In order to know how many times a pattern exists in current buffer, I do:</p> <pre><code>:%s/pattern-here/pattern-here/g </code></pre> <p>It gives the number of occurrences of the pattern, but is obviously cumbersome and also has the side-effect of setting the 'changed' status.</p> <p>Is there a more elegant way to count?</p>
<p>To avoid the substitution, leave the second pattern empty, and add the “n” flag:</p> <pre><code>:%s/pattern-here//gn </code></pre> <p>This is described as <a href="http://vimdoc.sourceforge.net/htmldoc/tips.html#count-items" rel="noreferrer">an official tip</a>.</p>
<p>vimgrep is your friend here:</p> <pre><code>vimgrep pattern % </code></pre> <p>Shows:</p> <pre><code>(1 of 37) </code></pre>
9,595
<p>We are producing a portable code (win+macOs) and we are looking at how to make the code more rubust as it crashes every so often... (overflows or bad initializations usually) :-(</p> <p>I was reading that Google Chrome uses a process for every tab so if something goes wrong then the program does not crash compleatelly, only that tab. I think that is quite neat, so i might give it a go!</p> <p>So i was wondering if someone has some tips, help, reading list, comment, or something that can help me build more rubust c++ code (portable is always better).</p> <p>In the same topic i was also wondering if there is a portable library for processes (like boost)?</p> <p>Well many Thanks. </p>
<p>I've developed on numerous multi-platform C++ apps (the largest being 1.5M lines of code and running on 7 platforms -- AIX, HP-UX PA-RISC, HP-UX Itanium, Solaris, Linux, Windows, OS X). You actually have two entirely different issues in your post.</p> <ol> <li><p>Instability. Your code is not stable. Fix it. </p> <ul> <li>Use unit tests to find logic problems before they kill you.</li> <li>Use debuggers to find out what's causing the crashes if it's not obvious. </li> <li>Use boost and similar libraries. In particular, the pointer types will help you avoid memory leaks.</li> </ul></li> <li><p>Cross-platform coding.</p> <ul> <li>Again, use libraries that are designed for this when possible. Particularly for any GUI bits.</li> <li>Use standards (e.g. ANSI vs gcc/MSVC, POSIX threads vs Unix-specific thread models, etc) as much as possible, even if it requires a bit more work. Minimizing your platform specific code means less overall work, and fewer APIs to learn.</li> <li>Isolate, isolate, isolate. Avoid in-line #ifdefs for different platforms as much as possible. Instead, stick platform specific code into its own header/source/class and use your build system and #includes to get the right code. This helps keep the code clean and readable.</li> <li>Use the C99 integer types if at all possible instead of "long", "int", "short", etc -- otherwise it will bite you when you move from a 32-bit platform to a 64-bit one and longs suddenly change from 4 bytes to 8 bytes. And if that's ever written to the network/disk/etc then you'll run into incompatibility between platforms.</li> </ul></li> </ol> <p>Personally, I'd stabilize the code first (without adding any more features) and then deal with the cross-platform issues, but that's up to you. Note that Visual Studio has an excellent debugger (the code base mentioned above was ported to Windows just for that reason).</p>
<p>You can always add exception handling to your program to catch these kinds of faults and ignore them (though the details are platform specific) ... but that is very much a two edged sword. Instead consider having the program catch the exceptions and create dump files for analysis.</p> <p>If your program has behaved in an unexpected way, what do you know about your internal state? Maybe the routine/thread that crashed has corrupted some key data structure? Maybe if you catch the error and try to continue the user will save whatever they are working on and commit the corruption to disk?</p>
11,031
<p>I'm looking for some image library that can work with multiple formats (jpg,gif,png), and is fast at displaying the images to the screen.</p> <p>Also, it would be nice if I could specify only part of the image to render to the screen.</p> <p>In the end I want to have lots of images on the screen that I can pan and zoom about.</p> <p>This is for a personal project on my ppc powerbook, and I'd prefer if the library be in c++.</p>
<p><a href="http://freeimage.sourceforge.net/" rel="nofollow noreferrer">FreeImage.</a></p> <p>That's for loading.</p> <p>For displaying, you can either use the FreeImage methods to make a bitmap that you can then display in some control (depending on your UI).</p> <p>For the real hotness in display, you'll then want to use <a href="http://www.opengl.org" rel="nofollow noreferrer">OpenGL</a>.</p> <p>Also, in the meantime, I've discovered <a href="http://cimg.sourceforge.net/" rel="nofollow noreferrer">CImg</a>, which isn't a library so much as a framework for doing lots of common imaging applications and works in C++.</p>
<p><a href="http://www.imagemagick.org/Magick++/" rel="nofollow noreferrer">ImageMagick</a> has libraries in several languages to do what you want.</p>
34,543
<p>I'm opening a new browser window from my site for some of the members. However, some may later close it, or it might have initially failed to open.</p> <p>Is there a snippet of fairly plain Javascript that can be run on each page to confirm if another browser window is open, and if not, to provide a link to re-open it?</p> <p><strong>[clarification:]</strong> The code to check is a window is open would be run on other pages - not just in the same window and URL that opened it. Imagine a user logging in, the window (tries to) open, and then they surf around in the same tab/window (or others) for some time before they close the 2nd window (or it never opened) - I want to be able to notice the window has been closed some time after the initial attempt at opening/after it's closed, so I'm not sure that checking the javascript's return from window.open() (with popup_window_handle.closed) is easily used, or indeed possible.</p>
<p>This <a href="http://www.irt.org/articles/js205/index.htm" rel="nofollow noreferrer">excellent, comprehensive article</a> <em>("Almost complete control of pop-up windows")</em> should answer all your questions about javascript popup windows.</p> <p><em>"JavaScript 1.1 also introduced the window <strong>closed</strong> property. Using this property, it is possible to detect if a window has been opened and subsequently closed. We can use this to load a page directly into the opener window if it still open for JavaScript 1.1 enabled browsers:"</em></p> <pre><code>&lt;script language="JavaScript"&gt;&lt;!-- function open_main(page) { window_handle = window.open(page,'main'); return false; } //--&gt;&lt;/script&gt; &lt;script language="JavaScript1.1"&gt;&lt;!-- function open_main(page) { if (opener &amp;&amp; !opener.closed) { opener.location.href = page; } else { window_handle = window.open(page,'main'); } return false; } //--&gt;&lt;/script&gt; &lt;a href="example.htm" onClick="return open_main('example.htm')"&gt;example.htm&lt;/a&gt; </code></pre> <p><strong>Addition:</strong> You can get the window handle back in another page by referring to the popup's name this way:</p> <pre><code>window_handle = window.open(page,'myPopupName'); </code></pre> <p>I guess in your case you should think about a consistent way to create all the names of the popup windows throughout the entire application.</p>
<p>There is no universal way to check it as each pop-up blocker has a different behaviour. For example, Opera will not shown the pop-up but the widow.closed will return false as behind the scene Opera keep a shadow copy of the blocked window, just in case the user would like to see it anyway.</p>
27,292
<p>I have Visual Studio 2008 with SP1 installed and it is crashing when I'm using lambda expressions in the Moq Framework.</p> <p>At first I thought the problem was Resharper...but now that I have uninstalled it, VS 2008 still crashes. I'm able to replicate the issue every time.</p> <p>I'm thinking perhaps it may be some other plugin that is causing the issue rather than VS 2008...but I can't be sure of that.</p> <p>So what I'm trying to find is where Visual Studio logs the crashes that occur?</p> <p>Unfortunately I'm unable to find it...does anyone out there know if it exists and if so where to look?</p> <p>Thanks in advance!</p>
<p>Just a few days ago, I learned about <a href="http://blogs.msdn.com/saraford/archive/2008/11/27/did-you-know-there-s-a-way-to-have-visual-studio-log-its-activity-for-troubleshooting-366.aspx" rel="noreferrer"><code>devenv.exe</code>'s <code>/log</code> switch</a>. I suggest you give that a try.</p>
<p>I'd suggest using WinDbg to run an instance of VS, and when it crashes look at managed and unmanaged callstacks. </p>
43,156
<p>I'm in need of a macro that will enter data into a webpage search field and than copy the results to excel.</p>
<p>It's just a simple "File Open". No need for a macro.</p> <p>Excel can open URLs directly. If the URL contains any tables, those will be formatted appropriately.</p> <p>Try this: </p> <ul> <li>Run Excel</li> <li>File | Open</li> <li>Type <code>http://finance.yahoo.com/q?s=MSFT</code> as the file name</li> <li>Ignore the warning</li> </ul>
<p>if using excel is not a constraint in your question.. i.e. you can use other software to get the job done.. you should check out Google Spreadsheet.. its a lot more webfriendly... has functions that can retrieve some page.. or alternatively google for something nd then put the results in your table.. <a href="http://spreadsheets.google.com/" rel="nofollow noreferrer">http://spreadsheets.google.com/</a><br> after that you can save the file in .xls format and bring it to any other platform</p>
32,529
<p>I can't find documentation for it, even on MSDN...</p>
<p>It's not Win32; it's MFC. Ordinarily, a Win32 control raises events by sending a message to its parent window. However, if you've got your own class derived from one of MFC's wrappers (e.g. you've wrapped CTreeCtrl with CMyFunkyTreeCtrl), you might want to handle these events in the derived class.</p> <p>MFC uses these reflection messages to bounce the event back to the class itself, where your derived class can see them.</p> <p>Look at <a href="http://msdn.microsoft.com/en-us/library/eeah46xd.aspx" rel="noreferrer">TN062: Message Reflection for Windows Controls (MFC)</a> for more information.</p>
<p>Some reasoning here:<br> <a href="http://www.tech-archive.net/Archive/VC/microsoft.public.vc.language/2005-08/msg00589.html" rel="nofollow noreferrer">http://www.tech-archive.net/Archive/VC/microsoft.public.vc.language/2005-08/msg00589.html</a></p>
24,626
<p>I have created the following style for a listbox that will have an image displayed next to some text:</p> <pre><code>&lt;Style x:Key="ImageListBoxStyle" TargetType="{x:Type ListBox}"&gt; &lt;Setter Property="SnapsToDevicePixels" Value="true"/&gt; &lt;Setter Property="BorderThickness" Value="1"/&gt; &lt;Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/&gt; &lt;Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/&gt; &lt;Setter Property="ScrollViewer.CanContentScroll" Value="True"/&gt; &lt;Setter Property="ItemContainerStyle"&gt; &lt;Setter.Value&gt; &lt;!-- Simple ListBoxItem - This is used for each Item in a ListBox. The item's content is placed in the ContentPresenter --&gt; &lt;Style TargetType="{x:Type ListBoxItem}"&gt; &lt;Setter Property="SnapsToDevicePixels" Value="true"/&gt; &lt;Setter Property="OverridesDefaultStyle" Value="true"/&gt; &lt;Setter Property="VerticalContentAlignment" Value="Center"/&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type ListBoxItem}"&gt; &lt;Grid SnapsToDevicePixels="true"&gt; &lt;Border x:Name="Border"&gt; &lt;Grid Height="40"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Image x:Name="DisplayImage" Source="{Binding Path=ThumbnailImage}" Height="30" Width="30" Grid.Column="0"/&gt; &lt;ContentPresenter x:Name="DisplayText" HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.Column="1"/&gt; &lt;!--&lt;ContentPresenter.Resources&gt; &lt;Style TargetType="{x:Type TextBlock}"&gt; &lt;Setter Property="Foreground" Value="Black"/&gt; &lt;/Style&gt; &lt;/ContentPresenter.Resources&gt;--&gt; &lt;!--Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=DisplayMemberPath, Converter={StaticResource myDisplayMemberConverter}}"--&gt; &lt;!--&lt;Label x:Name="Text" Content="{Binding Path=FullNameAndTitle}" Foreground="Black" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" VerticalContentAlignment="Center" HorizontalAlignment="Stretch" Grid.Column="1" Height="40"/&gt;--&gt; &lt;/Grid&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsSelected" Value="true"&gt; &lt;!--&lt;Setter Property="FontWeight" Value="Bold" TargetName="DisplayText"/&gt;--&gt; &lt;!--&lt;Setter Property="Style" Value="{StaticResource SelectedTextStyle}" TargetName="DisplayText"/&gt;--&gt; &lt;Setter Property="Background" Value="DarkBlue" TargetName="Border"/&gt; &lt;Setter Property="Width" Value="40" TargetName="DisplayImage"/&gt; &lt;Setter Property="Height" Value="40" TargetName="DisplayImage"/&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type ListBox}"&gt; &lt;Grid&gt; &lt;Border x:Name="Border" Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="{TemplateBinding BorderThickness}"&gt; &lt;Grid&gt; &lt;ScrollViewer Margin="1,1,1,1" Focusable="false" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"&gt; &lt;StackPanel IsItemsHost="true"/&gt; &lt;/ScrollViewer&gt; &lt;/Grid&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsGrouping" Value="true"&gt; &lt;Setter Property="ScrollViewer.CanContentScroll" Value="false"/&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>I have to use the contentpresenter as I am filtering what is displayed (text wise) using the DisplayMemberPath of the ListBox itself.</p> <p>All I want to do is set the FontWeight to Bold and the Foreground to White when an item is selected in the ListBox.</p> <p>Has anyone encountered a problem like this? I have looked at some related questions but people have been able to use a TextBlock to get around their issues I can't unfortunately.</p> <p>Any info ppl can give will be appreciated.</p> <p>Cheers</p>
<p>There is also another way. You can add in your <code>ContentPresenter</code> this attribute</p> <pre><code>TextBlock.Foreground="YourColour" </code></pre> <p>In this case you can also use animations over that property.</p>
<pre><code> &lt;Storyboard x:Key="Storyboard1"&gt; &lt;ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)" Storyboard.TargetName="myContentPresenter"&gt; &lt;EasingColorKeyFrame KeyTime="0" Value="Black"/&gt; &lt;EasingColorKeyFrame KeyTime="0:0:0.2" Value="White"/&gt; &lt;/ColorAnimationUsingKeyFrames&gt; &lt;/Storyboard&gt; </code></pre>
31,047
<p>I have found ASP.Net PageMethods very handy and easy to use, but I have just started developing using MVC and am not sure how to use them?</p> <p>What is the equivalent of <code>PageMethods.MyFunction()</code> in MVC where MyFunction is a Controller action?</p> <p>I know I can use the <code>Json</code> function to return a value, but how do I call the action from the client?</p>
<blockquote> <p>I know I can use the Json function to return a value, but how do I call the action from the client?</p> </blockquote> <p>I think you're looking for either <a href="http://docs.jquery.com/Ajax/jQuery.getJSON" rel="noreferrer">getJSON</a></p> <pre><code>$.getJSON("/controller/action", function(json) { alert("JSON Data: " + json.users[3].name); }); </code></pre> <p>or the <a href="http://docs.jquery.com/Ajax/jQuery.ajax" rel="noreferrer">ajax</a> jQuery method.</p> <p>Either can call an action and get JSON data back from ASP.NET MVC very easily.</p>
<p>I don't think you need page methods. Page methods in asp.net are a way to expose methods in the page class to your client-side code.</p> <p>In MVC, you don't have a page class, so you can just issue an XHR to a url (../controller/action/params, or whatever), and return JSON from the action.</p> <p><strong>Update</strong>: After re-reading your question, it sounds like you want to know <em>how</em> to issue an XHR from the client. In raw javascript, you can just use the XMLHttpRequest object, but whatever JS library you are using probably has a nicer wrapper. jQuery's, for instance, is <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options" rel="nofollow noreferrer">here</a></p>
48,276
<p>When working with WCF services, is it better to create a new instance of the service every time you use it? Or is it better to create one and re-use it? Why is either approach better? Is it the same for asynchronous proxies? </p>
<p>in addition to the things Guy Starbuck mentioned a key factor would be the security model you're using (in conjunction with the session requirements) - if you don't re-use your proxy, you can't re-use a security sessions. </p> <p>This means that the client would have to authenticate itself with each call which is wasteful. </p> <p>If, however, you decide this is what you wish to do, make sure to configure the client to not establish a security context (as you will never use it), this will save you a couple of roundtrips to the server :-)</p>
<p>There is a corollary here to Server Activated Objects in .NET Remoting (one of the technologies that is replaced by WCF), which have two modes, "Single Call" (stateless) and "Singleton" (stateful).</p> <p>The approach you take in WCF should be based on your performance and scaling requirements in conjunction with the needs of your consumers, as well as server-side design constraints.</p> <p>If you have to maintain state between calls to the service, then you will obviously want to have a stateful instance, but if you don't you should probably implement it so that it is static, which should scale better (you can more easily load balance, etc).</p>
42,940
<p>I understand benefits of dependency injection itself. Let's take Spring for instance. I also understand benefits of other Spring featureslike AOP, helpers of different kinds, etc. I'm just wondering, what are the benefits of XML configuration such as:</p> <pre><code>&lt;bean id="Mary" class="foo.bar.Female"&gt; &lt;property name="age" value="23"/&gt; &lt;/bean&gt; &lt;bean id="John" class="foo.bar.Male"&gt; &lt;property name="girlfriend" ref="Mary"/&gt; &lt;/bean&gt; </code></pre> <p>compared to plain old java code such as:</p> <pre><code>Female mary = new Female(); mary.setAge(23); Male john = new Male(); john.setGirlfriend(mary); </code></pre> <p>which is easier debugged, compile time checked and can be understood by anyone who knows only java. So what is the main purpose of a dependency injection framework? (or a piece of code that shows its benefits.)</p> <hr> <p><strong>UPDATE:</strong><br/> In case of</p> <pre><code>IService myService;// ... public void doSomething() { myService.fetchData(); } </code></pre> <p>How can IoC framework guess which implementation of myService I want to be injected if there is more than one? If there is only one implementation of given interface, and I let IoC container automatically decide to use it, it will be broken after a second implementation appears. And if there is intentionally only one possible implementation of an interface then you do not need to inject it.</p> <p>It would be really interesting to see small piece of configuration for IoC which shows it's benefits. I've been using Spring for a while and I can not provide such example. And I can show single lines which demonstrate benefits of hibernate, dwr, and other frameworks which I use.</p> <hr> <p><strong>UPDATE 2:</strong><br/> I realize that IoC configuration can be changed without recompiling. Is it really such a good idea? I can understand when someone wants to change DB credentials without recompiling - he may be not developer. In your practice, how often someone else other than developer changes IoC configuration? I think that for developers there is no effort to recompile that particular class instead of changing configuration. And for non-developer you would probably want to make his life easier and provide some simpler configuration file.</p> <hr> <p><strong>UPDATE 3:</strong><br/></p> <blockquote> <p>External configuration of mapping between interfaces and their concrete implementations </p> </blockquote> <p>What is so good in making it extenal? You don't make all your code external, while you definitely can - just place it in ClassName.java.txt file, read and compile manually on the fly - wow, you avoided recompiling. Why should compiling be avoided?!</p> <blockquote> <p>You save coding time because you provide mappings declaratively, not in a procedural code </p> </blockquote> <p>I understand that sometimes declarative approach saves time. For example, I declare only once a mapping between a bean property and a DB column and hibernate uses this mapping while loading, saving, building SQL based on HSQL, etc. This is where the declarative approach works. In case of Spring (in my example), declaration had more lines and had the same expressiveness as corresponding code. If there is an example when such declaration is shorter than code - I would like to see it.</p> <blockquote> <p>Inversion of Control principle allows for easy unit testing because you can replace real implementations with fake ones (like replacing SQL database with an in-memory one)</p> </blockquote> <p>I do understand inversion of control benefits (I prefer to call the design pattern discussed here as Dependency Injection, because IoC is more general - there are many kinds of control, and we are inverting only one of them - control of initialization). I was asking why someone ever needs something other than a programming language for it. I definitely can replace real implementations with fake ones using code. And this code will express same thing as configuration - it will just initialize fields with fake values.</p> <pre><code>mary = new FakeFemale(); </code></pre> <p>I do understand benefits of DI. I do not understand what benefits are added by external XML configuration compared to configuring code that does the same. I do not think that compiling should be avoided - I compile every day and I'm still alive. I think configuration of DI is bad example of declarative approach. Declaration can be useful if is declared once AND is used many times in different ways - like hibernate cfg, where mapping between bean property and DB column is used for saving, loading, building search queries, etc. Spring DI configuration can be easily translated to configuring code, like in the beginning of this question, can it not? And it is used only for bean initialization, isn't it? Which means a declarative approach does not add anything here, does it?</p> <p>When I declare hibernate mapping, I just give hibernate some information, and it works based on it - I do not tell it what to do. In case of spring, my declaration tells spring exactly wht to do - so why declare it, why not just do it?</p> <hr> <p><strong>LAST UPDATE:</strong><br/> Guys, a lot of answers are telling me about dependency injection, which I KNOW IS GOOD. The question is about purpose of DI configuration instead of initializing code - I tend to think that initializing code is shorter and clearer. The only answer I got so far to my question, is that it avoids recompiling, when the configuration changes. I guess I should post another question, because it is a big secret for me, why compiling should be avoided in this case.</p>
<p>For myself one of the main reasons to use an IoC (and make use of external configuration) is around the two areas of:</p> <ul> <li>Testing</li> <li>Production maintenance</li> </ul> <p><strong>Testing</strong></p> <p>If you split your testing into 3 scenarios (which is fairly normal in large scale development):</p> <ol> <li>Unit testing</li> <li>Integration testing</li> <li>Black box testing</li> </ol> <p>What you will want to do is for the last two test scenarios (Integration &amp; Black box), is not recompile any part of the application.</p> <p>If any of your test scenarios require you to change the configuration (ie: use another component to mimic a banking integration, or do a performance load), this can be easily handled (this does come under the benefits of configuring the DI side of an IoC though.</p> <p>Additionally if your app is used either at multiple sites (with different server and component configuration) or has a changing configuration on the live environment you can use the later stages of testing to verify that the app will handle those changes.</p> <p><strong>Production</strong></p> <p>As a developer you don't (and should not) have control of the production environment (in particular when your app is being distributed to multiple customers or seperate sites), this to me is the real benefit of using both an IoC and external configuration, as it is up to the infrastructure/production support to tweak and adjust the live environment without having to go back to developers and through test (higher cost when all they want to do is move a component).</p> <p><strong>Summary</strong></p> <p>The main benefits that external configuration of an IoC come from giving others (non-developers) the power to configure your application, in my experience this is only useful under a limited set of circumstances:</p> <ul> <li>Application is distributed to multiple sites/clients where environments will differ.</li> <li>Limited development control/input over the production environment and setup.</li> <li>Testing scenarios.</li> </ul> <p>In practice I've found that even when developing something that you do have control over the environment it will be run on, over time it is better to give someone else the capabilities to change the configuration:</p> <ul> <li>When developing you don't know when it will change (the app is so useful your company sells it to someone else).</li> <li>I don't want to be stuck with changing the code every time a slight change is requested that could have been handled by setting up and using a good configuration model. </li> </ul> <p><em>Note: Application refers to the complete solution (not just the executable), so all files required for the application to run</em>.</p>
<p>One of the most appealing reasons is the "<a href="http://en.wikipedia.org/wiki/Hollywood_Principle" rel="nofollow noreferrer">Hollywood principle</a>": don't call us, we'll call you. A component is not required to do the lookups to other components and services itself; instead they are provided to it automatically. In Java, this means that it is no longer necessary to do JNDI lookups inside the component.</p> <p>It is also lots easier to unit test a component in isolation: instead of giving it an actual implementation of the components it needs, you simply use (possibly auto generated) mocks.</p>
16,005
<p>Does anyone know of an RTF control that can be used on Linux/Windows/Mac? It's unfortunate that I have to mention it, but it actually has to be able to save and open rtf files... unlike wxWidgets wxRichTextCtrl for instance.</p> <p>Edit: Thanks to HappySmileMan for his reply. Better still if it's more of a standalone and not a part of a large library that it would depend on.</p> <p>Edit: ... and it doesn't look like it can open rtf files... ugh.</p>
<p>RTF is simply not that common; it's a messy format controlled by Microsoft, basically a text dump of the .doc format. The only open source RTF implementations I know of are in Abiword, OpenOffice, and KWord. All are cross-platform, but none probably qualify as "controls" to your liking (though abiword has a bonobo interface, and KWord has a KPart, so they can be embedded, albeit in a heavyweight fashion).</p>
<p>If I understand the question correctly, the feature you are looking for is in the Qt toolkit.</p> <p>Some info on this can be found at <a href="https://doc.qt.io/qt-5/richtext.html" rel="nofollow noreferrer">https://doc.qt.io/qt-5/richtext.html</a></p>
10,360
<p>Does anyone know of an algorithm that I could use to find an "interesting" representative thumbnail for a video? </p> <p>I have say 30 bitmaps and I would like to choose the most representative one as the video thumbnail. </p> <p>The obvious first step would be eliminate all black frames. Then perhaps look for the "distance" between the various frames and choose something that is close to the avg.</p> <p>Any ideas here or published papers that could help out? </p>
<p>If the video contains structure, i.e. several shots, then the standard techniques for video summarisation involve (a) shot detection, then (b) use the first, mid, or nth frame to represent each shot. See [1].</p> <p>However, let us assume you wish to find an interesting frame in a single continuous stream of frames taken from a single camera source. I.e. a shot. This is the "key frame detection" problem that is widely discussed in IR/CV (Information Retrieval, Computer Vision) texts. Some illustrative approaches:</p> <ul> <li>In [2] a mean colour histogram is computed for all frames and the key-frame is that with the closest histogram. I.e. we select the best frame in terms of it's colour distribution.</li> <li>In [3] we assume that camera stillness is an indicator of frame importance. As suggested by Beds, above. We pick the still frames using optic-flow and use that.</li> <li>In [4] each frame is projected into some high dimensional content space, we find those frames at the corners of the space and use them to represent the video.</li> <li>In [5] frames are evaluated for importance using their length and novelty in content space.</li> </ul> <p>In general, this is a large field and there are lots of approaches. You can look at the academic conferences such as The International Conference on Image and Video Retrieval (CIVR) for the latest ideas. I find that [6] presents a useful detailed summary of video abstraction (key-frame detection and summarisation).</p> <p>For your "find the best of 30 bitmaps" problem I would use an approach like [2]. Compute a frame representation space (e.g. a colour histogram for the frame), compute a histogram to represent all frames, and use the frame with the minimum distance between the two (e.g. pick a distance metric that's best for your space. I would try Earth Mover's Distance).</p> <ol> <li>M.S. Lew. Principles of Visual Information Retrieval. Springer Verlag, 2001. </li> <li>B. Gunsel, Y. Fu, and A.M. Tekalp. Hierarchical temporal video segmentation and content characterization. Multimedia Storage and Archiving Systems II, SPIE, 3229:46-55, 1997. </li> <li>W. Wolf. Key frame selection by motion analysis. In IEEE International Conference on Acoustics, Speech, and Signal Processing, pages 1228-1231, 1996. </li> <li>L. Zhao, W. Qi, S.Z. Li, S.Q. Yang, and H.J. Zhang. Key-frame extraction and shot retrieval using Nearest Feature Line. In IW-MIR, ACM MM, pages 217-220, 2000. </li> <li>S. Uchihashi. Video Manga: Generating semantically meaningful video summaries. In Proc. ACM Multimedia 99, Orlando, FL, Nov., pages 383-292, 1999. </li> <li>Y. Li, T. Zhang, and D. Tretter. An overview of video abstraction techniques. Technical report, HP Laboratory, July 2001. </li> </ol>
<p>Wow, what a great question - I guess a second step would be to iteratively remove frames where there's little or no change between it and it's successors. But all you're really doing there is reducing the set of <em>potentially</em> interesting frames. How exactly you determine "interestingness" is the special sauce I suppose as you don't have the user interaction statistics to rely on like Flickr does.</p>
36,397
<p>In the same way that you can use JSON in javascript? At least the static properties?</p> <p>Or maybe even for hash-table streaming?</p> <p>Is it oversimplistic about hoping to find something like </p> <p>Object.Serialize(stream) where stream is a file, overrideable with your choice of other likely candidate targets, using some default format, say XML?</p> <p>With Object obj = stream.Deserialize() ...</p>
<p>Java supports this with the <a href="http://java.sun.com/products/jfc/tsc/articles/persistence4/" rel="nofollow noreferrer">XMLEncoder</a> since 1.4. The format is quite compact and XMLEncoder allows to override the serialization of specific object classes, so you can use the default where it fits and do whatever you want to elsewhere.</p>
<p>I suggest you look at <a href="http://code.google.com/p/xstream-dot-net/" rel="nofollow noreferrer">XStream for .Net</a>. I haven't used that variant, but found the original XStream quite straightforward to use in Java.</p>
46,687
<p>A lot of my C# code follows this pattern:</p> <pre><code>void foo(string param1, string param2, string param3) { try { // do something... } catch(Exception ex) { LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message)); } } </code></pre> <p>Is there a way in .NET to get a Key/Value list of the parameters to a function so that I can call another function to construct my error logging string? OR Do you have a more generic / better way of doing this?</p>
<p>You could use Reflection and the convention that you must pass the parameters to the LogError with the right order:</p> <pre><code>private static void MyMethod(string s, int x, int y) { try { throw new NotImplementedException(); } catch (Exception ex) { LogError(MethodBase.GetCurrentMethod(), ex, s, x, y); } } private static void LogError(MethodBase method, Exception ex, params object[] values) { ParameterInfo[] parms = method.GetParameters(); object[] namevalues = new object[2 * parms.Length]; string msg = "Error in " + method.Name + "("; for (int i = 0, j = 0; i &lt; parms.Length; i++, j += 2) { msg += "{" + j + "}={" + (j + 1) + "}, "; namevalues[j] = parms[i].Name; if (i &lt; values.Length) namevalues[j + 1] = values[i]; } msg += "exception=" + ex.Message + ")"; Console.WriteLine(string.Format(msg, namevalues)); } </code></pre>
<p>There are scenarios of a few parameters or Large number of parameters...</p> <ol> <li><p>Few parameters, without much ado, better write them as part of the logging/exception message.</p></li> <li><p>In large parameters, a multi-layer application would be using ENTITIES ( like customer, CustomerOrder...) to transfer data between layers. These entities should implement override ToString() methods of class Object, there by, </p></li> </ol> <p>Logmessage(" method started " + paramObj.ToString()) would give the list of data in the object.. Any opinions? :) </p> <p>thanks</p>
16,440
<p>Setup is following: Drupal project, one svn repo with trunk/qa/production-ready branches, vhosts for every branch, post-commit hook that copies files from repository to docroots.</p> <p>Problem is following: Drupal website often relies not only on source code but on DB data too (node types, their settings, etc.). </p> <p>I'm looking for solution to make this changes versionable. But not like 'diffing' all data in database, instead something like fixtures in unit tests.</p> <p>Fixture-like scripts with SQL data and files for content that should be versionable and be applied after main post-commit hook.</p> <p>Is there anything written for that purpose, or maybe it would be easy to adapt some kind of build tool (like Apache Ant) or unit testing framework. And it would be very great, if this tool know about drupal, so in scripts I can do things like <code>variable_set()</code>, <code>drupal_execute()</code>.</p> <p>Any ideas? Or should I start coding right now instead of asking this? :)</p>
<p>It sounds like you've already got some infrastructure there that you've written.</p> <p>So I'd start coding! There's not anything that I'm aware of thats especially good for this at the moment. And if there is, I imagine that it would take some effort to get it going with your existing infrastructure. So starting coding seems the way to go.</p> <p>My approach to this is to use sql patch files (files containing the sql statements to upgrade the db schema/data) with a version number at the start of the filename. The database then contains a table with config info in (you may already have this) that includes info on which version the database is at.</p> <p>You can then take a number of approaches to automatically apply the patch. One would be a script that you call from the postcommit that checks the version the database is at, and then checks to see if the latest version you have a patch for is newer than the version the db is at, and applies it/them (in order) if so.</p> <p>The db patch should always finish by updating aforementioned the version number in the config table.</p> <p>This approach can be extended to include the ability to set up a new database based on a full dump file and then applying any necessary patches to it to upgrade it as well.</p>
<blockquote> <p>My approach to this is to use sql patch files (files containing the sql statements to upgrade the db schema/data) with a version number at the start of the filename. </p> </blockquote> <p>I was thinking of file (xml or something) with needed DB structure, and tool that applies necessary changes.</p> <p>And yes, after more research I agreee: it will be easier to code it than to adapt some other solutions. Though some routines from <a href="http://drupal.org/project/simpletest" rel="nofollow noreferrer">simpletest</a> drupal module will be helpful, I think.</p>
49,450
<ul> <li>The GoDiagram object model has a GoDocument. </li> <li>GoViews have a reference to a GoDocument.</li> <li>If the user does any modification on the diagramming surface, a GoDocument.Changed event is raised with the relevant information in the event arguments.</li> </ul> <p>I would like to be notified when some user-actions happen, so that I can confer with my Controller (disallow/cancel it if need be) and then issue view-update orders from there that actually modify the <strong>Northwoods GoDiagram</strong> third party component.<br> The Changed event is a notification that something just happened (past tense) - Doing all of the above in the event handler results in a .... (<em>wait for it</em>)... StackOverflowException. (GoDocument.Changed handler > Updates GoDocument > Firing new Changed events.. )</p> <p>So question, how do I get a BeforeEditing or BeforeResizing kind of notification model in GoDiagrams? Has anyone who's been there lived to tell a tale?</p>
<p>JFYI... The component-vendor recommendation is to subclass and override appropriate methods for this. Override the bool CanXXX() method, raise a cancelable custom event. If the subscriber returns false, bail out (<strong>return false to abort the user action</strong>) of CanXXX. <strong>No built-in mechanism for this in GoDiagrams.</strong></p> <blockquote> <p>For example, you could define a CustomView.ObjectResizing cancelable event. In your override of GoToolResizing.CanStart, you can raise that event. If the CancelEventArgs.Cancel property becomes true, you would have CanStart() return false.</p> </blockquote> <p>Source <a href="http://www.nwoods.com/forum/forum_posts.asp?TID=2745" rel="nofollow noreferrer">http://www.nwoods.com/forum/forum_posts.asp?TID=2745</a></p>
<p>The event arguments (GoChangedEventArgs) for the change event has a property IsBeforeChanging which indicates whether the change event was raised from the "RaiseChanging" method (true), or the RaiseChanged (false). That should tell you whether the change has occurred yet, but I know of no way to cancel it. </p> <p>The best I can suggest is instead of checking if the change is allowed and performing it, check if the change is <em>not</em> allowed, and if it isn't call the "Undo" method on the arguments in the change event. So essentially:</p> <pre><code>OnChanged(GoChangedEventArgs e) { if(NotAllowed) { e.Undo(); } } </code></pre>
13,696
<p>I have a wrapper around a C++ function call which I call from C# code. How do I attach a debugger in Visual Studio to step into the native C++ code?</p> <p>This is the wrapper that I have which calls GetData() defined in a C++ file:</p> <pre><code> [DllImport("Unmanaged.dll", CallingConvention=CallingConvention.Cdecl, EntryPoint = "GetData", BestFitMapping = false)] public static extern String GetData(String url); </code></pre> <p>The code is crashing and I want to investigate the root cause.</p> <p>Thanks, Nikhil</p>
<p>Check the Debug tab on your project's properties page. There should be an "Enable unmanaged code debugging" checkbox. This worked for me when we developed a new .NET UI for our old c++ DLLs.</p> <p>If your unmanaged DLL is being built from another project (for a while ours were being built using VS6) just make sure you have the DLL's pdb file handy for the debugging.</p> <p>The other approach is to use the C# exe as the target exe to run from the DLL project, you can then debug your DLL normally.</p>
<p>To anyone using WinDbg:</p> <p>1>Setup symbols</p> <p>Look at these commands. (Help: in console .hh &lt; command> )</p> <pre><code>.sympath .sympath+ .symfix </code></pre> <p>2>Set up source path</p> <pre><code>.srcpath </code></pre> <p>3>Load SOS extention to debug managed / mixed mode programs.</p> <p>(Make sure you have extention path setup correctly)</p> <p>Add Microsoft.NET\Framework\v2.0.50727 for x86 using-</p> <pre><code>.extpath </code></pre> <p>Set a breakpoint for the clr to load.</p> <pre><code>sxe ld:mscorwks </code></pre> <p>(F5 / g) (Wait for ModLoad BP on mscorwks.dll)</p> <p>Make sure you dont have a duplicate sos extention already loaded. See:</p> <pre><code>.chain </code></pre> <p>Now we're ready to load the sos extention. :)</p> <pre><code>.loadby sos mscorwks </code></pre> <p>4> Reload all the symbols..</p> <pre><code>.reload </code></pre> <p>Now you're all set :)</p> <p>(YMMV)</p>
8,224
<p>I've got an SQL query that looks like this:</p> <pre><code>INSERT INTO DB..incident ( incident_number --nvarchar(10) ) VALUES ( N'I?' ) </code></pre> <p>What does the ? do in the value statement?</p> <p>EDIT:: Turns out there's some funny business via triggers and custom datatypes that occur on insert (we've got a bit of a messed up DB.) Given normal settings I've marked the answer appropriately.</p>
<p>At the risk of sounding flippant... Nothing... It puts an I? into the field... Try this... </p> <pre><code>DECLARE @TestTable TABLE (test NVARCHAR(10)) INSERT INTO @TestTable ( test ) VALUES ( N'I?' ) SELECT * FROM @TestTable </code></pre>
<p>The question in my mind when I read this was, what does the N do?</p> <p>In Oracle, N before a character string literal indicates that the string should be encoded in the national (i.e. localized) character set rather than the default character set for the database.</p> <p>So as the others have said, you're inserting the string 'I?' into the column. However, it may be encoded using a different character set (although since these characters are in the standard ASCII range the result will probably be the same).</p>
36,220
<p>The ASP.NET calendar always displays 6 weeks of dates in a 7x6 grid. My problem is that the first day of the target month does <em>not necessarily</em> appear in the first row... in some cases, the entire first row displays dates from the previous month. In other cases, the entire last row displays dates from the next row. Is there a reliable way to query the calendar object to determine the 42-day range that would be rendered for a specific month/year?</p> <p>For example, consider June 2008 and Feb 2009:</p> <p><a href="http://img371.imageshack.us/img371/2290/datesmq5.png">Notice that the first week contains ONLY dates from prior month http://img371.imageshack.us/img371/2290/datesmq5.png</a></p> <p>I assume that the calendar tries to avoid bunching all of the "other month" dates at either the top or bottom of the grid, and therefore puts the first of the target month on the 2nd row. I am looking for an easy way to determine that the displayed range for June 2008 is May 25 - July 5, for instance.</p>
<p>Looking at the public members exposed by the ASP.NET Calendar control I do not believe that this information is something that you can just get from the calendar control. </p> <p>You have a few options as "workarounds" to this though, although not nice....but they would work.</p> <ol> <li>You could manually calculate the first week values</li> <li>You can handle the "day render" event to handle the binding of the individual days, and record min/max values.</li> </ol> <p>Granted neither is elegant, but AFAIK it is the only real option</p> <p><strong>Edit</strong></p> <p>After discussion in the comments, another option is a modified version of my second option above. Basically the first time Day Render is called, get the block of data for the next 42 days, then you can simply search the list for the proper day value to display on future calls to DayRender, avoiding a DB hit for each day. Doing this is another "non-elegant" solution, but it works, and reduces a bit of load on the DB, but introduces some overhead on the application side.</p> <p>It will be important here to define well structured page level properties to hold the items during the binding events, but to ensure that if a month changed, etc that it wasn't loaded incorrectly etc.</p>
<p>see this one.</p> <p><a href="https://stackoverflow.com/questions/2514065/how-to-remove-the-last-week-of-a-calendar/6145946#6145946">How to Remove the Last Week Of a Calendar</a></p>
32,903
<p>I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#.</p> <p>In my C++ source I can write</p> <p>LOGERR("Some error"); or LOGERR("Error with inputs %s and %d", stringvar, intvar);</p> <p>The macro &amp; supporting library code then passes the (possibly varargs) formatted message into a database along with the source file, source line, user name, and time. The same data is also stuffed into a data structure for later reporting to the user.</p> <p>Does anybody have C# code snippets or pointers to examples that do this basic error reporting/logging?</p> <p><strong>Edit:</strong> At the time I asked this question I was really new to .NET and was unaware of System.Diagnostics.Trace. System.Diagnostics.Trace was what I needed at that time. Since then I have used log4net on projects where the logging requirements were larger and more complex. Just edit that 500 line XML configuration file and log4net will do everything you will ever need :)</p>
<p>Lots of log4net advocates here so I'm sure this will be ignored, but I'll add my own preference:</p> <pre><code>System.Diagnostics.Trace </code></pre> <p>This includes listeners that listen for your <code>Trace()</code> methods, and then write to a log file/output window/event log, ones in the framework that are included are <code>DefaultTraceListener</code>, <code>TextWriterTraceListener</code> and the <code>EventLogTraceListener</code>. It allows you to specify levels (Warning,Error,Info) and categories.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.trace.aspx" rel="noreferrer">Trace class on MSDN</a><br> <a href="https://stackoverflow.com/questions/286060/what-do-i-need-to-change-to-alllow-my-iis7-asp-net-3-5-application-to-create-an/7848414#7848414">Writing to the Event Log in a Web Application</a><br> <a href="http://www.anotherchris.net/log4net/udptracelistener-a-udp-tracelistener-compatible-with-log4netlog4j/" rel="noreferrer">UdpTraceListener - write log4net compatible XML messages to a log viewer such as log2console</a></p>
<p>Log4Net, as others have said, is fairly common and similar to Log4j which will help you if you ever do any Java.</p> <p>You also have the option of using the Logging Application Block <a href="http://www.codeproject.com/KB/architecture/GetStartedLoggingBlock.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/architecture/GetStartedLoggingBlock.aspx</a></p>
17,767
<p>I get the following warning when using <code>java.net.URLEncoder.encode</code>:</p> <pre>warning: [deprecation] encode(java.lang.String) in java.net.URLEncoder has been deprecated</pre> <p>What should I be using instead?</p>
<p>Use the other <code>encode</code> method in <a href="http://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html#encode-java.lang.String-java.lang.String-" rel="noreferrer">URLEncoder</a>:</p> <pre><code>URLEncoder.encode(String, String) </code></pre> <p>The first parameter is the text to encode; the second is the name of the character encoding to use (e.g., <code>UTF-8</code>). For example:</p> <pre><code>System.out.println( URLEncoder.encode( "urlParameterString", java.nio.charset.StandardCharsets.UTF_8.toString() ) ); </code></pre>
<p>As an additional reference for the other responses, instead of using <strong>"UTF-8"</strong> you can use:</p> <p><code>HTTP.UTF_8</code> </p> <p>which is included since Java 4 as part of the org.apache.http.protocol library, which is included also since Android API 1.</p>
26,247
<p>I am trying to use the Google Maps API in a ColdFusion template that is a border type cflayoutarea container. However, the map simply doesn't show up:</p> <pre><code>&lt;cfif isdefined("url.lat")&gt; &lt;cfset lat="#url.lat#"&gt; &lt;cfset lng="#url.lng#"&gt; &lt;/cfif&gt; &lt;head&gt; &lt;script src= "http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;key=xxxx" type="text/javascript"&gt; function getMap(lat,lng){ if (GBrowserIsCompatible()) { var map = new GMap2(document.getElementById("map_canvas")); var pt= new GLatLng(lat,lng); map.setCenter(pt, 18,G_HYBRID_MAP); map.addOverlay(new GMarker(pt)); } } &lt;/script&gt; &lt;/head&gt; &lt;cfoutput&gt; &lt;body onLoad="getMap(#lat#,#lng#)" onUnload="GUnload()"&gt; Map:&lt;br&gt; &lt;div id="map_canvas" style="width: 500px; height: 300px"/&gt; &lt;/body&gt; &lt;/cfoutput&gt;" </code></pre> <p>where lat and lng are the co-ordinates in degree.decimal format. I have traced down to the line where GBrowserIsCompatible() somehow never returns TRUE and thus no further action was taken.</p> <p>If opened separately the template works perfectly but just not when opened as a cflayoutarea container. Anyone has experience in this? Any suggestions is much appreciated.</p> <p>Lawrence</p> <p>Using CF 8.01, Dreamweaver 8</p> <hr> <p>Tried your suggestion but still doesn't work; the map only shows when the calling code is inline. However, if this container page was called from yet another div the map disappears again.</p> <p>I suspect this issue is related to the cflayout container; I'll look up the Extjs doc to see if there're any leads to a solution.</p>
<p>Success! (sort of...)</p> <p>Finally got it working, but not in the way Adam suggested:</p> <pre><code>&lt;script src= "http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;key=xxxx" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; getMap=function(lat,lng){ if (GBrowserIsCompatible()){ var map = new GMap2(document.getElementById("map_canvas")); var pt = new GLatLng(lat,lng); map.setCenter(pt, 18,G_HYBRID_MAP); map.addOverlay(new GMarker(pt)); } } &lt;/script&gt; &lt;cflayout name="testlayout" type="border"&gt; &lt;cflayoutarea name="left" position="left" size="250"/&gt; &lt;cflayoutarea name="center" position="center"&gt; &lt;!--- sample hard-coded co-ordinates ---&gt; &lt;body onLoad="getMap(22.280161,114.185096)"&gt; Map:&lt;br /&gt; &lt;div id="map_canvas" style="width:500px; height: 300px"/&gt; &lt;/body&gt; &lt;/cflayoutarea&gt; &lt;!--- &lt;cflayoutarea name="center" position="center" source="map_content.cfm?lat=22.280161&amp;lng=114.185096"/&gt; ---&gt; &lt;/cflayout&gt; </code></pre> <p>The whole thing must be contained within the same file or it would not work. My suspicion is that the getElementByID function, as it stands, cannot not reference an element that is outside of its own file. If the div is in another file (as in Adam's exmaple), it results in an undefined map, ie a map object is created but with nothing in it.</p> <p>So I think this question is now elevated to a different level: how do you reference an element that is inside an ajax container? </p>
<p>Maybe the layout area doesn't have the right <strong>style</strong>. I think you may have to give the map_canvas a</p> <pre><code>position: absolute </code></pre> <p>or </p> <pre><code>position: relative </code></pre> <p>That's just a hunch.</p>
10,570
<p>Let's say I have four tables: <code>PAGE</code>, <code>USER</code>, <code>TAG</code>, and <code>PAGE-TAG</code>:</p> <pre><code>Table | Fields ------------------------------------------ PAGE | ID, CONTENT TAG | ID, NAME USER | ID, NAME PAGE-TAG | ID, PAGE-ID, TAG-ID, USER-ID </code></pre> <p>And let's say I have four pages:</p> <pre><code>PAGE#1 'Content page 1' tagged with tag#1 by user1, tagged with tag#1 by user2 PAGE#2 'Content page 2' tagged with tag#3 by user2, tagged by tag#1 by user2, tagged by tag#8 by user1 PAGE#3 'Content page 3' tagged with tag#7 by user#1 PAGE#4 'Content page 4' tagged with tag#1 by user1, tagged with tag#8 by user1 </code></pre> <p>I expect my query to look something like this: </p> <pre><code>select page.content ? from page, page-tag where page.id = page-tag.pag-id and page-tag.tag-id in (1, 3, 8) order by ? desc </code></pre> <p>I would like to get output like this:</p> <pre><code>Content page 2, 3 Content page 4, 2 Content page 1, 1 </code></pre> <hr> <p>Quoting Neall </p> <blockquote> <p>Your question is a bit confusing. Do you want to get the number of times each page has been tagged? </p> </blockquote> <p>No</p> <blockquote> <p>The number of times each page has gotten each tag? </p> </blockquote> <p>No</p> <blockquote> <p>The number of unique users that have tagged a page? </p> </blockquote> <p>No </p> <blockquote> <p>The number of unique users that have tagged each page with each tag?</p> </blockquote> <p>No</p> <p>I want to know how many of the passed tags appear in a particular page, not just if any of the tags appear. </p> <p>SQL IN works like an boolean operator OR. If a page was tagged with any value within the IN Clause then it returns true. I would like to know how many of the values inside of the IN clause return true. </p> <p>Below i show, the output i expect: </p> <pre><code>page 1 | in (1,2) -&gt; 1 page 1 | in (1,2,3) -&gt; 1 page 1 | in (1) -&gt; 1 page 1 | in (1,3,8) -&gt; 1 page 2 | in (1,2) -&gt; 1 page 2 | in (1,2,3) -&gt; 2 page 2 | in (1) -&gt; 1 page 2 | in (1,3,8) -&gt; 3 page 4 | in (1,2,3) -&gt; 1 page 4 | in (1,2,3) -&gt; 1 page 4 | in (1) -&gt; 1 page 4 | in (1,3,8) -&gt; 2 </code></pre> <p>This will be the content of the page-tag table i mentioned before: </p> <pre><code> id page-id tag-id user-id 1 1 1 1 2 1 1 2 3 2 3 2 4 2 1 2 5 2 8 1 6 3 7 1 7 4 1 1 8 4 8 1 </code></pre> <p><strong>@Kristof</strong> does not exactly what i am searching for but thanks anyway. </p> <p><strong>@Daren</strong> If i execute you code i get the next error: </p> <pre><code>#1054 - Unknown column 'page-tag.tag-id' in 'having clause' </code></pre> <p><strong>@Eduardo Molteni</strong> Your answer does not give the output in the question but: </p> <pre><code>Content page 2 8 Content page 4 8 content page 2 3 content page 1 1 content page 1 1 content page 2 1 cotnent page 4 1 </code></pre> <p><strong>@Keith</strong> I am using plain SQL not T-SQL and i am not familiar with T-SQL, so i do not know how your query translate to plain SQL.</p> <p>Any more ideas?</p>
<p>This might work:</p> <pre><code>select page.content, count(page-tag.tag-id) as tagcount from page inner join page-tag on page-tag.page-id = page.id group by page.content having page-tag.tag-id in (1, 3, 8) </code></pre>
<p>In T-Sql:</p> <pre><code>select count(distinct name) from page-tag where tag-id in (1, 3, 8) </code></pre> <p>This will give you a count of the number of different tag names for your list of ids</p>
5,202
<p>How do you compare two instances of structs for equality in standard C?</p>
<p>C provides no language facilities to do this - you have to do it yourself and compare each structure member by member.</p>
<p>if the 2 structures variable are initialied with calloc or they are set with 0 by memset so you can compare your 2 structures with memcmp and there is no worry about structure garbage and this will allow you to earn time </p>
17,131
<p>All,</p> <p>I'm working on a SharePoint project, but this isn't a SharePoint-specific question per-se. I have an assembly I've deployed to a SharePoint farm, and I'd like to verify whether my "newest version" is sitting in the GAC, or if an older version from late yesterday is sitting there instead. This is a test farm, so yes, we are revving versions constantly.</p> <p>Without doing anything crazy like changing the assembly version itself every time I compile*, is there some assembly property I can check (or set at compile-time)?</p> <p>*I should clarify, in SharePoint projects we hardcode the assembly's full name in multiple places (including XML files), so changing the assembly version is a less savory option than you might think.</p>
<p>Assembly Version is the intended mechanism for this, but you could roll your own by comparing an MD5 hash of the GAC assembly with the MD5 of your latest version.</p>
<p>You could use AssemblyFileVersion attribute. From the docs, the AssemblyFileVersion</p> <p><em>Instructs a complier to use a specific version number for the Win32 file version resource. The Win32 file version is not required to be the same as the assembly's version number.</em></p>
26,930
<p>It is often handy to have a canonical representation of a language (in my case they are usually domain specific languages); however, I believe there are strict limits on the expressiveness of the languages involved that determine whether a canonical form can be determined and/or created for an arbitrary program in that language. Unfortunately, I've been unable to find the references that I (vaguely) recall reading about this in.</p> <p>On one hand, it seems reasonable that creating a canonical representation of a language is of comparable complexity to many hard graph problems (eg: graph isomorphism), but on the other hand, iirc, compilers like gcc, yhc, and ghc use intermediate representations to generate outputs in various formats (assembly, javascript, etc.), so this is at least in some forms, a solved problem. </p> <p>When is it possible to determine / generate a canonical form for a given language? (How expressive can that language be, and how does language expressiveness impact the utility of the canonical forms?) Please provide references or proofs if at all possible.</p> <p><em>Edit:</em> For example, a <a href="http://en.wikipedia.org/wiki/Regular_language" rel="nofollow noreferrer">Regular Language</a> (eg: the 'pure' form of regular expressions) can not express many of the same things that a <a href="http://en.wikipedia.org/wiki/Turing_complete" rel="nofollow noreferrer">Turing-complete language</a> can. In other words, you can't write a web server in a regular language, but you can with lambda calculus). My question is about the theoretical possibilities, and does have a specific answer relating to complexity theory. If I have a DSL that needs to be transmitted to another system, it will often be beneficial to generate a canonical form of that code before transmitting it, since that will decouple the independent representations used by the two different systems. <em>However</em>, if it is P-Space complete, or NP-Complete to translate a Turing-complete language into a canonical form, then you shouldn't waste time trying to build a canonical form -- either find another way to do it, or reduce the language complexity to something that <em>can</em> be canonicalized in polynomial time.</p>
<p>By "canonical representation" I assume you mean the following: Call programs <em>P</em> and <em>Q</em> <em>equivalent</em> if they "do the same thing" on the same inputs. "Doing the same thing" means that the programs have the same output, and either both programs halt after a finite time or both enter an infinite loop. This equivalence relation defines equivalence classes in the set of all programs. The "canonical representation" of a program <em>P</em> is a program <em>P'</em> belonging to the same equivalence class, and you require that all members of the same equivalence class have the same canonical representation. </p> <p>For Turing-complete languages, a Turing-computable canonical representation would enable you to solve the <a href="http://en.wikipedia.org/wiki/Halting_problem" rel="nofollow noreferrer">Halting Problem</a> as follows: first write a program consisting of an infinite loop and find its canonical representation <em>Q</em>. Then for any input program <em>P</em>, first transform it mechanically into a program <em>P</em><sub>0</sub> that does the same thing except that it produces no output, and then find the canonical representation <em>P</em><sub>0</sub>' of this program. If the result is <em>Q</em>, you know that <em>P</em><sub>0</sub> does not halt, and therefore neither does <em>P</em>. Otherwise, <em>P</em><sub>0</sub> halts, and so does <em>P</em>.</p> <p>For even more fun, read some of <a href="http://en.wikipedia.org/wiki/Gregory_Chaitin" rel="nofollow noreferrer">Gregory Chaitin's</a> work on what he calls "elegant" programs.</p>
<p>It seems to me that compiling into an assembly language could be categorized as translation into a canonical form in a practical fashion.</p>
22,380
<p>I am serving all content through apache with <code>Content-Encoding: zip</code> but that compresses on the fly. A good amount of my content is static files on the disk. I want to gzip the files beforehand rather than compressing them every time they are requested.</p> <p>This is something that, I believe, <code>mod_gzip</code> did in Apache 1.x automatically, but just having the file with .gz next to it. That's no longer the case with <code>mod_deflate</code>.</p>
<p>This functionality was misplaced in mod_gzip anyway. In Apache 2.x, <a href="http://httpd.apache.org/docs/2.2/content-negotiation.html" rel="noreferrer">you do that with content negotiation</a>. Specifically, you need to enable <code>MultiViews</code> with the <a href="http://httpd.apache.org/docs/2.2/mod/core.html#options" rel="noreferrer"><code>Options</code> directive</a> and you need to specify your encoding types with the <a href="http://httpd.apache.org/docs/2.2/mod/mod_mime.html#addencoding" rel="noreferrer"><code>AddEncoding</code> directive</a>.</p>
<p>You can use <a href="http://httpd.apache.org/docs/2.2/mod/mod_cache.html" rel="nofollow noreferrer"><code>mod_cache</code></a> to proxy local content in memory or on disk. I don't know if this will work as expected with <code>mod_deflate</code>.</p>
10,110
<p>Navigation systems like the Garmin and TomTom have always fascinated me. I've wanted to implement small map/navigation applications to try out various pathing algorithms and expand on my knowledge of them.</p> <p>This is a two part question:</p> <p><strong>1.) How is Map data stored?</strong> - When you have a network of roads, how is this data generally stored? What parts of the data are retained inorder to reproduce a map later? Is each road stored as a series of points where it changes direction? What kind of file formats is this data stored in? Are there publically available libraries for easily parsing these files? Does anyone have specifics on how map/road data is stored/represented it would be very helpful.</p> <p><strong>2.) Navigation/Pathing</strong> - When doing basic pathing on this map data (a la Garmin) is my assumption correct that it is converted to a directed graph? Is each road intersection a vertex with the edge weights the distance between vertexes? This is what I was thinking about doing so I could try some basic well known pathing algorithms and see what I get.</p> <p>I've seen <a href="http://www.bts.gov/publications/north_american_transportation_atlas_data/" rel="noreferrer">this</a> publically available map data on the US but I'm not sure how it is represented and if it is detailed enough for me to be able to build my directed graph out of it.</p> <p>If anyone has any information I would appreciate it. The more detailed knowledge you have the better.</p>
<p>I don't know specifics about navigation system units, but in the standard GIS world, map data is stored basically as a collection of polygons, lines and points, each described by its coordinates (and the projection used and some other parameters). For instance, one of the most common formats, shapefiles, is described <a href="http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf" rel="noreferrer">here,</a> and the database based format standard is <a href="http://www.opengeospatial.org/standards/sfs" rel="noreferrer">here</a>.</p> <p>I've successfully used this storage model for roads display and route calculation, using <a href="http://postgresql.org" rel="noreferrer">PostgreSQL</a>, <a href="http://postgis.refractions.net" rel="noreferrer">PostGIS</a> and <a href="http://pgrouting.postlbs.org/" rel="noreferrer">PGRouting</a>. Calculations are done using the usual graph algorithms and the data stored in the common format is stored also as a graph to allow for their application. I can't extrapolate that experience to an embedded device as they likely do it very differently given their limited computing capacity. They very probably precalculate lots of stuff.</p> <p>For a somewhat different approach to storage, check <a href="http://www.openstreetmap.org" rel="noreferrer">OpenStreetMap</a></p>
<p>For improved drawing speed at the cost of more storage and limited resolution, many applications will use a georeferenced raster format such as <a href="http://www.remotesensing.org/geotiff/geotiff.html" rel="nofollow noreferrer">GeoTiff</a>. </p> <p>Given the rather insistent comment by Zich below that </p> <blockquote> <p>"Data are in vector in all Navigation systems with no exception!"</p> </blockquote> <p>I thought I'd add a bit to the above. Firstly, I'd define a navigation system as a system that assists you how you get to where you want to go based on your current location, typically by costing a number of possible alternative routes and recommending the lowest cost one. Possible routes may be dictated by mode of transport, cars stay on roads for example whereas hill walkers don't. Costing of routes may vary by mode of transport too as well as user requirements. Cars might want to take quickest route based on road speed, trucks might want most fuel efficient route, hill walkers might want the safest direct route, boats or aeroplanes might want a route that avoids dangerous weather systems, while also minimising fuel cost and time spent.</p> <p>At the most simple level a map and compass is a navigation system. Replace the map with a small screen, a scalable raster map and a GPS and you still have a navigation system. Most low to medium end maritime navigation systems still work this way, with charts representing the coastline and seabed and GPS to give you location, and echo sounding for depth.</p> <p>At the more advanced end of the spectrum, autonomous robotic navigation systems such as the <a href="http://mars.nasa.gov/mer/home/posters/OpportunityPosterBack.pdf" rel="nofollow noreferrer">Mars Rover navigation system</a> generate DTM models on the fly as a basis for short range navigation, and satellite gathered DEMs for longer range navigation.</p> <p>To suggest that all navigation systems work like consumer Garmin or Tom Tom devices is a rather naive presumption. FWIW, many modern Garmin devices also include <a href="http://pinns.co.uk/osm/dem.html" rel="nofollow noreferrer">raster based DEM data</a> where low cost GPS heighting can be wildly inaccurate. </p>
21,364
<p>I'm currently working on a DNA database class and I currently associate each row in the database with both a match score (based on edit distance) and the actual DNA sequence itself, is it safe to modify first this way within an iteration loop?</p> <pre><code>typedef std::pair&lt;int, DnaDatabaseRow&gt; DnaPairT; typedef std::vector&lt;DnaPairT&gt; DnaDatabaseT; // .... for(DnaDatabaseT::iterator it = database.begin(); it != database.end(); it++) { int score = it-&gt;second.query(query); it-&gt;first = score; } </code></pre> <p>The reason I am doing this is so that I can sort them by score later. I have tried maps and received a compilation error about modifying first, but is there perhaps a better way than this to store all the information for sorting later?</p>
<p>To answer your first question, yes. It is perfectly safe to modify the members of your pair, since the actual data in the pair does not affect the vector itself.</p> <p><b>edit:</b> I have a feeling that you were getting an error when using a map because you tried to modify the <code>first</code> value of the map's internal pair. That would not be allowed because that value is part of the map's inner workings.</p> <p>As stated by <a href="https://stackoverflow.com/users/36565/dribeas">dribeas</a>:</p> <blockquote>In maps you cannot change first as it would break the invariant of the map being a sorted balanced tree </blockquote> <p><b>edit:</b> To answer your second question, I see nothing at all wrong with the way you are structuring the data, but I would have the database hold <i>pointers</i> to <code>DnaPairT</code> objects, instead of the objects themselves. This would dramatically reduce the amount of memory that gets copied around during the sort procedure.</p> <pre><code>#include &lt;vector&gt; #include &lt;utility&gt; #include &lt;algorithm&gt; typedef std::pair&lt;int, DnaDatabaseRow&gt; DnaPairT; typedef std::vector&lt;DnaPairT *&gt; DnaDatabaseT; // ... // your scoring code, modified to use pointers void calculateScoresForQuery(DnaDatabaseT& database, queryT& query) { for(DnaDatabaseT::iterator it = database.begin(); it != database.end(); it++) { int score = (*it)-&gt;second.query(query); (*it)-&gt;first = score; } } // custom sorting function to handle DnaPairT pointers bool sortByScore(DnaPairT * A, DnaPairT * B) { return (A-&gt;first &lt; B-&gt;first); } // function to sort the database void sortDatabaseByScore(DnaDatabaseT& database) { sort(database.begin(), database.end(), sortByScore); } // main int main() { DnaDatabaseT database; // code to load the database with DnaPairT pointers ... calculateScoresForQuery(database, query); sortDatabaseByScore(database); // code that uses the sorted database ... }</code></pre> <p>The only reason you might need to look into more efficient methods is if your database is so enormous that the sorting loop takes too long to complete. If that is the case, though, I would imagine that your <code>query</code> function would be the one taking up most of the processing time.</p>
<p>You can't modify since the variable first of std::pair is defined const</p>
42,775
<p>I have been sick and tired Googling the solution for doing case-insensitive search on Sybase ASE (Sybase data/column names are case sensitive). The Sybase documentation proudly says that there is only one way to do such search which is using the Upper and Lower functions, but the adage goes, it has performance problems. And believe me they are right, if your table has huge data the performance is so awkward you are never gonna use Upper and Lower again. My question to fellow developers is: how do you guys tackle this? </p> <p>P.S. Don't advise to change the sort-order or move to any other Database please, in real world developers don't control the databases.</p>
<p>Try creating a <code>functional index</code>, like </p> <pre><code>Create Index INDX_MY_SEARCH on TABLE_NAME(LOWER(@MySearch) </code></pre>
<p>If you cannot change the sort-order on the database(best option), then the indexes on unknown case fields will not help. There is a way to do this and keep performance if the number of fields is manageable. You make an extra column MyFieldLower. You use a trigger to keep the field filled with a lower case of MyField. </p> <p>Then the query is: WHERE MyFieldLower = LOWER(@MySearch)</p> <p>This will use indexing.</p>
10,685
<p>I want to provide silverlight app to my customer while hosting the app at my own site for streamlined maintenance.</p> <ul> <li>my Silverlight .xap is hosted in, let say, domain <em>me-supplier.com</em></li> <li>i want to embed it in, let say, domain <em>my-customer.com</em></li> </ul> <p>It works perfectly for <em><a href="http://my-customer.com" rel="nofollow noreferrer">http://my-customer.com</a></em>, not for <strong><em>https</strong>://my-customer.com</em> </p> <ul> <li>i have added the (<em>me-supplier.com</em> hosted) cross domain silverlight policy file to allow <em>my-customer.com</em></li> <li>i have configured the mime types for .xap</li> <li>the silverlight app needs html dom access so the iframe approach is not viable i believe.</li> </ul> <p>this works for javascript code, so why not for silverlight ? any idea, workaround ?</p>
<p>The short story is that it isn't <a href="http://forums.asp.net/p/1006669/1336527.aspx" rel="nofollow noreferrer">easily</a> accomplished. That code is added to the header by the menu during the prerender phase. </p> <p>A possible workaround might be overriding the menu's onprerender in a custom menu control and don't call base. You could then replace the default menu control with your own using <a href="http://msdn.microsoft.com/en-us/library/ms164641.aspx" rel="nofollow noreferrer">tagMappings</a>.</p> <p>I'd suggest you stay clear of the menu control if you can.</p>
<p>The short story is that it isn't <a href="http://forums.asp.net/p/1006669/1336527.aspx" rel="nofollow noreferrer">easily</a> accomplished. That code is added to the header by the menu during the prerender phase. </p> <p>A possible workaround might be overriding the menu's onprerender in a custom menu control and don't call base. You could then replace the default menu control with your own using <a href="http://msdn.microsoft.com/en-us/library/ms164641.aspx" rel="nofollow noreferrer">tagMappings</a>.</p> <p>I'd suggest you stay clear of the menu control if you can.</p>
27,366
<p>If I have a VB.Net function that returns an Int32, but uses an unsigned int (UInt32) for calculations, etc. How can I convert a variable "MyUintVar32" with a value of say "3392918397 into a standard Int32 in VB.Net? </p> <p>In c# if I just do a "return (int)(MyUintVar32);", I get -902048899, not an error.</p> <p>I've tried several different methods. What is the difference in the way c# handles these conversions versus VB.Net?</p>
<p>I realize this is an old post, but the question has not been answered. Other people my want to know:</p> <pre><code>Dim myUInt32 As UInt32 = 3392918397 Dim myInt32 As Int32 = Convert.ToInt32(myUInt32.ToString("X"), 16) </code></pre> <p>the reverse operation: </p> <pre><code>myUInt32 = Convert.ToUInt32(myInt32.ToString("X"), 16) </code></pre> <p>Also, one can create a union structure to easily convert between Int32 and UInt32: </p> <pre><code>Imports System.Runtime.InteropServices &lt;StructLayout(LayoutKind.Explicit)&gt; _ Public Structure UnionInt32 &lt;FieldOffset(0)&gt; _ Public IntValue As Int32 &lt;FieldOffset(0)&gt; _ Public UIntValue As UInt32 End Structure Dim MyUnionInt32 as UnionInt32 MyUnionInt32.UIntValue = 3392918397 Dim IntVal as Int32 = MyUnionInt32.UIntValue '= -902048899 </code></pre> <p>the reverse operation: </p> <pre><code>MyUnionInt32.IntValue = -902048000 Dim UIntVal as UInt32 = MyUnionInt32.UIntValue '= 3392919296 </code></pre> <p>Cheers, TENware</p>
<p>Or after doing the Uint32 work check it against MAXINT and 0. </p> <p>If > MAXINT and &lt; 0 then you're ok. If not you "overflowed" and should throw an exception.</p> <p>I don't remember if MAXINT is defined. You can use: 2^31 - 1 instead.</p>
25,822
<p>When using Groovy <code>MarkupBuilder</code>, I have places where I need to output text into the document, or call a function which outputs text into the document. Currently, I'm using the undefined tag <em>"text"</em> to do the output. Is there a better way to write this code?</p> <pre><code>li { text("${type.getAlias()} blah blah ") function1(type.getXYZ()) if (type instanceof Class1) { text(" implements ") ft.getList().each { if (it == '') return text(it) if (!function2(type, it)) text(", ") } } } </code></pre>
<p>Actually, the recommended way now is to use <code>mkp.yield</code>, e.g.,</p> <pre><code>src.p { mkp.yield 'Some element that has a ' strong 'child element' mkp.yield ' which seems pretty basic.' } </code></pre> <p>to produce</p> <pre><code>&lt;p&gt;Some element that has a &lt;strong&gt;child element&lt;/strong&gt; which seems pretty basic.&lt;/p&gt; </code></pre>
<p>Include a method:</p> <pre><code>void text(n){ builder.yield n } </code></pre> <p>Most likely you (I) copied this code from somewhere that had a text method, but you didn't also copy the text method. Since MarkupBuilder accepts any name for the name of a tag and browsers ignore unknown markup, it just happened to work.</p>
4,314
<p>We're thinking of buying a PETG-powered printer. When researching printers available on the market, there are machines with a 100 microns. I was wondering if there are machines with a 50 microns or close to 50 micros? Otherwise, why not?</p>
<blockquote> <p>I was wondering the other day why don't all three motors move at the same time?</p> </blockquote> <p>That is perfectly possible for most printers (with limitations, &quot;3D Printing&quot; with all steppers being used is called &quot;non-planar&quot; printing), but there are some major cons you need to deal with. First, there are not that many software suites that slice objects perfectly well like the &quot;normal&quot; per &quot;fixed/variable layer height&quot; slicing as the slicers are under developed. Second, it requires a specific tall and slender nozzle/print head, else the height of printing is very limited. Last, besides generally not being useful for rectangular prints (except for 90° overhanging structures<sup>1)</sup>), this method is only/best suitable for curved objects as the top layer will follow the contours of the object.</p> <blockquote> <p>It makes sense if a 3D printer really does print with all three motors moving.</p> </blockquote> <p>No, it does not make sense, the essentials of 3D printing it that it produces a 3D object, not that all stepper motors should be running simultaneously.</p> <blockquote> <p>Won't it also be more efficient if they do 3D print in all axes?</p> </blockquote> <p>Not necessarily, there are limitations to non-planar printing like geometry and print quality, but, you could (in some cases) print with less support material.</p> <hr /> <p><sup>1)</sup> : From <a href="https://xyzdims.com/2021/03/03/3d-printing-90-overhangs-without-support-structure-with-non-planar-slicing-on-3-axis-printer/" rel="nofollow noreferrer">Rene K. Mueller, published March 3, 2021, https://xyzdims.com</a>: <a href="https://i.stack.imgur.com/eaJm0.png" rel="nofollow noreferrer" title="Non-planar slicing for printing 90° overhangs are tilted sliced"><img src="https://i.stack.imgur.com/eaJm0.png" alt="Non-planar slicing for printing 90° overhangs are tilted sliced" title="Non-planar slicing for printing 90° overhangs are tilted sliced" /></a> <a href="https://i.stack.imgur.com/Liiiw.png" rel="nofollow noreferrer" title="Non-planar slicing for printing 90° overhangs are conically sliced"><img src="https://i.stack.imgur.com/Liiiw.png" alt="Non-planar slicing for printing 90° overhangs are conically sliced" title="Non-planar slicing for printing 90° overhangs are conically sliced" /></a></p> <p><em>Note that these are <strong>demonstration</strong> pieces, normally you would rotate the print for 90° and print it sliced normal (planar).</em></p>
<p>The Z axis moves between each layer so you are indeed printing in the 3rd dimension. There are some techniques that move all three axis at the same time.</p>
1,925
<p>Half a year passed since <a href="https://3dprinting.meta.stackexchange.com/questions/430/tag-maintenance-summer-2019">Tag Maintenance Summer 2019</a>. A lot was done, some wasn't, so cleanup and rinse and repeat: Let's do some tag maintenance, especially regarding printers to make them easier to read. Use an answer to propose a change, merge or split. Discussions for each change should go into the comments of each change.</p> <p>Some things are easier than others: </p> <ul> <li><strong>Renaming</strong> a tag can be done with mod tools.</li> <li><strong>Alias/Synonyms</strong> are reasonably quick, often follow along renaming</li> <li>Some tags need <strong>manual (separation)</strong>. Sifting through what is and what isn't this tag has to be done to separate the stuff. It can be noisy to the front site but has to be done.</li> </ul>
<h1>Laundry list:</h1> <h2>Open</h2> <ul> <li><a href="https://3dprinting.meta.stackexchange.com/a/458/8884">Filled PLA</a></li> <li><a href="https://3dprinting.meta.stackexchange.com/a/459/8884">Repair vs. Maintenance</a></li> </ul> <h2>Done</h2> <ul> <li><a href="https://3dprinting.meta.stackexchange.com/a/456/8884">e3d</a></li> <li><a href="https://3dprinting.meta.stackexchange.com/a/455/8884">Monoprice</a></li> <li><a href="https://3dprinting.meta.stackexchange.com/a/457/8884">Creality</a></li> <li><a href="https://3dprinting.meta.stackexchange.com/a/460/8884">Prusa</a></li> </ul>
<h1>Manufacturer: E3D</h1> <p>Status: <strong>Done</strong>/split up</p> <p><a href="https://3dprinting.meta.stackexchange.com/a/438/8884">Takeover from Summer 2019</a></p> <p>We have a lot of questions tagged <a href="https://3dprinting.stackexchange.com/questions/tagged/e3d" class="post-tag" title="show questions tagged &#39;e3d&#39;" rel="tag">e3d</a>. Some concearn the <a href="https://3dprinting.stackexchange.com/questions/tagged/e3d-v6" class="post-tag" title="show questions tagged &#39;e3d-v6&#39;" rel="tag">e3d-v6</a>, one the <a href="https://3dprinting.stackexchange.com/questions/tagged/e3d-titan-aero" class="post-tag" title="show questions tagged &#39;e3d-titan-aero&#39;" rel="tag">e3d-titan-aero</a>, I think I have seen at least one <a href="https://3dprinting.stackexchange.com/questions/tagged/e3d-volcano" class="post-tag" title="show questions tagged &#39;e3d-volcano&#39;" rel="tag">e3d-volcano</a>. As of today (updated), there's a pair of <a href="https://3dprinting.stackexchange.com/questions/tagged/e3d-hemera" class="post-tag" title="show questions tagged &#39;e3d-hemera&#39;" rel="tag">e3d-hemera</a>/(formerly: <a href="https://3dprinting.stackexchange.com/questions/tagged/e3d-hemes" class="post-tag" title="show questions tagged &#39;e3d-hemes&#39;" rel="tag">e3d-hemes</a>) and a single <a href="https://3dprinting.stackexchange.com/questions/tagged/e3d-v5" class="post-tag" title="show questions tagged &#39;e3d-v5&#39;" rel="tag">e3d-v5</a> on a very old question.</p> <p>Should we split it? Should we weed out those that use <a href="https://3dprinting.stackexchange.com/questions/tagged/e3d" class="post-tag" title="show questions tagged &#39;e3d&#39;" rel="tag">e3d</a> but mean <a href="https://3dprinting.stackexchange.com/questions/tagged/all-metal-hotend" class="post-tag" title="show questions tagged &#39;all-metal-hotend&#39;" rel="tag">all-metal-hotend</a> instead, and make that tag?</p> <ul> <li>It has been split.</li> </ul>
73
<p>I have many items inside a list control. I want each item to have a different item template depending on the type of the item. So the first item in the list is a ObjectA type and so I want it to be rendered with ItemTemplateA. Second item is a ObjectB type and so I want it to have ItemTemplateB for rendering. At the moment I can only use the ItemTemplate setting to define one template for them all. Any way to achieve this?</p>
<p>the <code>ItemTemplateSelector</code> will work but I think it is easier to create multiple <code>DataTemplate</code>s in your resource section and then just giving each one a <code>DataType</code>. This will automatically then use this <code>DataTemplate</code> if the items generator detects the matching data type?</p> <pre><code>&lt;DataTemplate DataType={x:Type local:ObjectA}&gt; ... &lt;/DataTemplate&gt; </code></pre> <p>Also make sure that you have no <code>x:Key</code> set for the <code>DataTemplate</code>.<br> Read more about this approach <a href="http://www.zagstudio.com/blog/361#.Us6JPJG-3nc" rel="nofollow noreferrer">here</a> </p>
<p>Have a look at the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemtemplateselector.aspx" rel="noreferrer">ItemTemplateSelector</a> property of your list control. You can point it to a custom TemplateSelector and decide which template to use in code.</p> <p>Here's a blog post describing TemplateSelectors:</p> <p><a href="http://blogs.interknowlogy.com/johnbowen/archive/2007/06/21/20463.aspx" rel="noreferrer">http://blogs.interknowlogy.com/johnbowen/archive/2007/06/21/20463.aspx</a></p> <p>Edit: Here's a better post:</p> <p><a href="http://blog.paranoidferret.com/index.php/2008/07/16/wpf-tutorial-how-to-use-a-datatemplateselector/" rel="noreferrer">http://blog.paranoidferret.com/index.php/2008/07/16/wpf-tutorial-how-to-use-a-datatemplateselector/</a></p>
18,418
<p>I wrote this small script to pull the office property from get-user by piping the exchange mailbox object. </p> <pre><code>$server = "tms08" $arrUser = get-mailbox -Server $server |Get-MailboxStatistics |select identity foreach ( $id in $arrUuser) { $office = get-user -Identity $id.Identity |select office $out += $id.Identity } $out </code></pre> <p>I don't get any output or red errors. just the warning:</p> <blockquote> <p>WARNING:There is no data to return for the specifed mailbox 'Globe/MobileElect Usertemplate', because it has not been logged on to. WARNING:By default only the first 1000 items are returned. To change the number of items returned, specify the parameter "-ResultSize". To return all items specify "-ResultSize Unilimited" (Note: REturning all items maytake a long time and consume a large amount of memory depending on the actual number of items). It is not recommended to store the results in a variable; instead pipe the results to another task or script to perform batch changes.</p> </blockquote> <p>Any ideas on what might be causing this? </p> <p>My goal is to develop a script which executes once a day via scheduled task which compiles all mailbox names, mailbox sizes, totalitems, totaldeleted items, along with their office and description fields (from active directory). </p> <p>I'm guessing the get-qaduser is part of the quest powershell addon. I'll install it locally and give it a try.. </p> <p>the identiy property seems to give a number similar to the guid which looks like 1234as01-4f54-1234-b1df-f1df1df12d2d </p> <p>I tried running</p> <pre><code>get-user -identity 1234as01-4f54-1234-b1df-f1df1df12d2d </code></pre> <p>and it found a name (joey blasio) and recipient type (usermailbox) </p> <p>then i ran</p> <pre><code>get-user -Identity 1234as01-4f54-1234-b1df-f1df1df12d2d | select displayname, distinguistedname </code></pre> <blockquote> <p>Displayname (Joey Blasio ) and DistinguishedName (CN=Joey Blasio,OU=EWE,DC=BLA-1,DC=net)</p> </blockquote>
<p>Check this out: <a href="http://msdn.microsoft.com/en-us/library/6t9t5wcf.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/6t9t5wcf.aspx</a></p> <p>And this: <a href="http://www.xenocode.com/Products/Postbuild-for-NET/?AdGroup=Linking&amp;gclid=CNGCo-7zopcCFSYMDQod0giG_A" rel="nofollow noreferrer">http://www.xenocode.com/Products/Postbuild-for-NET/?AdGroup=Linking&amp;gclid=CNGCo-7zopcCFSYMDQod0giG_A</a></p>
<p><a href="http://www.dcl.hpi.uni-potsdam.de/research/lego.NET/release.htm" rel="nofollow noreferrer">Lego.NET</a> can create native binaries, but it's still fairly limited.</p>
43,516
<p>Is there a CPAN module that can read a string like this:</p> <pre><code>"[[&lt;asdf&gt;, &lt;foo&gt;], (abc, def, ghi), ({'jkl'})]" </code></pre> <p>...and parse it into some sort of tree structure that's easy to walk and pretty-print?</p>
<p>I think that you could build on top of <a href="http://search.cpan.org/dist/Text-Balanced/" rel="nofollow noreferrer">Text::Balanced</a>, which will do a lot of the heavy lifting for you. You'll still need to build a tree structure, though.</p>
<p>If the string is identical to the <a href="http://perldoc.perl.org/Data/Dumper.html" rel="nofollow noreferrer">Data Dumper</a> format, then it can be <code>eval</code>-ed back into the original structure.</p>
46,150
<p>Inspired by <a href="https://devblogs.microsoft.com/oldnewthing/20080902-00/?p=21003" rel="noreferrer">Raymond Chen's post</a>, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.</p> <pre><code>[1][2][3][4] [5][6][7][8] [9][0][1][2] [3][4][5][6] </code></pre> <p>Becomes:</p> <pre><code>[3][9][5][1] [4][0][6][2] [5][1][7][3] [6][2][8][4] </code></pre> <p><strong>Update</strong>: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?</p>
<p><strong>O(n^2) time and O(1) space algorithm</strong> ( without any workarounds and hanky-panky stuff! )</p> <p><strong>Rotate by +90:</strong></p> <ol> <li>Transpose</li> <li>Reverse each row</li> </ol> <p><strong>Rotate by -90:</strong></p> <p><em>Method 1 :</em></p> <ol> <li>Transpose</li> <li>Reverse each column</li> </ol> <p><em>Method 2 :</em></p> <ol> <li>Reverse each row</li> <li>Transpose</li> </ol> <p><strong>Rotate by +180:</strong></p> <p><em>Method 1</em>: Rotate by +90 twice</p> <p><em>Method 2</em>: Reverse each row and then reverse each column (Transpose)</p> <p><strong>Rotate by -180:</strong></p> <p><em>Method 1</em>: Rotate by -90 twice</p> <p><em>Method 2</em>: Reverse each column and then reverse each row</p> <p><em>Method 3</em>: Rotate by +180 as they are same</p>
<p>The O(1) memory algorithm:</p> <ol> <li><p>rotate the outer-most data, then you can get below result:</p> <pre><code>[3][9][5][1] [4][6][7][2] [5][0][1][3] [6][2][8][4] </code></pre></li> </ol> <p>To do this rotation, we know </p> <pre><code> dest[j][n-1-i] = src[i][j] </code></pre> <p>Observe below: a(0,0) -> a(0,3) a(0,3) -> a(3,3) a(3,3) -> a(3,0) a(3,0) -> a(0,0)</p> <p>Therefore it's a circle, you can rotate N elements in one loop. Do this N-1 loop then you can rotate the outer-most elements.</p> <ol> <li>Now you can the inner is a same question for 2X2. </li> </ol> <p>Therefore we can conclude it like below:</p> <pre><code>function rotate(array, N) { Rotate outer-most data rotate a new array with N-2 or you can do the similar action following step1 } </code></pre>
6,405
<p>I've been developing an internal website for a portfolio management tool. There is a lot of text data, company names etc. I've been really impressed with some search engines ability to very quickly respond to queries with "Did you mean: xxxx".</p> <p>I need to be able to intelligently take a user query and respond with not only raw search results but also with a "Did you mean?" response when there is a highly likely alternative answer etc</p> <p>[I'm developing in <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="noreferrer">ASP.NET</a> (VB - don't hold it against me! )]</p> <p>UPDATE: OK, how can I mimic this without the millions of 'unpaid users'?</p> <ul> <li>Generate typos for each 'known' or 'correct' term and perform lookups?</li> <li>Some other more elegant method?</li> </ul>
<p>Here's the explanation directly from the source ( almost ) </p> <h2><strong><a href="http://www.youtube.com/watch?v=syKY8CrHkck#t=22m03s" rel="noreferrer">Search 101!</a></strong></h2> <p>at min 22:03</p> <p>Worth watching!</p> <p>Basically and according to Douglas Merrill former CTO of Google it is like this:</p> <p>1) You write a ( misspelled ) word in google </p> <p>2) You don't find what you wanted ( don't click on any results )</p> <p>3) You realize you misspelled the word so you rewrite the word in the search box.</p> <p>4) You find what you want ( you click in the first links ) </p> <p>This pattern multiplied millions of times, shows what are the most common misspells and what are the most "common" corrections. </p> <p>This way Google can almost instantaneously, offer spell correction in every language.</p> <p>Also this means if overnight everyone start to spell night as "nigth" google would suggest that word instead. </p> <p><strong>EDIT</strong></p> <p>@ThomasRutter: Douglas describe it as "statistical machine learning". </p> <p>They know who correct the query, because they know which query comes from which user ( using cookies ) </p> <p>If the users perform a query, and only 10% of the users click on a result and 90% goes back and type another query ( with the corrected word ) and this time that 90% clicks on a result, then they know they have found a correction. </p> <p>They can also know if those are "related" queries of two different, because they have information of all the links they show. </p> <p>Furthermore, they are now including the context into the spell check, so they can even suggest different word depending on the context. </p> <p>See this <a href="http://www.youtube.com/watch?v=v_UyVmITiYQ#t=44m06s" rel="noreferrer">demo of google wave</a> ( @ 44m 06s ) that shows how the context is taken into account to automatically correct the spelling.</p> <p><a href="http://www.youtube.com/watch?v=Sx3Fpw0XCXk" rel="noreferrer">Here</a> it is explained how that natural language processing works.</p> <p>And finally here is an awesome demo of what can be done adding automatic <a href="http://www.youtube.com/watch?v=v_UyVmITiYQ#t=1h12m47s" rel="noreferrer">machine translation</a> ( @ 1h 12m 47s ) to the mix. </p> <p><sub> I've added anchors of minute and seconds to the videos to skip directly to the content, if they don't work, try reloading the page or scrolling by hand to the mark. </sub></p>
<p>Easiest way to figure it out is to Google dynamic programming.</p> <p>It's an algorithm that's been borrowed from Information Retrieval and is used heavily in modern day bioinformatics to see how similiar two gene sequences are.</p> <p>Optimal solution uses dynamic programming and recursion.</p> <p>This is a very solved problem with lots of solutions. Just google around until you find some open source code.</p>
39,541
<p>Our team is creating a new recruitment workflow system to replace an old one. I have been tasked with migrating the old data into the new schema. I have decided to do this by creating a small Windows Forms project as the schema are radically different and straight TSQL scripts are not an adequate solution.</p> <p>The main sealed class 'ImportController' that does the work declares the following delegate event:</p> <pre><code>public delegate void ImportProgressEventHandler(object sender, ImportProgressEventArgs e); public static event ImportProgressEventHandler importProgressEvent; </code></pre> <p>The main window starts a static method in that class using a new thread:</p> <pre><code>Thread dataProcessingThread = new Thread(new ParameterizedThreadStart(ImportController.ImportData)); dataProcessingThread.Name = "Data Importer: Data Processing Thread"; dataProcessingThread.Start(settings); </code></pre> <p>the ImportProgressEvent args carries a string message, a max int value for the progress bar and an current progress int value. The Windows form subcribes to the event:</p> <pre><code>ImportController.importProgressEvent += new ImportController.ImportProgressEventHandler(ImportController_importProgressEvent); </code></pre> <p>And responds to the event in this manner using it's own delegate:</p> <pre><code> private delegate void TaskCompletedUIDelegate(string completedTask, int currentProgress, int progressMax); private void ImportController_importProgressEvent(object sender, ImportProgressEventArgs e) { this.Invoke(new TaskCompletedUIDelegate(this.DisplayCompletedTask), e.CompletedTask, e.CurrentProgress, e.ProgressMax); } </code></pre> <p>Finally the progress bar and listbox are updated:</p> <pre><code>private void DisplayCompletedTask(string completedTask, int currentProgress, int progressMax) { string[] items = completedTask.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (string item in items) { this.lstTasks.Items.Add(item); } if (currentProgress &gt;= 0 &amp;&amp; progressMax &gt; 0 &amp;&amp; currentProgress &lt;= progressMax) { this.ImportProgressBar.Maximum = progressMax; this.ImportProgressBar.Value = currentProgress; } } </code></pre> <p>The thing is the ListBox seems to update very quickly, but the progress bar never moves until the batch is almost complete anyway ??? what gives ?</p>
<p>Maybe you can try the BackgroundWorker component. It makes threading easier. Examples here:</p> <ul> <li><a href="http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx" rel="nofollow noreferrer">BackgroundWorker Threads and Supporting Cancel</a></li> <li><a href="http://www.c-sharpcorner.com/UploadFile/LivMic/BGWorker07032007000515AM/BGWorker.aspx" rel="nofollow noreferrer">Using the BackgroundWorker Component in .NET 2 applications</a></li> <li><a href="http://www.danielmoth.com/Blog/2004/12/backgroundworker-sample.html" rel="nofollow noreferrer">BackgroundWorker Sample</a></li> </ul>
<p>Are you sure that the UI thread is running freely during all this process? i.e. it's not sitting blocked-up on a Join or some other wait? That's what it looks like to me.</p> <p>The suggestion of using BackgroundWorker is a good one - definitely superior to trying to sledge-hammer your way out of the problem with a load of Refresh/Update calls.</p> <p>And BackgroundWorker will use a pool thread, which is a friendlier way to behave than creating your own short-lived thread.</p>
3,318
<p>I'm writing what will be an intranet application, and one of its features is roughly analogous to content voting - not unlike what SO, Amazon, and many other sites do.</p> <p>Assuming each votable piece of content has a unique ID, and each user (they're authenticated) has a unique ID, the easiest way would seem to be to have a "votes" table...</p> <pre><code>ContentID int UserID int VoteValue int </code></pre> <p>But this creates one row per vote - with millions of pieces of content and tens of thousands of users, that table's gonna be huge huge huge. Is this the best way to do it? I mean, if an int takes 4 bytes, each row takes 12 bytes. If a million pieces of content get a hundred votes, that's 400MB+ in storage, yeah? Seems... like a lot :). Even if the VoteValue is a tinyint (which is probably fine) and only 1 byte, that's still a couple hundred megabytes in the table. I mean sheesh.</p> <p>Is there a smarter way? Should I store this "votes" table in a separate database (ignoring potential data integrity issues) to partition it from the "main" data in terms of storage and performance?</p> <p>(I do realize that in today's world 400MB ain't a ton - but it seems like a LOT just to store votes, yeah?)</p>
<p>Personally as long as you have good indexes in place, you are going about it the right way. Depending on your usage, for performance you might try to avoid hitting the votes table by storing secondary count information, but overall if you must track WHO has voted something, you need to do it in the way you have listed.</p> <p>I wouldn't bother moving to another database, if you are REALLY concerned in SQL Server you could create a separate filegroup to hold it.....but most likely not necessary.</p>
<p>I'd say you need to figure out how these votes will be used and design specific queries for your data model first. This is not necessarily SQL model. If you're coming from SQL world, passing through official MongoDB tutorial helps to clear the mind for the start.</p> <p>For example, if you only need to store and display votes for a single issue page, it may be convenient to store votes in a single string field of the issue, which will look like <code>id1:id2:id3:</code>. Assuming all ids are of the same length, there are some interesting properties:</p> <ol> <li><p>Count all votes for the issue:</p> <p><code>len(issue.votes)/len(id)</code></p></li> <li><p>Find I voted on the issue</p> <p><code>myid in issue.votes</code></p></li> <li><p>Find all issues you voted on:</p> <p><code>select issue.id from issues where issue.votes contains(myid)</code></p></li> <li><p>Find the most voted issues</p> <p><code>select issue.id from issues order by len(issue.votes) desc limit 10</code></p></li> </ol> <p>This architecture allows to avoid expensive calculations on read in these specific cases, but updating <code>issue.votes</code> on vote might be more expensive than adding a row in a table. In this case 100 votes with 4 bytes per id + separator is 500 bytes string. In your proposed variant 100 votes are 800 bytes.</p> <p>Disclaimer: I never implemented anything like this, it is just an idea.</p>
44,546
<p>Many times, a Java app needs to connect to the Internet. The most common example happens when it is reading an XML file and needs to download its schema.</p> <p>I am behind a proxy server. How can I set my JVM to use the proxy ?</p>
<p>From the Java documentation (<em>not</em> the javadoc API):</p> <p><a href="http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html" rel="noreferrer">http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html</a></p> <p>Set the JVM flags <code>http.proxyHost</code> and <code>http.proxyPort</code> when starting your JVM on the command line. This is usually done in a shell script (in Unix) or bat file (in Windows). Here's the example with the Unix shell script:</p> <pre><code>JAVA_FLAGS=-Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800 java ${JAVA_FLAGS} ... </code></pre> <p>When using containers such as JBoss or WebLogic, my solution is to edit the start-up scripts supplied by the vendor.</p> <p>Many developers are familiar with the Java API (javadocs), but many times the rest of the documentation is overlooked. It contains a lot of interesting information: <a href="http://download.oracle.com/javase/6/docs/technotes/guides/" rel="noreferrer">http://download.oracle.com/javase/6/docs/technotes/guides/</a></p> <hr /> <p><strong>Update :</strong> If you do not want to use proxy to resolve some local/intranet hosts, check out the comment from @Tomalak:</p> <blockquote> <p>Also don't forget the http.nonProxyHosts property!</p> </blockquote> <pre><code>-Dhttp.nonProxyHosts=&quot;localhost|127.0.0.1|10.*.*.*|*.example.com|etc&quot; </code></pre>
<p>You can utilize the http.proxy* JVM variables if you're within a standalone JVM but you SHOULD NOT modify their startup scripts and/or do this within your application server (except maybe jboss or tomcat). Instead you should utilize the JAVA Proxy API (not System.setProperty) or utilize the vendor's own configuration options. Both WebSphere and WebLogic have very defined ways of setting up the proxies that are far more powerful than the J2SE one. Additionally, for WebSphere and WebLogic you will likely break your application server in little ways by overriding the startup scripts (particularly the server's interop processes as you might be telling them to use your proxy as well...). </p>
14,690
<p>I want to add the link tags to redirect my web-site to my OpenID provider. These tags should go in the head element. What's the best way to add them in Plone?</p> <p>I understand that filling the head_slot is a way to do it, but that can only happen when you are adding a template to the page and that template is being rendered. In my case I'm not adding any template. Which template should I modify (that is not main_template.pt, which is my current solution, with it's huge drawbacks).</p>
<p>You need fill the <code>head_slot</code> defined in <code>main_template.pt</code></p> <p>In your base plone template, add the following:</p> <pre><code>&lt;head&gt; &lt;metal:block metal:fill-slot="head_slot"&gt; &lt;link rel="openid.server" href="http://your.provider"&gt; &lt;link rel="openid.delegate" href="http://your.url"&gt; &lt;/metal:block&gt; &lt;/head&gt; </code></pre>
<p>Plone documentation on supporting OpenID can be found here.</p> <p><a href="http://plone.org/documentation/how-to/openid-support/view?searchterm=openid" rel="nofollow noreferrer">http://plone.org/documentation/how-to/openid-support/view?searchterm=openid</a></p> <p>Hope this helps.</p>
16,680
<p>Do you know of a JAXB setting to prevent <strong>standalone="yes"</strong> from being generated in the resulting XML?</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; </code></pre>
<p>This property:</p> <pre class="lang-java prettyprint-override"><code>marshaller.setProperty(&quot;com.sun.xml.bind.xmlDeclaration&quot;, false); </code></pre> <p>...can be used to have no:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt; </code></pre> <p>However, I wouldn't consider this best practice.</p>
<p>If you have <code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;</code> </p> <p>but want this: <code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;</code></p> <p>Just do:</p> <pre><code>marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;"); </code></pre>
35,091
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname">JavaScript: var functionName = function() {} vs function functionName() {}</a> </p> </blockquote> <p>What's the difference between:</p> <pre><code>function sum(x, y) { return x+y; } // and var sum = function (x, y) { return x+y; } </code></pre> <p>Why is one used over the other?</p>
<p>The first is known as a named function where the second is known as an anonymous function.</p> <p>The key practical difference is in when you can use the sum function. For example:-</p> <pre><code>var z = sum(2, 3); function sum(x, y) { return x+y; } </code></pre> <p><code>z</code> is assigned 5 whereas this:-</p> <pre><code>var z = sum(2, 3); var sum = function(x, y) { return x+y; } </code></pre> <p>Will fail since at the time the first line has executed the variable sum has not yet been assigned the function.</p> <p>Named functions are parsed and assigned to their names before execution begins which is why a named function can be utilized in code that precedes its definition.</p> <p>Variables assigned a function by code can clearly only be used as function once execution has proceeded past the assignment.</p>
<p>They mean the exact same thing. It's just syntactic sugar. The latter is IMO more revealing of what JavaScript is really doing; i.e. "sum" is just a variable, initialised with a function object, which can then be replaced by something else:</p> <pre><code>$ js js&gt; function sum(x,y) { return x+y; } js&gt; sum(1,2); 3 js&gt; sum=3 3 js&gt; sum(1,2); typein:4: TypeError: sum is not a function js&gt; sum 3 </code></pre>
13,982
<p>We will need to call out to a 3rd party to retrieve a value using REST, however if we do not receive a response within 10ms, I want to use a default value and continue processing.</p> <p>I'm leaning towards using an asynchronous WebRequest do to this, but I was wondering if there was a trick to doing it using a synchronous request.</p> <p>Any advice?</p>
<p>If you are doing a request and waiting on it to return I'd say stay synchronous - there's no reason to do an async request if you're not going to do anything or stay responsive while waiting.</p> <p>For a sync call:</p> <pre><code>WebRequest request = WebRequest.Create("http://something.somewhere/url"); WebResponse response = null; request.Timeout = 10000; // 10 second timeout try { response = request.GetResponse(); } catch(WebException e) { if( e.Status == WebExceptionStatus.Timeout) { //something } } </code></pre> <p>If doing async:</p> <p>You will have to call Abort() on the request object - you'll need to check the timeout yourself, there's no built-in way to enforce a hard timeout.</p>
<p>You could encapsulate your call to the 3rd party in a WebService. You could then call this WebService synchronously from your application - the web service reference has a simple timeout property that you can set to 10 seconds or whatever.</p> <p>Your call to get the 3rd party data from your WebService will throw a WebException after the timeout period has elapsed. You catch it and use a default value instead.</p> <p>EDIT: Philip's response above is better. RIF.</p>
16,341
<p>When I turn an image (<code>&lt;img&gt;</code>) into a hyperlink (by wrapping it in <code>&lt;a&gt;</code>), Firefox adds a black border around the image. Safari does not display the same border. </p> <p>What CSS declaration would be best to eliminate the border?</p>
<pre><code>img { border: 0 } </code></pre> <p>Or old-fashioned:</p> <pre><code>&lt;img border="0" src="..." /&gt; ^^^^^^^^^^ </code></pre>
<p>Try this:</p> <pre><code>img { border-style: none; } </code></pre>
7,260
<p>Where can I find comprehensive documentation for MOQ? I'm just starting with mocking and am having difficulty getting my head around it. I've read through all the links at <a href="http://code.google.com/p/moq/wiki/QuickStart" rel="noreferrer">http://code.google.com/p/moq/wiki/QuickStart</a> but can't seem to find a tutorial or gentle introduction.</p> <p>I have also looked briefly at Rhino Mocks but found it very confusing.</p> <hr> <p>Yes - I read Stephen Walthers article - very helpful. I also went through the links. I can't seem to watch the video at <strike><a href="http://www.bestechvideos.com/2008/06/08/dimecasts-net-introduction-to-mocking-with-moq" rel="noreferrer">http://www.bestechvideos.com/2008/06/08/dimecasts-net-introduction-to-mocking-with-moq</a></strike> <sup>[broken link]</sup></p> <p>Specifically I am trying to determine whether an event was raised from the mocked class. I can't get the example for events on the QuickStarts page to compile. On the google groups, Daniel explained that CreateEventHandler can only handle an event of type <code>EventHandler&lt;TEventArgs&gt;</code>, but even then I can't get the code to compile.</p> <p>More specifically I have a class that implements <code>INotifyChanged</code>. </p> <pre><code>public class Entity : INotifyChanged { public event PropertyChangingEventHandler PropertyChanging; public int Id { get {return _id;} set { _id = value; OnPropertyChanged("Id"); } } protected void OnPropertyChanged(string property) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } etc ..... } </code></pre> <p>How do I mock the class to test whether the <code>PropertyChanged</code> event was fired? I can't rewrite the event to <code>public event EventHandler&lt;PropertyChangedEventArgs&gt;</code> becuase I get this error:</p> <blockquote> <p>Error 1 'CoreServices.Notifier' does not implement interface member System.ComponentModel.INotifyPropertyChanged.PropertyChanged'. 'CoreServices.Notifier.PropertyChanged' cannot implement 'System.ComponentModel.INotifyPropertyChanged.PropertyChanged' because it does not have the matching return type of 'System.ComponentModel.PropertyChangedEventHandler'.</p> </blockquote>
<p>Moq's latest documentation is now available at github wiki page:</p> <p><a href="https://github.com/Moq/moq4/wiki/Quickstart" rel="noreferrer">https://github.com/Moq/moq4/wiki/Quickstart</a></p> <p>Previously they were on Google Code. As well as the wiki and other online resources, there's full documentation in Windows .CHM help-file format included in the <a href="https://github.com/Moq/moq4/wiki/Quickstart" rel="noreferrer">Moq binary download</a> linked from <a href="https://github.com/Moq/" rel="noreferrer">the Moq homepage</a>.</p>
<blockquote> <p>I am trying to determine whether an event was raised from the mocked class.</p> </blockquote> <p>Are you? Or are you trying to determine if the <code>Id</code> property was set? Remember, by default a mock has no behavior. It's not raising notification events.</p> <p>I'd do:</p> <pre><code>const int ExpectedId = 123; mockEntity.VerifySet(x =&gt; x.Id = ExpectedId); </code></pre> <p>This assumes that Entity implements an interface; one example:</p> <pre><code>public interface IKeyedEntity { int Id { get; set; } } </code></pre> <p>That said, if <code>Entity</code> is a <a href="http://en.wikipedia.org/wiki/Plain_Old_CLR_Object" rel="nofollow">POCO</a> with no interesting behavior I would neither implement an interface (other than <code>INotifyChanged</code>) nor mock it. Test with an actual <code>Entity</code> instance (just don't use a database). Reserve mocking for services and complex dependencies.</p> <p>For more Moq features, see</p> <p><a href="http://blogs.clariusconsulting.net/kzu/old-style-imperative-mocks-vs-moq-functional-specifications/" rel="nofollow">Old style imperative mocks vs moq functional specifications</a> and <a href="http://groups.google.com/group/moqdisc/browse_thread/thread/7c0477e3f4e6f400?pli=1" rel="nofollow">Mock.Of - how to specify behavior? (thread)</a>. I also posted my own example of <a href="http://www.truewill.net/myblog/index.php/2011/04/20/moq_v4_functional_specifications" rel="nofollow">Moq v4 functional specifications</a>.</p>
28,614
<p>Let's say I've got some Perl code that increments a column in a specific row of a database each time it's hit, and I'm expecting it to be hit pretty frequently, so I'd like to optimize it with FCGI. Right now, I basically wrapped most of the code in something like this:</p> <pre><code>while (FCGI::accept() &gt;= 0) { [code which currently creates a db connection and makes calls through it] } </code></pre> <p>I'm wondering if it's better to put the database connection (my $dbh = DBI->connect(etc)) outside of the FCGI loop so that the script keeps the connection alive, or will I still gain the advantages of FCGI in speed &amp; resources by leaving it in the loop?</p>
<p>bmdhacks is right that if you're using MySQL or PostgreSQL it doesn't matter as much since connections are pretty cheap. But no matter your database you will have speed gains by using persistent connections.</p> <p>But if you do decide to go with persistent connections you will need to worry about connection timeouts. These will happen at any time during the life of your program depending on your server settings and the amount of traffic you're getting. <code>ping()</code> is your friend here. And if you need more help, look at how <code>Apache::DBI</code> does it.</p>
<p>You would still gain from FCGI even if you do keep your DB connection in the loop - but you would gain even more if you moved it out.</p>
25,353
<p>I've been trying to understand how Ruby blocks work, and to do that I've been trying to implement them in C.</p> <p>One easy way to implement closures is to pass a <code>void*</code> to the enclosing stack to the closure/function but Ruby blocks also seem to handle returns and break statements from the scope that uses the block.</p> <pre><code>loop do break i if (i &gt;= 4000) i *= 2 end </code></pre> <p>I think one of the closures proposals for Java works like this also.</p> <p>So, how would you implement Ruby-blocks/Java-closures in C?</p>
<p>The concept of closures requires the concept of contexts. C's context is based on the stack and the registers of the CPU, so to create a block/closure, you need to be able to manipulate the stack pointer in a correct (and reentrant) way, and store/restore registers as needed.</p> <p>The way this is done by interpreters or virtual machines is to have a <code>context</code> structure or something similar, and not use the stack and registers directly. This structure keeps track of a stack and optionally some registers, if you're designing a register based VM. At least, that's the simplest way to do it (though slightly less performant than actually mapping things correctly).</p>
<p>There's a good set of slides on Ruby Blocks as part of the "Rails with Passion" course:</p> <p><a href="http://www.javapassion.com/rubyonrails/ruby_blocks.pdf" rel="nofollow noreferrer">Ruby_Blocks.pdf</a></p> <p>This covers representing a block, how they get passed arguments and executed, and even further into things like Proc objects. It's very clearly explained.</p> <p>It might then be of interest to look at how the JRuby guys handled these in their parsing to Java. Take a look at the source at <a href="http://svn.codehaus.org/jruby/" rel="nofollow noreferrer">codehaus</a>.</p>
4,022
<p>I'd like to have an application monitor written in C# monitoring a set of Forex trading positions. It would be connected via USB to a real set of "traffic lights" sat on a desk which it would use to indicate system status. Can anybody suggest a good solution?</p>
<p>Normally I'd say parallel port or some other such thing, but if you've got your hopes up for USB, then <em>definitely</em> have a look at the <a href="http://www.arduino.cc/" rel="nofollow noreferrer">Arduino</a>. It's a very low cost microcontroller that can run standalone, or can talk to a PC through a number of flexible interfaces (including USB). </p> <p>It is extremely popular with the hobbyist community, and as such, there are a number of entry-level projects to get one started with the device. Price on <a href="http://www.sparkfun.com/commerce/product_info.php?products_id=666" rel="nofollow noreferrer">Sparkfun is $35 USD</a> for a fully assembled USB-enabled version.</p>
<p>Try using simple usb experimentation interfaces such as Phidgets (Www.phidgets.com) or the Velleman k8055 USB experimentation board (<a href="http://www.velleman.be/ot/en/product/view/?id=351346" rel="nofollow noreferrer">http://www.velleman.be/ot/en/product/view/?id=351346</a>).</p>
34,267
<p>In Office 2003 if I recall correctly you had a "record macro" option.</p> <p>In PowerPoint 2007, under View->Macros, you get a macro box. None of the options are "record". If you put in a name, you can select "create", but that takes you to the VB editor. If you edit the slide manually, it does not generate the VBA code.</p> <p>You do not have the option of defining VBA code by a sequence of keystrokes/mouseclicks/whatever.</p>
<p>It seems you are out of luck <a href="http://office.microsoft.com/en-us/powerpoint/HA101181981033.aspx?pid=CH101030561033" rel="nofollow noreferrer">What happened to the macro recorder?</a></p> <p>I have since read:</p> <blockquote> <p>Contrary to what Microsoft says, use the legacy keyboard commands Alt+T, M, R to start the macro recorder in Powerpoint 2007, and use the same keyboard combination to stop recording.</p> </blockquote>
<p>The Keystroke activated record doesen't work it creates an empty macro with very few(usually none!) of the actual actions that you performed.</p>
49,963
<p>I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:</p> <pre><code>var results = from myRow in myDataTable where results.Field("RowNo") == 1 select results; </code></pre> <p>This is not allowed. How do I get something like this working?</p> <p>I'm amazed that LINQ queries are not allowed on DataTables!</p>
<p>You can't query against the <code>DataTable</code>'s <em>Rows</em> collection, since <code>DataRowCollection</code> doesn't implement <code>IEnumerable&lt;T&gt;</code>. You need to use the <code>AsEnumerable()</code> extension for <code>DataTable</code>. Like so:</p> <pre><code>var results = from myRow in myDataTable.AsEnumerable() where myRow.Field&lt;int&gt;(&quot;RowNo&quot;) == 1 select myRow; </code></pre> <p>And as <a href="https://stackoverflow.com/a/10893/5519709">@Keith</a> says, you'll need to add a reference to <a href="http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.aspx" rel="noreferrer">System.Data.DataSetExtensions</a></p> <p><code>AsEnumerable()</code> returns <code>IEnumerable&lt;DataRow&gt;</code>. If you need to convert <code>IEnumerable&lt;DataRow&gt;</code> to a <code>DataTable</code>, use the <code>CopyToDataTable()</code> extension.</p> <p>Below is query with Lambda Expression,</p> <pre><code>var result = myDataTable .AsEnumerable() .Where(myRow =&gt; myRow.Field&lt;int&gt;(&quot;RowNo&quot;) == 1); </code></pre>
<p>I propose following solution:</p> <pre><code>DataView view = new DataView(myDataTable); view.RowFilter = "RowNo = 1"; DataTable results = view.ToTable(true); </code></pre> <p>Looking at the <a href="https://learn.microsoft.com/de-de/dotnet/api/system.data.dataview?view=netframework-4.8" rel="nofollow noreferrer">DataView Documentation</a>, the first thing we can see is this:</p> <blockquote> <p>Represents a databindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation.</p> </blockquote> <p>What I am getting from this is that DataTable is meant to only store data and DataView is there enable us to "query" against the DataTable. </p> <p>Here is how this works in this particular case:</p> <p>You try to implement the SQL Statement</p> <pre><code>SELECT * FROM myDataTable WHERE RowNo = 1 </code></pre> <p>in "DataTable language". In C# we would read it like this:</p> <pre><code>FROM myDataTable WHERE RowNo = 1 SELECT * </code></pre> <p>which looks in C# like this:</p> <pre><code>DataView view = new DataView(myDataTable); //FROM myDataTable view.RowFilter = "RowNo = 1"; //WHERE RowNo = 1 DataTable results = view.ToTable(true); //SELECT * </code></pre>
3,202
<p>In particular, I am interested in: 1) Getting up a <em>free</em> environment setup to do workflows. 2) How to use existing workflow items/states and what is involved in that.</p> <p>Thanks!</p>
<p>Are you looking for a virtual lab like this one from <a href="http://blogs.msdn.com/pandrew/archive/2007/04/16/new-msdn-virtual-lab-for-windows-workflow-foundation.aspx" rel="nofollow noreferrer">MSDN</a>?</p> <p>For some How Tos, try downloading <a href="http://www.microsoft.com/downloadS/details.aspx?familyid=2E575633-E357-4EE7-AAFF-34138F00E830&amp;displaylang=en" rel="nofollow noreferrer">Hands-on Labs for Windows Workflow Foundation</a> </p>
<p>Are you looking for a virtual lab like this one from <a href="http://blogs.msdn.com/pandrew/archive/2007/04/16/new-msdn-virtual-lab-for-windows-workflow-foundation.aspx" rel="nofollow noreferrer">MSDN</a>?</p> <p>For some How Tos, try downloading <a href="http://www.microsoft.com/downloadS/details.aspx?familyid=2E575633-E357-4EE7-AAFF-34138F00E830&amp;displaylang=en" rel="nofollow noreferrer">Hands-on Labs for Windows Workflow Foundation</a> </p>
21,332
<p>There's <a href="http://developer.apple.com/quicktime/download/" rel="nofollow noreferrer">Quicktime SDK</a> for Windows, but any application that uses it needs quicktime runtime libraries to be installed on the system (SDK itself just has headers and library stubs, and not the actual DLLs).</p> <p>If my application uses Quicktime, I'd like to install the necessary libraries with it's installer, thus not requiring user to install Quicktime separately. What I'm looking for is some sort of "quicktime redistributable".</p> <p>As of now (quicktime 7.x), I can't find a way to do that. I could bundle whole quicktime installer (about 20 MiB), and launch it with MSI's silent/unattended flag. However, that way it has several side effects:</p> <ol> <li>creates Quicktime player shortcut on desktop and in quick launch bar</li> <li>hijacks file associations, (e.g. .mov becomes associated with Quicktime Player, even if it was associated with something else before)</li> <li>installs some service/process (qttask) that presumably watches for Quicktime associations, or handles auto-updates.</li> <li>installs Quicktime Player, which I don't need in fact.</li> </ol> <p>Of the above, first three are quite bad.</p> <p>Is there a way to "just install the libraries" for Quicktime?</p> <p>In my application, I'd use Quicktime to import images, movies and audio files in various formats. If there is no sane way to install Quicktime runtime without side effects (changed file associations, extra icons, ...), then I should be seriously looking at alternative solutions (e.g. FreeImage to load images, perhaps DirectShow for video/audio).</p>
<p>If you need to redistribute QuickTime, see <a href="http://developer.apple.com/softwarelicensing/agreements/quicktime.html" rel="nofollow noreferrer">QuickTime Licensing</a> for details. You're not allowed to redistribute any of the QuickTime libraries without a written agreement with Apple. Many CD-replication companies will actually request proof of this agreement before printing large numbers of CDs.</p> <p>I would definitely not distribute "QuickTime Lite" without consulting with either a lawyer or your Apple licensing representative.</p> <p>Your best bet, AFAIK, is to use the full QuickTime installer (all 20MB of it), and have your main installer run it with a "silent" flag. That, at least, will allow your users to install QuickTime without a half-dozen dialogs (and without those annoying pictures of surfers in bikinis). The people at Apple's licensing division seemed to think that using the "silent" flag was acceptable, at least when we consulted them.</p> <p>One warning: If the user already has an older version of QuickTime 6 Pro (or earlier) installed, then installing QuickTime 7 silently will nuke their QuickTime Pro registration and they'll have to repurchase it. We actually detect this situation in our installer and display a warning during the installation process, much like Apple does.</p> <p>Yes, this is a pain. After 6+ years of working with QuickTime, I'd honestly recommend looking at other video frameworks. We're currently evaluating Ogg Theora.</p>
<p>You could include, with your setup package, a program called Quicktime Lite. It comes with the same libraries as Quicktime uses, but is much, much smaller.</p> <p>Here"s the link: <a href="http://www.codecguide.com/qt_lite.htm" rel="nofollow noreferrer">Download Quicktime Lite</a></p>
10,022
<p>How do I embed a WMV file in an ASP.NET Web page? I want it visible as a player, not just a link. Is there an ASP.NET control for this? I don't see one on the VS 2008 toolbar, and can't find one in the help. And I'm not yet ready to move this site to Silverlight, where media is really easy.</p>
<p>Check if your project is targeted for 3.5. If it is, you should be able to see the mediaplayer control in your toolbox.</p> <p>WMV can be shown in Firefox with this plugin: <a href="http://port25.technet.com/pages/windows-media-player-firefox-plugin-download.aspx" rel="nofollow noreferrer">http://port25.technet.com/pages/windows-media-player-firefox-plugin-download.aspx</a></p> <p>WMV can be shown in QuickTime with this plugin: <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=915D874D-D747-4180-A400-5F06B1B5E559&amp;displaylang=en" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?FamilyID=915D874D-D747-4180-A400-5F06B1B5E559&amp;displaylang=en</a></p> <p>Anthony :-)</p>
<p>WMV is primarily a Microsoft file format. There is no inherent browser support for this format, so you're going to need a browser plugin to play it.</p> <p>I'm pretty sure you can embed Windows Media Player on a page to play it, but that'll limit you to clients running Windows and who happen to have Media Player installed.</p> <p>If you need to support a wide audience, I'd seriously consider re-encoding your video to something like FLV and using a Flash based video player. I haven't got statistics to hand that back this up - but Flash Video is the most widely supported video format in the browser.</p>
42,697
<p>Does anyone know of any good library that abstracts the problem of path manipulation in a nice way? I'd like to be able to combine and parse paths with arbitrary separators ('/' or ':' for example) without reinventing the wheel.</p> <p>It's a shame that <code>System.IO.Path</code> isn't more reusable.</p> <p>Thanks</p>
<p>System.IO.Path.Combine will work great for many different types of paths:</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx</a></p> <p>System.IO.Path.Combine uses the current platform standard separators to combine paths. That means on Windows it uses "\" and on unix/linux (mono) it uses "/". Can you give some samples of what paths you are trying to combine and on what platform?</p>
<p>You're describing regular expressions! Use that as the underpinning for what you need to do. </p>
7,529
<p>I've recently gotten charged with designing and implementing a source code version control, testing, and deployment scheme at the company I work.</p> <p>Personally I've worked with Subversion for a few years on my own projects. But I've never dealt with it at this big scale. Hence I thought I'd ask here if anyone has any comments or suggestions about the following setup I've deviced:</p> <ul> <li>Trunk is used as the main development tree, as it should be</li> <li>Remote servers (testing and production) check out code from the SVN repo. <ul> <li>Testing servers check out trunk.</li> <li>Production servers checkout the "production" branch.</li> </ul></li> <li>Once trunk is deemed ready for production, it's merged into two branches, "stable", and "production".</li> <li>The stable branch is a stepping stone to the production branch. If bugs are found once the new code goes live on the production server, the stable branch is used for fixing the bugs, and also testing the bug fixes.</li> <li>Once fixed, changes are merged into the production branch, and also back into trunk where development has kept on going like normal adding new features and whatever independently of any bug fixes that were needed.</li> </ul> <p>This way, development doesn't have to halt on trunk whenever there's a production release, as bug fixes aren't dependent on trunk. Also, there's always a "read-only" branch where the latest stable and most-bug free code is available, even in the middle of heavy bug fixing.</p> <p>If anybody has any suggestions, comments, or otherwise, I'd greatly appreciate it :)</p>
<p>If you want the same busy indicator for all actions, then use a counter.</p> <p>Instead of "show_busy_icon()", do a "increment_busy_count()", which calls "show_busy_icon()" if busy count goes from 0 to 1. Instead of "hide_busy_icon()", do a "decrement_busy_count()", which calls "hide_busy_icon()" if busy count goes from 1 to 0.</p>
<p>Please see my answer here: </p> <p><a href="https://stackoverflow.com/questions/244183/how-to-display-a-loading-screen-while-site-content-loads#244190">How to display a loading screen while site content loads</a></p> <p>I give a small, working JavaScript example of how to do exactly this, hope it helps.</p>
46,080
<p>When I go back to school after Thanksgiving, I'll be taking a course in CS Theory covering topics such as deterministic and nondeterministic finite state machines, turing machines, pushdown automata and a few other things. However, I haven't found a good application that can produce a visual representation of them as well as testing how they work (pass/fail, etc). The best that I've found so far is <a href="http://www.jflap.org/" rel="nofollow noreferrer">jFlap</a>, and I'm finding it rather awkward.</p>
<p>It was <a href="http://www.cs.duke.edu/csed/jflap/" rel="nofollow noreferrer">JFlap</a> that I used in college. I didn't find it that awkward to use, but it looks like it may have changed since then. Sorry I don't have a better answer for you than that.</p>
<p><a href="http://www.iar.com/website1/1.0.1.0/371/1/index.php" rel="nofollow noreferrer">IAR visualSTATE</a> might be of interest.</p>
24,174
<p>I'd like to find an opensource software that communicates directly with the RAMPS board (or any other 3D printer driver) without using the arduino...</p> <p>It doesn't matter if it runs on Windows or linux as long as it's opensource. Also, I'm not worried about how this communication is done (USB, serial port, parallel port)...</p> <p>Has anyone ever heard about projects like this?</p>
<p>No, there exists no software like that. You can't communicate with a RAMPs board because a RAMPs board has no logic built-in; it's just a dumb breakout board that connects the Arduino Mega to your printer's components (such as stepper drivers, MOSFETs for controlling heaters, endstops,...).</p> <p>If you wanted to connect a RAMPs board "directly" to your computer, you'd need a way for your computer to generate the pulses that the Arduino normally generates. You could potentially use a parallel port for this but you'd need many more outputs than a single parallel port can provide <em>and</em> you'd need to find a way to do the analog to digital conversion needed for the thermistors.</p> <p>It's just not very feasible (considering how few computers have parallel ports nowadays).</p>
<p>No, there exists no software like that. You can't communicate with a RAMPs board because a RAMPs board has no logic built-in; it's just a dumb breakout board that connects the Arduino Mega to your printer's components (such as stepper drivers, MOSFETs for controlling heaters, endstops,...).</p> <p>If you wanted to connect a RAMPs board "directly" to your computer, you'd need a way for your computer to generate the pulses that the Arduino normally generates. You could potentially use a parallel port for this but you'd need many more outputs than a single parallel port can provide <em>and</em> you'd need to find a way to do the analog to digital conversion needed for the thermistors.</p> <p>It's just not very feasible (considering how few computers have parallel ports nowadays).</p>
267
<p>I am creating a website in CakePHP and I am kind of new on it. I couldn't find good resources on this matter, so there you go:</p> <p>I have a three table structure for registering users: <code>Users</code>, <code>Addresses</code> and <code>Contacts</code>. I have to build a view with info of all three tables like:</p> <pre> Full Name: [ ] (from Users) Shipping Address: [ ] (from Address) Mobile Phone: [ ] (from Contact) e-Mail Address: [ ] (from Contact) </pre> <p>What is the best way to deal with this situation. <em>Specially for saving</em>. Creating a new Model to represent this, that will have a <code>save()</code> method itself (Maybe a sql view in the database) Create a Controller to deal with this View that <code>bind</code>s or <code>unbind</code>s info</p> <p>I wonder still how I will handle both contacts as they will be 2 different <code>INSERT</code>'s</p> <p>Any hint or resources I can dig of I will be glad.</p>
<p>If your using the latest 1.2 code, check out Model::saveAll in the api</p> <p>eg. Your view might look something like this:</p> <pre><code>echo $form-&gt;create('User', array('action' =&gt; 'add'); echo $form-&gt;input('User.name'); echo $form-&gt;input('Address.line_1'); echo $form-&gt;input('Contact.tel'); echo $form-&gt;end('Save'); </code></pre> <p>Then in your Users controller add method you'd have something like:</p> <pre><code>... if($this-&gt;User-&gt;saveAll($this-&gt;data)) { $this-&gt;Session-&gt;setFlash('Save Successful'); $this-&gt;redirect(array('action' =&gt; 'index')); } else { $this-&gt;Session-&gt;setFlash('Please review the form for errors'); } ... </code></pre> <p>In your User model you will need something like:</p> <pre><code>var $hasOne = array('Address', 'Contact'); </code></pre> <p>Hope that helps!</p> <p><a href="http://api.cakephp.org/class_model.html#49f295217028004b5a723caf086a86b1" rel="nofollow noreferrer">http://api.cakephp.org/class_model.html#49f295217028004b5a723caf086a86b1</a></p>
<blockquote> <p>3 models : User, Address, Contact</p> </blockquote> <pre><code>User hasOne Address, Contact Address belongsTo User Contact belongsTo User </code></pre> <p>in your model you define this like this :</p> <pre><code>class User extends AppModel { var $name = 'User'; var $hasOne = array('Address','Contact'); .. </code></pre> <p>To make this view, you need <strong>user_id</strong> field ind <em>addresses</em>, and <em>contacts</em> tables</p> <p>To use this in a view, you simply call a find on the User model with a recursive of one (and btw, the users controller only uses User model).</p> <pre><code>$this-&gt;User-&gt;recursive = 1; $this-&gt;set('user', $this-&gt;User-&gt;find('first', array('conditions'=&gt;array('id'=&gt;666))); </code></pre> <p>This will result in this array for your view : </p> <pre><code>array( 'Use' =&gt; array( 'id' =&gt; 666, 'name' =&gt; 'Alexander' ), 'Address' =&gt; array( 'id' =&gt; 123, 'zip' =&gt; 555 ), 'Contact' =&gt; array( 'id' =&gt; 432, 'phone' =&gt; '555-1515' )); </code></pre>
13,544
<p>Since Rails 2.1, if you define a new column in a migration with the type set to :integer and the :limit set to 5 or more, the column actually created in your MySQL database will be of type BigInt. That's perfect.</p> <p>But I cannot figure out how to create a table with a BigInt primary key.</p> <p>Any clues?</p>
<p>Not sure about the Apple ones, but this one has been really good at getting started:</p> <p><a href="http://iphone.christosblog.com/" rel="nofollow noreferrer">Christos Blog</a></p> <p>They hop into the code and tools rather than spending too much time explaining the tools. I think they will help you. </p>
<p>I believe you need to download them from iTunes which requires either a Mac or PC but they are standard mpeg-4 videos and should be viewable in vlc.</p>
40,364
<p>How do I split strings in J2ME in an effective way?</p> <p>There is a <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html" rel="noreferrer"><code>StringTokenizer</code></a> or <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split%28java.lang.String%29" rel="noreferrer"><code>String.split(String regex)</code></a> in the standard edition (J2SE), but they are absent in the micro edition (J2ME, MIDP).</p>
<p>There are a few implementations of a StringTokenizer class for J2ME. This one by <a href="http://ostermiller.org/utils/StringTokenizer.html" rel="nofollow noreferrer">Ostermiller</a> will most likely include the functionality you need</p> <p>See also <a href="https://web.archive.org/web/20120206073031/http://mobilepit.com:80/09/using-stringtokenizer-in-j2me-javame-applications.html" rel="nofollow noreferrer">this page on Mobile Programming Pit Stop</a> for some modifications and the following example:</p> <pre><code>String firstToken; StringTokenizer tok; tok = new StringTokenizer(&quot;some|random|data&quot;,&quot;|&quot;); firstToken= tok.nextToken(); </code></pre>
<p>Another alternative solution:</p> <pre><code> public static Vector split(String stringToSplit, String separator){ if(stringToSplit.length&lt;1){ return null; } Vector stringsFound = new Vector(); String remainingString = stringToSplit; while(remainingString.length()&gt;0){ int separatorStartingIndex = remainingString.indexOf(separator); if(separatorStartingIndex==-1){ // Not separators found in the remaining String. Get substring and finish stringsFound.addElement(remainingString); break; } else{ // The separator is at the beginning of the String, // Push the beginning at the end of separator and continue if(remainingString.startsWith(separator)){ remainingString = remainingString.substring(separator.length()); } // The separator is present and is not the beginning, add substring and continue else{ stringsFound.addElement(remainingString.substring(0, separatorStartingIndex)); remainingString = remainingString.substring(separatorStartingIndex + separator.length()); } } } return stringsFound; } </code></pre>
24,499
<p>Has anybody had any success ever attaching a debugger to a tethered device? I am able to debug my j2me application in the emulator, but have a lot of trouble sorting out phone-specific problems when they come up. The phone I'm using is a Nokia N95, but ideally the debug process would work on any phone.</p> <p>Is this possible? If so does anyone have steps they've used to set it up?</p>
<p>Motorola phones support a debugging interface called <a href="https://developer.motorola.com/docstools/technicalarticles/KDWP_20060501.pdf/" rel="nofollow noreferrer">KDWP</a>(Motodev registration required).Their MIDway tool can also be useful for getting debug trace information from a midlet running on a device.</p>
<p>I think it is possible to add additional debugging information on preprocess step. Like this:</p> <pre> public void myMethod() { Debug.traceMethod("myMethod"); int var = 1; Debug.newLine(); var++; Debug.newLine(); ... } </pre>
42,963
<p>I'm trying to use the Windows API to set the primary monitor. It doesn't seem to work - my screen just flicks and nothing happens.</p> <pre><code> public const int DM_ORIENTATION = 0x00000001; public const int DM_PAPERSIZE = 0x00000002; public const int DM_PAPERLENGTH = 0x00000004; public const int DM_PAPERWIDTH = 0x00000008; public const int DM_SCALE = 0x00000010; public const int DM_POSITION = 0x00000020; public const int DM_NUP = 0x00000040; public const int DM_DISPLAYORIENTATION = 0x00000080; public const int DM_COPIES = 0x00000100; public const int DM_DEFAULTSOURCE = 0x00000200; public const int DM_PRINTQUALITY = 0x00000400; public const int DM_COLOR = 0x00000800; public const int DM_DUPLEX = 0x00001000; public const int DM_YRESOLUTION = 0x00002000; public const int DM_TTOPTION = 0x00004000; public const int DM_COLLATE = 0x00008000; public const int DM_FORMNAME = 0x00010000; public const int DM_LOGPIXELS = 0x00020000; public const int DM_BITSPERPEL = 0x00040000; public const int DM_PELSWIDTH = 0x00080000; public const int DM_PELSHEIGHT = 0x00100000; public const int DM_DISPLAYFLAGS = 0x00200000; public const int DM_DISPLAYFREQUENCY = 0x00400000; public const int DM_ICMMETHOD = 0x00800000; public const int DM_ICMINTENT = 0x01000000; public const int DM_MEDIATYPE = 0x02000000; public const int DM_DITHERTYPE = 0x04000000; public const int DM_PANNINGWIDTH = 0x08000000; public const int DM_PANNINGHEIGHT = 0x10000000; public const int DM_DISPLAYFIXEDOUTPUT = 0x20000000; public const int ENUM_CURRENT_SETTINGS = -1; public const int CDS_UPDATEREGISTRY = 0x01; public const int CDS_TEST = 0x02; public const int CDS_SET_PRIMARY = 0x00000010; public const long DISP_CHANGE_SUCCESSFUL = 0; public const long DISP_CHANGE_RESTART = 1; public const long DISP_CHANGE_FAILED = -1; public const long DISP_CHANGE_BADMODE = -2; public const long DISP_CHANGE_NOTUPDATED = -3; public const long DISP_CHANGE_BADFLAGS = -4; public const long DISP_CHANGE_BADPARAM = -5; public const long DISP_CHANGE_BADDUALVIEW = -6; public static void SetPrimary(Screen screen) { DISPLAY_DEVICE d = new DISPLAY_DEVICE(); DEVMODE dm = new DEVMODE(); d.cb = Marshal.SizeOf(d); uint deviceID = 1; User_32.EnumDisplayDevices(null, deviceID, ref d, 0); // User_32.EnumDisplaySettings(d.DeviceName, 0, ref dm); dm.dmPelsWidth = 2560; dm.dmPelsHeight = 1600; dm.dmPositionX = screen.Bounds.Right; dm.dmFields = DM_POSITION | DM_PELSWIDTH | DM_PELSHEIGHT; User_32.ChangeDisplaySettingsEx(d.DeviceName, ref dm, IntPtr.Zero, CDS_SET_PRIMARY, IntPtr.Zero); } </code></pre> <p>I call the method like this:</p> <pre><code>SetPrimary(Screen.AllScreens[1]) </code></pre> <p>Any ideas?</p>
<p>I ran into exactly the same problem, both from C# and after following the advice here to try it in C++. I eventually discovered that the thing the Microsoft documentation doesn't make clear is that the request to set the primary monitor will be ignored (but with the operation reported as successful!) unless you also set the position of the monitor to (0, 0) on the DEVMODE struct. Of course, this means that you also need to shift the positions of your other monitors so that they stay in the same place relative to the new primary monitor. Per the documentation (<a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd183413%28v=vs.85%29.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/windows/desktop/dd183413%28v=vs.85%29.aspx</a>), call ChangeDisplaySettingsEx for each monitor with the CDS_NORESET flag and then make a final call with everything null.</p> <p>The following code worked for me:</p> <pre><code> public static void SetAsPrimaryMonitor(uint id) { var device = new DISPLAY_DEVICE(); var deviceMode = new DEVMODE(); device.cb = Marshal.SizeOf(device); NativeMethods.EnumDisplayDevices(null, id, ref device, 0); NativeMethods.EnumDisplaySettings(device.DeviceName, -1, ref deviceMode); var offsetx = deviceMode.dmPosition.x; var offsety = deviceMode.dmPosition.y; deviceMode.dmPosition.x = 0; deviceMode.dmPosition.y = 0; NativeMethods.ChangeDisplaySettingsEx( device.DeviceName, ref deviceMode, (IntPtr)null, (ChangeDisplaySettingsFlags.CDS_SET_PRIMARY | ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY | ChangeDisplaySettingsFlags.CDS_NORESET), IntPtr.Zero); device = new DISPLAY_DEVICE(); device.cb = Marshal.SizeOf(device); // Update remaining devices for (uint otherid = 0; NativeMethods.EnumDisplayDevices(null, otherid, ref device, 0); otherid++) { if (device.StateFlags.HasFlag(DisplayDeviceStateFlags.AttachedToDesktop) &amp;&amp; otherid != id) { device.cb = Marshal.SizeOf(device); var otherDeviceMode = new DEVMODE(); NativeMethods.EnumDisplaySettings(device.DeviceName, -1, ref otherDeviceMode); otherDeviceMode.dmPosition.x -= offsetx; otherDeviceMode.dmPosition.y -= offsety; NativeMethods.ChangeDisplaySettingsEx( device.DeviceName, ref otherDeviceMode, (IntPtr)null, (ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY | ChangeDisplaySettingsFlags.CDS_NORESET), IntPtr.Zero); } device.cb = Marshal.SizeOf(device); } // Apply settings NativeMethods.ChangeDisplaySettingsEx(null, IntPtr.Zero, (IntPtr)null, ChangeDisplaySettingsFlags.CDS_NONE, (IntPtr)null); } </code></pre> <p>Note that a signature for ChangeDisplaySettingsEx with a DEVMODE struct as the second parameter obviously won't allow you to pass in IntPtr.Zero. Create yourself two different signatures for the same extern call, i.e.</p> <pre><code> [DllImport("user32.dll")] public static extern DISP_CHANGE ChangeDisplaySettingsEx(string lpszDeviceName, ref DEVMODE lpDevMode, IntPtr hwnd, ChangeDisplaySettingsFlags dwflags, IntPtr lParam); [DllImport("user32.dll")] public static extern DISP_CHANGE ChangeDisplaySettingsEx(string lpszDeviceName, IntPtr lpDevMode, IntPtr hwnd, ChangeDisplaySettingsFlags dwflags, IntPtr lParam); </code></pre>
<p>I can't really help you with the winapi-stuff but if you are using a Nvidia card you may have a look at the <a href="http://developer.download.nvidia.com/SDK/9.5/Samples/DEMOS/common/src/NvCpl/docs/NVControlPanel_API.pdf" rel="nofollow noreferrer">NVcontrolPanel Api Documentation</a> Then you could make the secondary output your primary using <code>rundll32.exe NvCpl.dll,dtcfg primary 2</code> Hope that will help you.</p>
23,717
<p>Delphi 2009 introduced a hierarchical system for project options configuration, where you set "base" options and then have different build styles with their own option sets. But can you extend the hierarchy even further? I do most of my coding with debug options on, of course, but sometimes there are special cases where I want a slightly different set of debug options. I'd really like to be able to set up a basic debug configuration and then three more specific configurations underneath it, but I can't find any option to do this. Is it not possible in D2009, or am I just missing something?</p>
<p>Yes, it's straightforward.</p> <p>In the project manager, just right-click on the "Debug" configuration, and select "New Configuration". Your new configuration will appear as descended from "Debug" in the way that you expect.</p>
<p>Build Configurations are completely hierarchical. You can create any depth of hierarchies that you want in your configurations. Any build configuration can be descended from, and the hierarchies can be as deep as you like.</p> <p>In addition, you can use Option Sets to alter any given configuration. Save an Option Set in a file and apply it to any configuration that you like at any time. </p> <p>I think it is safe to say that the Build Configuration System in Delphi 2009 is about as flexible and powerful as you'd want it to be.</p>
33,247
<p>I need to have a routine/function/stored proc/whatever to archive particular accounts from our 'active' table, to an inactive table.</p> <p>I can write this out as a group of queries, all executed in order by PHP one at a time, but I'm looking to offload most of the work to mysql because it's not necessary for PHP to be involved here.</p> <p>Basically, this would get all the data:</p> <pre><code>insert into credit_archive_acc select * from credit_acc where uid_usr = n; delete from credit_acc where uid_usr =n; insert into user_archive_usr select * from user_usr where id_usr = n; delete from user_usr where id_usr = n; </code></pre> <p>(about 3 other tables I'll do this to)</p> <p>Anyway, I'd like to just be able to do something like: call archive_account(n); and have that do all the work (and as a transaction with rollback if it fails)</p> <p>Am I asking too much of mysql?</p>
<p>You might want to use scheduled tasks aka events if you want this to be run daily, automatically. You can read about them in the MySQL documentation <a href="http://dev.mysql.com/tech-resources/articles/event-feature.html" rel="nofollow noreferrer">here</a>.</p> <p>Keep in mind you need to use MySQL 5.1.6 or newer to do this, if not, time to upgrade (there's been some noteworthy speed improvements in the new version anyway).</p>
<p>You might want to use scheduled tasks aka events if you want this to be run daily, automatically. You can read about them in the MySQL documentation <a href="http://dev.mysql.com/tech-resources/articles/event-feature.html" rel="nofollow noreferrer">here</a>.</p> <p>Keep in mind you need to use MySQL 5.1.6 or newer to do this, if not, time to upgrade (there's been some noteworthy speed improvements in the new version anyway).</p>
48,203
<p>My application has a WCF service tier between the front-end and the database. Since we currently host in IIS6 we are using SOAP over HTTP. How can I find out how much real world time I am spending doing serialization activities in my application?</p>
<p>Not about measuring - but about improving: I've been working on <a href="http://code.google.com/p/protobuf-net/" rel="nofollow noreferrer">protobuf-net</a>, an implementation of Google's "protocol buffers" (a compact, low-CPU binary serialization format) for use with .NET - including a WCF hook (to replace the DataContractSerializer). It has some <a href="http://code.google.com/p/protobuf-net/wiki/Performance" rel="nofollow noreferrer">pretty good metrics</a> re serialization.</p> <p>When used with the basic http binding, it also works with MTOM, so you don't even get the base-64 overhead of binary. There is a WCF sample <a href="http://code.google.com/p/protobuf-net/source/browse/#svn/trunk/WcfPerfTest" rel="nofollow noreferrer">here</a>.</p> <p>It might be of interest...</p>
<p>One of the dead simple things old mainframes always used to to was to include a "sever time" field in the response. Therefore you'd know that anything that happened between your observed time and server time is network/serialization overhead. I know it kind of 1960-ish, but it still works well.</p> <p>If you want avoid changing the method signature you can set it in a http response header or something ;)</p>
32,002
<p>I've been a longtime ASP.NET developer in the web forms model, and am using a new project as an opportunity to get my feet wet with ASP.NET MVC.</p> <p>The application will need an API so that a group of other apps can communicate with it. I've always built API's out just using a standard web service prior to this.</p> <p>As a sidenote, I'm a little hesitant to plunge headfirst into the REST style of creating API's, for this particular instance at least. This application will likely need a concept of API versioning, and I think that the REST approach, where the API is essentially scattered across all the controllers of the site, is a little cumbersome in that regard. (But I'm not completely opposed to it if there is a good answer to the potential versioning potential requirement.)</p> <p>So, what say ye, Stack Overflow denizens?</p>
<p>I'd agree with Kilhoffer. Try using a "Facade" wrapper class that inherits from an "IFacade". In your Facade class put your code to consume your web service. In this way your controllers will simply make calls to the Facade. The plus side of this being that you can swap a "DummyFacade" that implements the same IFacade interface in that doesn't actually talk to the web service and just returns static content. Lets you actually do some unit testing without hitting the service. Basically the same idea as the Repository pattern.</p>
<p>I would still recommend a service layer that can serve client side consumers or server side consumers. Possibly even returning data in a variety of formats, depending on the consuming caller.</p>
16,333
<p>I've got a SQLServer Database and an application (.NET) that configures data on that database. On the other hand, I've got an application (VC++) that reads that data from the database and must be 'informed' a soon as possible of any change in the data saved on the database.</p> <p>I would like to receive a signal from the database engine when some data had been changed by the first app. Of course, I can code some kind of message that comunicates both apps but my question is if exists that mechanism (some kind of ultra-trigger that warns the other app) in SQLServer or in any API for accessing SQLServer (Native, OLE DB, or even ODBC)</p> <p>PS: Apologize for my english</p>
<p>You can use a SQL Agent Job that will notify the other app starting it with sp_start_job. Check <a href="http://www.windows-tech.info/15/830e5ff5a0c026bf.php" rel="nofollow noreferrer">this</a> out.</p>
<p>You can use a SQL Agent Job that will notify the other app starting it with sp_start_job. Check <a href="http://www.windows-tech.info/15/830e5ff5a0c026bf.php" rel="nofollow noreferrer">this</a> out.</p>
41,383
<p>I understand how Lucene.net can work for text indexing. Will I be able to efficiently search for documents based on a given date range? Or will Lucene.net just use text matching to match the dates?</p>
<p>Lucene.Net will just use text matching, so you'd need to format the dates correctly before adding to the index:</p> <pre><code> public static string Serialize(DateTime dateTime) { return dateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture); } public static DateTime Deserialize(string str) { return DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); } </code></pre> <p>You can then, for example, perform a range based query to filter by date (e.g. 2006* to 2007* to include all dates in 2006 and 2007).</p>
<p>I went in to trouble when i converted date in to <code>yyyymmddHHmmssff</code>. When i tried sorting the data, it gave me an exception that too big to convert..something. Hence i search and found then you need to have two columns. one in <code>yyyymmdd</code> and the other <code>HHmmss</code>, and then use <code>Sort[]</code> and give these two columns and then use. This will solve the issue.</p>
37,920
<p>I need to change in a text input the character '.' to ',' while typing. In IE I change the keyCode event property in the keypress event, like this</p> <pre><code>document.getElementById('mytext').onkeypress = function (evt) { var e = evt || window.event; if (e.keyCode &amp;&amp; e.keyCode==46) e.keyCode = 44; else if (e.which &amp;&amp; e.which==46) { e.which = 44; } }; </code></pre> <p>but it seemes that in Firefox it's impossible to change characters typed in key events. Any suggestions?</p>
<p>Try this. It works on all browsers:</p> <pre><code>window.onload = function () { var input = document.getElementById("mytext"); input.onkeypress = function () { var evt = arguments[0] || event; var char = String.fromCharCode(evt.which || evt.keyCode); // Is it a period? if (char == ".") { // Replace it with a comma input.value += ","; // Cancel the original event evt.cancelBubble = true; return false; } } }; </code></pre> <p><strong>Update:</strong> <strong>Pier Luigi</strong> pointed out a problem with the above. It doesn't take care of the caret position not being at the end of the text. It will append the command to the end even if you're inserting some text to the value.</p> <p>The solution would be, instead of appending a comma, to simulate a keypress event for the comma key. Unfortunately the way dispatching of synthetic events work in different browsers seems to show a lot of variety and isn't an easy feat. I'll see if I can find a nice and generic method for it.</p>
<p>Does this really need to be done on the fly? If you are collecting the information to be posted to a form or submitted to a database, would it not be better to modify the data once it was submitted? That way the user never sees the confusing change.</p>
26,848
<p>I am intercepting Win32 API calls a native dll or exe is doing from C# using some kind of hooking. In this particular case I am interested in DrawText() in user32.dll. It is declared like this in Win32 API:</p> <pre><code>INT WINAPI DrawTextW(HDC hdc, LPCWSTR str, INT count, LPRECT rect, UINT flags) </code></pre> <p>The LPRECT struct has the following signature (also in Win32 API):</p> <pre><code>typedef struct tagRECT { LONG left; LONG top; LONG right; LONG bottom; } RECT LPRECT; </code></pre> <p>LONG is a typedef for 32bit integers on 32bit systems (don't know about 64bit systems, it is irrelevant at this point because I am on 32bit Windows). To be able to access the members of this struct I declared it in my C# code...</p> <pre><code>[StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RECT { public Int32 left; public Int32 top; public Int32 right; public Int32 bottom; } </code></pre> <p>... and wrote the signature of P/Invoke using this RECT struct:</p> <pre><code>[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true, CallingConvention = CallingConvention.StdCall)] static extern IntPtr DrawText(IntPtr HDC, String str, Int32 count, ref RECT rect, UInt32 flags, IntPtr dtp); </code></pre> <p>Since structs are value types in C# as opposed to being reference types like in C/C++, the ref modifier is necessary here.</p> <p>However when I use <code>rect.top rect.left</code> etc, they almost always return 0. I know for a fact that this is incorrect. But after googling countless hours and trying a lot of different things, I couldn't make this simple stuff work.</p> <p>Things I've tried:</p> <ul> <li>Using different primitives for RECT members (int, long, short, UInt32...). Actually it is kinda obvious that this is not a type problem because in any case I should see some garbled numbers, not 0.</li> <li>Removing ref modifier. This is also stupid (desperate times, desperate measures) because rect.left correctly returns the pointer to rect instead of its value.</li> <li>Tried <code>unsafe</code> code blocks. Didn't work but I may have made a mistake in the implementation (I don't remember what I've done). Besides this approach is generally reserved for tricky pointer situations in COM and Win32, it is overkill for my case anyway.</li> <li>Tried adding <code>[MarshallAs]</code> before the members of RECT. Made no difference.</li> <li>Played around with <code>Pack</code> values. No difference.</li> </ul> <p>I am fairly sure that I'm missing something very easy and straightforward but I have no idea what it is...</p> <p>Any help is appreciated. Thank you.</p>
<p><a href="http://www.pinvoke.net/default.aspx/user32.DrawText" rel="noreferrer">http://www.pinvoke.net/default.aspx/user32.DrawText</a></p>
<p>Part of the problem is the use of String where a StringBuilder should be used. </p> <p>Try this signature (Generated with <a href="http://codeplex.com/clrinterop" rel="nofollow noreferrer">PInvoke Interop Assistant</a>)</p> <pre><code> [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct tagRECT { /// LONG->int public int left; /// LONG->int public int top; /// LONG->int public int right; /// LONG->int public int bottom; } public partial class NativeMethods { /// Return Type: int ///hdc: HDC->HDC__* ///lpchText: LPCWSTR->WCHAR* ///cchText: int ///lprc: LPRECT->tagRECT* ///format: UINT->unsigned int [System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint="DrawTextW")] public static extern int DrawTextW([System.Runtime.InteropServices.InAttribute()] System.IntPtr hdc, [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] System.Text.StringBuilder lpchText, int cchText, ref tagRECT lprc, uint format) ; } </code></pre>
24,855
<p>I just set up my new homepage at <a href="http://ritter.vg" rel="noreferrer">http://ritter.vg</a>. I'm using jQuery, but very minimally.<br> It loads all the pages using AJAX - I have it set up to allow bookmarking by detecting the hash in the URL. </p> <pre><code> //general functions function getUrl(u) { return u + '.html'; } function loadURL(u) { $.get(getUrl(u), function(r){ $('#main').html(r); } ); } //allows bookmarking var hash = new String(document.location).indexOf("#"); if(hash &gt; 0) { page = new String(document.location).substring(hash + 1); if(page.length &gt; 1) loadURL(page); else loadURL('news'); } else loadURL('news'); </code></pre> <p>But I can't get the back and forward buttons to work. </p> <p>Is there a way to detect when the back button has been pressed (or detect when the hash changes) without using a setInterval loop? When I tried those with .2 and 1 second timeouts, it pegged my CPU.</p>
<p>Use the <a href="https://github.com/cowboy/jquery-hashchange" rel="noreferrer">jQuery hashchange event</a> plugin instead. Regarding your full ajax navigation, try to have <a href="http://www.chazzuka.com/blog/?p=90" rel="noreferrer">SEO friendly ajax</a>. Otherwise your pages shown nothing in browsers with JavaScript limitations.</p>
<p>I do the following, if you want to use it then paste it in some where and set your handler code in locationHashChanged(qs) where commented, and then call changeHashValue(hashQuery) every time you load an ajax request. Its not a quick-fix answer and there are none, so you will need to think about it and pass sensible hashQuery args (ie a=1&amp;b=2) to changeHashValue(hashQuery) and then cater for each combination of said args in your locationHashChanged(qs) callback ...</p> <pre><code>// Add code below ... function locationHashChanged(qs) { var q = parseQs(qs); // ADD SOME CODE HERE TO LOAD YOUR PAGE ELEMS AS PER q !! // YOU SHOULD CATER FOR EACH hashQuery ATTRS COMBINATION // THAT IS PASSED TO changeHashValue(hashQuery) } // CALL THIS FROM YOUR AJAX LOAD CODE EACH LOAD ... function changeHashValue(hashQuery) { stopHashListener(); hashValue = hashQuery; location.hash = hashQuery; startHashListener(); } // AND DONT WORRY ABOUT ANYTHING BELOW ... function checkIfHashChanged() { var hashQuery = getHashQuery(); if (hashQuery == hashValue) return; hashValue = hashQuery; locationHashChanged(hashQuery); } function parseQs(qs) { var q = {}; var pairs = qs.split('&amp;'); for (var idx in pairs) { var arg = pairs[idx].split('='); q[arg[0]] = arg[1]; } return q; } function startHashListener() { hashListener = setInterval(checkIfHashChanged, 1000); } function stopHashListener() { if (hashListener != null) clearInterval(hashListener); hashListener = null; } function getHashQuery() { return location.hash.replace(/^#/, ''); } var hashListener = null; var hashValue = '';//getHashQuery(); startHashListener(); </code></pre>
20,843
<pre><code>- Unit Testing - Mocking - Inversion of Control - Refactoring - Object Relational Mapping - Others? </code></pre> <p>I have found <a href="http://www.lastcraft.com/simple_test.php" rel="nofollow noreferrer">simpletest</a> for unit testing and mocking and, though it leaves much to be desired, it kind-of sort of works.</p> <p>I have yet to find any reasonable Inversion of Control framework (there is one that came up on phpclasses but no documentation and doesn't seem like anyone's tried it).</p>
<p><a href="http://www.phpundercontrol.org/" rel="nofollow noreferrer">phpUnderControl</a> - continuous integration.</p> <p>Don't forget about version control (e.g. using <a href="http://www.nongnu.org/cvs/" rel="nofollow noreferrer">CVS</a> or <a href="http://subversion.tigris.org/" rel="nofollow noreferrer">Subversion</a>)!</p>
<p>Unit Testing - PHPUnit <a href="http://www.phpunit.de/" rel="nofollow noreferrer">phpunit.de</a></p> <p>ORM - Doctrine <a href="http://www.phpdoctrine.org/" rel="nofollow noreferrer">phpdoctrine.org</a>, Propel <a href="http://propel.phpdb.org/" rel="nofollow noreferrer">propel.phpdb.org</a></p>
7,311
<p>I'm in the process of learning Erlang. As an exercise I picked up the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="noreferrer">Sieve of Eratosthenes</a> algorithm of generating prime numbers. Here is my code:</p> <pre><code>-module(seed2). -export([get/1]). get(N) -&gt; WorkList = lists:duplicate(N, empty), get(2, N, WorkList, []). get(thats_the_end, _N, _WorkList, ResultList) -&gt; lists:reverse(ResultList); get(CurrentPrime, N, WorkList, ResultList) -&gt; ModWorkList = markAsPrime(CurrentPrime, N, WorkList), NextPrime = findNextPrime(CurrentPrime + 1, N, WorkList), get(NextPrime, N, ModWorkList, [CurrentPrime|ResultList]). markAsPrime(CurrentPrime, N, WorkList) when CurrentPrime =&lt; N -&gt; WorkListMod = replace(CurrentPrime, WorkList, prime), markAllMultiples(CurrentPrime, N, 2*CurrentPrime, WorkListMod). markAllMultiples(_ThePrime, N, TheCurentMark, WorkList) when TheCurentMark &gt; N -&gt; WorkList; markAllMultiples(ThePrime, N, TheCurrentMark, WorkList) -&gt; WorkListMod = replace(TheCurrentMark, WorkList, marked), markAllMultiples(ThePrime, N, TheCurrentMark + ThePrime, WorkListMod). findNextPrime(Iterator, N, _WorkList) when Iterator &gt; N -&gt; thats_the_end; findNextPrime(Iterator, N, WorkList) -&gt; I = lists:nth(Iterator, WorkList), if I =:= empty -&gt; Iterator; true -&gt; findNextPrime(Iterator + 1, N, WorkList) end. replace(N, L, New)-&gt; {L1, [_H|L2]} = lists:split(N - 1, L), lists:append(L1, [New|L2]). </code></pre> <p>This code actually works :) . The problem is that I have this feeling that it is not the best possible implementation. </p> <p>My question is what would be the "erlangish" way of implementing the "Sieve of Eratosthenes"</p> <p>EDIT: OK, Andreas solution is very good but it is slow. Any ideas how to improve that? </p>
<p>Here's a simple (but not terribly fast) sieve implementation:</p> <pre><code>-module(primes). -export([sieve/1]). -include_lib("eunit/include/eunit.hrl"). sieve([]) -&gt; []; sieve([H|T]) -&gt; List = lists:filter(fun(N) -&gt; N rem H /= 0 end, T), [H|sieve(List)]; sieve(N) -&gt; sieve(lists:seq(2,N)). </code></pre>
<p>my fastest code so far (faster than Andrea's) is with using array:</p> <pre><code>-module(seed4). -export([get/1]). get(N) -&gt; WorkList = array:new([{size, N}, {default, empty}]), get(2, N, WorkList, []). get(thats_the_end, _N, _WorkList, ResultList) -&gt; lists:reverse(ResultList); get(CurrentPrime, N, WorkList, ResultList) -&gt; ModWorkList = markAsPrime(CurrentPrime, N, WorkList), NextPrime = findNextPrime(CurrentPrime + 1, N, WorkList), get(NextPrime, N, ModWorkList, [CurrentPrime|ResultList]). markAsPrime(CurrentPrime, N, WorkList) when CurrentPrime =&lt; N -&gt; WorkListMod = replace(CurrentPrime, WorkList, prime), markAllMultiples(CurrentPrime, N, 2*CurrentPrime, WorkListMod). markAllMultiples(_ThePrime, N, TheCurentMark, WorkList) when TheCurentMark &gt; N -&gt; WorkList; markAllMultiples(ThePrime, N, TheCurrentMark, WorkList) -&gt; WorkListMod = replace(TheCurrentMark, WorkList, marked), markAllMultiples(ThePrime, N, TheCurrentMark + ThePrime, WorkListMod). findNextPrime(Iterator, N, _WorkList) when Iterator &gt; N -&gt; thats_the_end; findNextPrime(Iterator, N, WorkList) -&gt; I = array:get(Iterator - 1, WorkList), if I =:= empty -&gt; Iterator; true -&gt; findNextPrime(Iterator + 1, N, WorkList) end. replace(N, L, New) -&gt; array:set(N - 1, New, L). </code></pre>
17,654
<p>I wish to implement my software on a shareware basis, so that the user is given a maximum trial period of (say) 30 days with which to try out the software. On purchase I intend the user to be given a randomly-generated key, which when entered enables the software again.</p> <p>I've never been down this route before, so any advice or feedback or pointers to 'standard' ways of how this is done would be much appreciated.</p> <p>I do not anticipate users cheating by changing the system date or anything like that, though this is probably worth considering. Apologies if this topic has appeared before.</p>
<p>With regards to a random-generated key, how will you verify a key is legit or if a key is bogus if it is actually random? Have a look at the article "<a href="http://www.brandonstaggs.com/2007/07/26/implementing-a-partial-serial-number-verification-system-in-delphi/" rel="nofollow noreferrer">Implementing a Partial Serial Number Verification System</a>" as it is quite good and is easy to implement in any language.</p> <p>With regards to time trials, as basic solution would be to compare your main executable files creation time to the current system time and act on the difference. This assumes your installer sets the files creation time to the time of install as opposed to preserving the time you compiled it! :)</p>
<p>On the first start, you can store the actual date somewhere.<br> Each following start, you look for the stored date, if it exist you read it an if it is more than 30 days after the first start, you stop the program.</p>
20,962
<p>I would like to create (in code) tree of controls that would render as a table with several TBODY tags, i.e.:</p> <p> </p> <pre><code>&lt;TBODY&gt; &lt;TR&gt; &lt;TD&gt;&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD&gt;&lt;/TD&gt; &lt;/TR&gt; &lt;/TBODY&gt; </code></pre> <p></p> <p>I tried both Table and HtmlTable controls but had no success. Any clues?</p>
<p>How are you generating your data? You could use a templated control like a Repeater or ListView as that gives you full control of the HTML you're generating.</p> <p>If you're wanting to create the controls purely in C# you can use the HtmlGenericControl (<a href="http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlgenericcontrol.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlgenericcontrol.aspx</a>), you'll need to provide a tag type in the constructor.</p>
<p>I am writing a class that implements IBindableTemplate, so all of the rendering has to be done in code. I will give the HtmlGenericControl a try. Thanks!</p>
24,968
<p>I have the following enum declared:</p> <pre><code> public enum TransactionTypeCode { Shipment = 'S', Receipt = 'R' } </code></pre> <p>How do I get the value 'S' from a TransactionTypeCode.Shipment or 'R' from TransactionTypeCode.Receipt ?</p> <p>Simply doing TransactionTypeCode.ToString() gives a string of the Enum name "Shipment" or "Receipt" so it doesn't cut the mustard.</p>
<p>You have to check the underlying type of the enumeration and then convert to a proper type:</p> <pre><code>public enum SuperTasks : int { Sleep = 5, Walk = 7, Run = 9 } private void btnTestEnumWithReflection_Click(object sender, EventArgs e) { SuperTasks task = SuperTasks.Walk; Type underlyingType = Enum.GetUnderlyingType(task.GetType()); object value = Convert.ChangeType(task, underlyingType); // x will be int } </code></pre>
<p>Marking this as not correct, but I can't delete it.</p> <p>Try this:</p> <pre><code>string value = (string)TransactionTypeCode.Shipment; </code></pre>
12,287
<p>With ASP.NET's view engine/template aspx/ashx pages the way to spit to screen seems to be: </p> <pre><code>&lt;%= Person.Name %&gt; </code></pre> <p>Which was fine with webforms as alot of model data was bound to controls programatically. But with MVC we are now using this syntax more oftern. </p> <p>The issue I have with it is quite trivial, but annoying either way. This is that it seems to break up the mark up i.e.:</p> <pre><code>&lt;% foreach(var Person in People) { %&gt; &lt;%= Person.Name %&gt; &lt;% } %&gt; </code></pre> <p>That seems like alot of opening and closing tags to me!</p> <p>Other view engines in the MVC contrib have a means of spitting to screen with out opening and closing the script tags using standard keyword such as "print, out, echo" i.e. (brail example):</p> <pre><code>&lt;% for element in list: output "&lt;li&gt;${element}&lt;/li&gt;" end %&gt; </code></pre> <p>Now, I said this may seem trivial, but it just seems more readable this way. So what are the advantages of MS having this syntax, and not providing a output method?</p> <p>Cheers, Chris.</p>
<p>Consider something like this, instead:</p> <pre><code>&lt;% foreach(var Person in People) { Response.Write(Person.Name); } %&gt; </code></pre> <p>I believe that'll work. (Although I haven't tested it; I've only just begun with MVC and don't have the toolset here at the office.)</p> <p>EDIT: I apparently missed the actual question ... :)</p> <p>Microsoft does provide an output method, but didn't provide a syntax like the one you describe. The output method is <code>Response.Write()</code>. I can't answer this directly (I believe you'll need to check with Scott Hanselmann over at MS :)), but I think they didn't want to complicate scripting by adding yet-another-language for us to learn; I think they wanted to leverage the languages (C#, VB, etc.) which developers already knew.</p> <p>EDIT #2: I placed the following in a comment, and in retrospect (for completeness), it should be part of the answer.</p> <p>If you head over to the <a href="http://www.asp.net/learn/mvc/tutorial-04-cs.aspx" rel="noreferrer">Learn MVC site on ASP.NET</a>, in the view tutorial (that's the link), you'll see the following paragraph:</p> <blockquote> <p>Since you call <code>Response.Write()</code> so often, Microsoft provides you with a shortcut for calling the <code>Response.Write()</code> method. The view in Listing 3 uses the delimiters <code>&lt;%=</code> and <code>%&gt;</code> as a shortcut for calling <code>Response.Write()</code>.</p> </blockquote> <p>Essentially, <code>&lt;%= %&gt;</code> is the accepted shortcut for <code>Response.Write</code>, and you therefore can use the full <code>Response.Write</code> method anywhere you'd use <code>&lt;%= %&gt;</code>.</p>
<p>What you're looking for is probably a different View engine -- they each handle embedded code like that in their own way. Check out <a href="http://andrewpeters.net/2007/12/19/introducing-nhaml-an-aspnet-mvc-view-engine/" rel="nofollow noreferrer">NHaml</a>, an ASP.Net port of Rails' <a href="http://haml.hamptoncatlin.com/" rel="nofollow noreferrer">Haml</a> engine.</p> <p>Some more view engines to look at: <a href="http://www.codeplex.com/MVCContrib/Wiki/View.aspx?title=Brail&amp;referringTitle=Documentation" rel="nofollow noreferrer">Brail</a>, <a href="http://nvelocity.sourceforge.net/index.html" rel="nofollow noreferrer">NVelocity</a></p>
24,048
<p>Is anyone aware of general UI design guidelines for increasing ad revenue from web ads? Obviously many SO users use adblock, and probably find this type of question reprehensible, but I believe that it is possible to integrate advertising (and other revenue streams) into sites so that they are visually appealing, on-target, and functional. However, this is only a belief ;).</p> <p>Given the widespread use of advertising as a means of income, this seems like it must be an active area of research.</p> <p>I believe that any web design that is intended to generate income should take this into account, since the web designer (read: a sizable portion of the SO user base) should be trying to get the biggest return on their time/skills.</p> <p>(This question is a repost because there is <em>no</em>way* on SO to contest a 'closed question', and it only takes one person with enough rep to decide they don't like it.)</p> <p><strong>Edit:</strong> Just incase anyone goes looking, I deleted the initial question (which was closed) since it didn't make sense to pollute the search results.</p>
<p>In fact, <a href="https://stackoverflow.com/users/1">one of the people who created this site</a> made a <a href="http://www.codinghorror.com/blog/archives/000893.html" rel="nofollow noreferrer">post regarding this</a> on his <a href="http://www.codinghorror.com/" rel="nofollow noreferrer">blog</a> </p>
<p>You may be interested in seeing <a href="https://www.google.com/adsense/support/bin/answer.py?hl=en&amp;answer=17954" rel="nofollow noreferrer">what Google has to say</a> about the placement of ads.</p>
14,369
<p>I have an object.</p> <pre><code> fp = open(self.currentEmailPath, "rb") p = email.Parser.Parser() self._currentEmailParsedInstance= p.parse(fp) fp.close() </code></pre> <p>self.currentEmailParsedInstance, from this object I want to get the body of an email, text only no HTML....</p> <p>How do I do it?</p> <hr> <p>something like this? </p> <pre><code> newmsg=self._currentEmailParsedInstance.get_payload() body=newmsg[0].get_content....? </code></pre> <p>then strip the html from body. just what is that .... method to return the actual text... maybe I mis-understand you</p> <pre><code> msg=self._currentEmailParsedInstance.get_payload() print type(msg) </code></pre> <p>output = type 'list'</p> <hr> <p>the email </p> <p>Return-Path: <br> Received: from xx.xx.net (example) by mxx3.xx.net (xxx)<br> id 485EF65F08EDX5E12 for xxx@xx.com; Thu, 23 Oct 2008 06:07:51 +0200<br> Received: from xxxxx2 (ccc) by example.net (ccc) (authenticated as xxxx.xxx@example.com) id 48798D4001146189 for example.example@example-example.com; Thu, 23 Oct 2008 06:07:51 +0200<br> From: "example" <br> To: <br> Subject: FW: example Date: Thu, 23 Oct 2008 12:07:45 +0800<br> Organization: example Message-ID: &lt;001601c934c4$xxxx30$a9ff460a@xxx><br> MIME-Version: 1.0<br> Content-Type: multipart/mixed;<br> boundary="----=_NextPart_000_0017_01C93507.F6F64E30"<br> X-Mailer: Microsoft Office Outlook 11<br> X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3138<br> Thread-Index: Ack0wLaumqgZo1oXSBuIpUCEg/wfOAABAFEA </p> <p>This is a multi-part message in MIME format. </p> <p>------=_NextPart_000_0017_01C93507.F6F64E30<br> Content-Type: multipart/alternative;<br> boundary="----=_NextPart_001_0018_01C93507.F6F64E30" </p> <p>------=_NextPart_001_0018_01C93507.F6F64E30<br> Content-Type: text/plain;<br> charset="us-ascii"<br> Content-Transfer-Encoding: 7bit </p> <p>From: example.example[mailto:example@example.com]<br> Sent: Thursday, October 23, 2008 11:37 AM<br> To: xxxx@example.com<br> Subject: S/I for example(B/L<br> No.:4357-0120-810.044) </p> <p>Please find attached the example.doc), </p> <p>Thanks. </p> <p>B.rgds, </p> <p>xxx xxx </p> <p>------=_NextPart_001_0018_01C93507.F6F64E30<br> Content-Type: text/html;<br> charset="us-ascii"<br> Content-Transfer-Encoding: quoted-printable </p> <p> xmlns:o=3D"urn:schemas-microsoft-com:office:office" =<br> xmlns:w=3D"urn:schemas-microsoft-com:office:word" =<br> xmlns:st1=3D"urn:schemas-microsoft-com:office:smarttags" =<br> xmlns=3D"<a href="http://www.w3.org/TR/REC-html40" rel="nofollow noreferrer">http://www.w3.org/TR/REC-html40</a>"> </p> <p>HTML STUFF till </p> <p>------=_NextPart_001_0018_01C93507.F6F64E30-- </p> <p>------=_NextPart_000_0017_01C93507.F6F64E30<br> Content-Type: application/msword;<br> name="xxxx.doc"<br> Content-Transfer-Encoding: base64<br> Content-Disposition: attachment;<br> filename="xxxx.doc" </p> <p>0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAABAAAAYAAAAAAAAAAA EAAAYgAAAAEAAAD+////AAAAAF8AAAD///////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////s pcEAI2AJBAAA+FK/AAAAAAAAEAAAAAAABgAAnEIAAA4AYmpiaqEVoRUAAAAAAAAAAAAAAAAAAAAA AAAECBYAMlAAAMN/AADDfwAAQQ4AAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAA AAAAAAD//w8AAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAKQAAAAAAEYEAAAAAAAARgQAAEYE AAAAAAAARgQAAAAAAABGBAAAAAAAAEYEAAAAAAAARgQAABQAAAAAAAAAAAAAAFoEAAAAAAAA4hsA AAAAAADiGwAAAAAAAOIbAAA4AAAAGhwAAHwAAACWHAAARAAAAFoEAAAAAAAABzcAAEgBAADmHAAA FgAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAA AAAAMjYAAAIAAAA0NgAAAAAAADQ2AAAAAAAANDYAAAAAAAA0NgAAAAAAADQ2AAAAAAAANDYAACQA AABPOAAAaAIAALc6AACOAAAAWDYAAGkAAAAAAAAAAAAAAAAAAAAAAAAARgQAAAAAAABHLAAAAAAA AAAAAAAAAAAAAAAAAAAAAAD8HAAAAAAAAPwcAAAAAAAARywAAAAAAABHLAAAAAAAAFg2AAAAAAAA</p> <p>------=_NextPart_000_0017_01C93507.F6F64E30-- </p> <hr> <p>I just want to get : </p> <p>From: xxxx.xxxx [mailto:xxxx@example.com]<br> Sent: Thursday, October 23, 2008 11:37 AM<br> To: xxxx@example.com<br> Subject: S/I for xxxxx (B/L<br> No.:4357-0120-810.044) </p> <p>Pls find attached the xxxx.doc), </p> <p>Thanks. </p> <p>B.rgds, </p> <p>xxx xxx </p> <hr> <p>not sure if the mail is malformed! seems if you get an html page you have to do this:</p> <pre><code> parts=self._currentEmailParsedInstance.get_payload() print parts[0].get_content_type() ..._multipart/alternative_ textParts=parts[0].get_payload() print textParts[0].get_content_type() ..._text/plain_ body=textParts[0].get_payload() print body ...get the text without a problem!! </code></pre> <p>thank you so much Vinko.</p> <p>So its kinda like dealing with xml, recursive in nature.</p>
<p>This will get you the contents of the message</p> <pre><code>self.currentEmailParsedInstance.get_payload() </code></pre> <p>As for the text only part you will have to strip HTML on your own, for example using BeautifulSoup.</p> <p>Check <a href="http://www.python.org/doc/2.2.3/lib/module-email.Message.html" rel="nofollow noreferrer">this link</a> for more information about the Message class the Parser returns. If you mean getting the text part of messages containing both HTML and plain text version of themselves, you can specify an index to get_payload() to get the part you want.</p> <p>I tried with a different MIME email because what you pasted seems malformed, hopefully it got malformed when you edited it.</p> <pre><code>&gt;&gt;&gt; parser = email.parser.Parser() &gt;&gt;&gt; message = parser.parse(open('/home/vinko/jlm.txt','r')) &gt;&gt;&gt; message.is_multipart() True &gt;&gt;&gt; parts = message.get_payload() &gt;&gt;&gt; len(parts) 2 &gt;&gt;&gt; parts[0].get_content_type() 'text/plain' &gt;&gt;&gt; parts[1].get_content_type() 'message/rfc822' &gt;&gt;&gt; parts[0].get_payload() 'Message Text' </code></pre> <p>parts will contain all parts of the multipart message, you can check their content types as shown and get only the text/plain ones, for instance.</p> <p>Good luck.</p>
<p>ended up with this</p> <pre><code> parser = email.parser.Parser() self._email = parser.parse(open('/home/vinko/jlm.txt','r')) parts=self._email.get_payload() check=parts[0].get_content_type() if check == "text/plain": return parts[0].get_payload() elif check == "multipart/alternative": part=parts[0].get_payload() if part[0].get_content_type() == "text/plain": return part[0].get_payload() else: return "cannot obtain the body of the email" else: return "cannot obtain the body of the email" </code></pre>
35,424
<p>I'm currently in the process of writing my first Windows Forms application. I've read a few C# books now so I've got a relatively good understanding of what language features C# has to deal with exceptions. They're all quite theoretical however so what I haven't got yet is a feel for how to translate the basic concepts into a good exception-handling model in my application.</p> <p>Would anyone like to share any pearls of wisdom on the subject? Post any common mistakes you've seen newbies like myself make, and any general advice on handling exceptions in a way that will my application more stable and robust.</p> <p>The main things I'm currently trying to work out are: </p> <ul> <li>When should I re-throw an exception?</li> <li>Should I try to have a central error-handling mechanism of some kind?</li> <li>Do handling exceptions which might be thrown have a performance hit compared with pre-emptively testing things like whether a file on disk exists?</li> <li>Should all executable code be enclosed in try-catch-finally blocks?</li> <li>Are there any times when an empty catch block might be acceptable?</li> </ul> <p>All advice gratefully received!</p>
<p>There is an excellent code <a href="http://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET" rel="noreferrer">CodeProject article here</a>. Here are a couple of highlights:</p> <ul> <li>Plan for the worst*</li> <li>Check it early</li> <li>Don't trust external data</li> <li>The only reliable devices are: the video, the mouse and keyboard.</li> <li>Writes can fail, too</li> <li>Code Safely</li> <li>Don't throw new Exception()</li> <li>Don't put important exception information on the Message field</li> <li>Put a single catch (Exception ex) per thread</li> <li>Generic Exceptions caught should be published</li> <li>Log Exception.ToString(); never log only Exception.Message!</li> <li>Don't catch (Exception) more than once per thread</li> <li>Don't ever swallow exceptions</li> <li>Cleanup code should be put in finally blocks</li> <li>Use "using" everywhere</li> <li>Don't return special values on error conditions</li> <li>Don't use exceptions to indicate absence of a resource</li> <li>Don't use exception handling as means of returning information from a method</li> <li>Use exceptions for errors that should not be ignored</li> <li>Don't clear the stack trace when re-throwing an exception</li> <li>Avoid changing exceptions without adding semantic value</li> <li>Exceptions should be marked [Serializable]</li> <li>When in doubt, don't Assert, throw an Exception</li> <li>Each exception class should have at least the three original constructors</li> <li>Be careful when using the AppDomain.UnhandledException event</li> <li>Don't reinvent the wheel</li> <li>Don't use Unstructured Error Handling (VB.Net)</li> </ul>
<p>You have to think about the user. The application crash is the <strong>last</strong> thing the user wants. Therefore any operation that can fail should have a try catch block at the ui level. It's not necessary to use try catch in every method, but every time the user does something it must be able to handle generic exceptions. That by no means frees you from checking everything to prevent exceptions in the first case, but there is no complex application without bugs and the OS can easily add unexpected problems, therefore you must anticipate the unexpected and make sure if a user wants to use one operation there won't be data loss because the app crashes. There is no need to ever let your app crash, if you catch exceptions it will never be in an indeterminate state and the user is ALWAYS inconvenienced by a crash. Even if the exception is at the top most level, not crashing means the user can quickly reproduce the exception or at least record the error message and therefore greatly help you to fix the problem. Certainly a lot more than getting a simple error message and then seeing only windows error dialog or something like that.</p> <p>That's why you must NEVER just be conceited and think your app has no bugs, that is not guaranteed. And it is a <em>very</em> small effort to wrap some try catch blocks about the appropriate code and show an error message / log the error.</p> <p>As a user, I certainly get seriously pissed whenever a brows or office app or whatever crashes. If the exception is so high that the app can't continue it's better to display that message and tell the user what to do (restart, fix some os settings, report the bug, etc.) than to simply crash and that's it.</p>
22,201