instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'm loading an XML document in my C# application with the following:</p> <pre><code>XDocument xd1 = new XDocument(); xd1 = XDocument.Load(myfile); </code></pre> <p>but before that, I do test to make sure the file exists with:</p> <pre><code>File.Exists(myfile); </code></pre> <p>But... is there an (easy) way to test the file before the XDocument.Load() to make sure it's a valid XML file? In other words, my user can accidentally click on a different file in the file browser and trying to load, say, a .php file causes an exception. </p> <p>The only way I can think of is to load it into a StreamWriter and simple do a text search on the first few characters to make sure they say " <p>Thanks!</p> <p>-Adeena</p>
<p>It's probably just worth catching the specific exception if you want to show a message to the user:</p> <pre><code> try { XDocument xd1 = new XDocument(); xd1 = XDocument.Load(myfile); } catch (XmlException exception) { ShowMessage("Your XML was probably bad..."); } </code></pre>
<p>I would not XDocument.Load(), as per the accepted answer; why would you read the entire file into memory, it could be a huge file?</p> <p>I'd probably read the first few bytes into a byteArray (it could even be any binary file), convert the byteArray to string e.g. <code>System.Text.Encoding.ASCII.GetString(byteArray)</code> ,check if the converted string contains the Xml elements you are expecting, only then continue.</p>
49,158
<p>I'm making a simple form to create polls, therefore I want the possibility to add additional input fields in case the user wants more options in the poll.</p> <p>I've made Javascript code that adds a new input field to the form, but the dynamically added input fields are not posted when the form is submitted (I use a standard submit button). </p> <p><strong>Is there some way to get the dynamically added fields posted/recognized as a part of the form?</strong></p> <pre><code>&lt;form id="myForm" method="post"&gt; &lt;input type="submit"&gt; &lt;input type="text" name="poll[question]"&gt; &lt;input type="text" name="poll[option1]"&gt; &lt;input type="text" name="poll[option2]"&gt; &lt;/form&gt; &lt;a href="javascript:addOption();"&gt;Add option&lt;/a&gt; &lt;script&gt; var optionNumber = 3; //The first option to be added is number 3 function addOption() { var theForm = document.getElementById("myForm"); var newOption = document.createElement("input"); newOption.name = "poll[option"+optionNumber+"]"; // poll[optionX] newOption.type = "text"; theForm.appendChild(newOption); optionNumber++; } &lt;/script&gt; </code></pre>
<p>I just debugged my site where I was having a similar issue. For me it turned out that having my table and form tags in the "wrong" order caused the issue.</p> <p>Broken:</p> <pre> table form </pre> <p>Working:</p> <pre> form table </pre> <p>This points out something pretty important. The browser may render fine, and the form may work fine, with malformed html, but you can still break things, like this, by having not having properly formatted html. Maybe I should start using mod_tidy! </p>
<p>You can always serialize the form yourself using a javascript function and then submit that (using AJAX or a get request or something).<br> <a href="http://malsup.com/jquery/form/comp/" rel="nofollow noreferrer">http://malsup.com/jquery/form/comp/</a></p>
40,289
<p>I have a script that works fine on my test server (using IIS6). The script processes an ajax request and sends a response with the following line:</p> <pre><code>header( 'application/javascript' ); </code></pre> <p>But on my live server, this line crashes the page and causes a 500 error.</p> <p>Do I need to allow PHP to send different MIME types in IIS7? If so, how do I do this? I can't find any way on the interface.</p>
<p>The header is incorrect, try this instead:</p> <pre><code>header('Content-Type: application/javascript'); </code></pre>
<p>take a look at <strong><a href="http://en.wikipedia.org/wiki/Mime_type" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Mime_type</a></strong></p> <p>There it says you should use application/javascript instead of text/javascript.</p>
10,759
<p>I'd like to be able to create a large (say 20,000 x 20,000) pixel bitmap in a C++ MFC application, using a CDC derived class to write to the bitmap. I've tried using memory DCs as described in the MSDN docs, but these appear to be restricted to sizes compatible with the current display driver.</p> <p>I'm currently using a bitmap print driver to do the job, but it is extremely slow and uses very large amounts of intermediate storage due to spooling GDI information.</p> <p>The solution I'm looking for should not involve metafiles or spooling, as the model that I am drawing takes many millions of GDI calls to render.</p> <p>I could use a divide and conquer approach via multiple memory DCs, but it seems like a pretty cumborsome and inelegant technique.</p> <p>any thoughts?</p>
<p>CDC and CBitmap appears to only support device dependant bitmaps, you might have more luck creating your bitmap with <a href="http://msdn.microsoft.com/en-us/library/ms532292(VS.85).aspx" rel="nofollow noreferrer">::CreateDIBSection</a>, then attaching a CBitmap to that. The raw GDI interfaces are a little hoary, unfortunately.</p> <p>You probably won't have much luck with 20,000 x 20,000 at 32 BPP, at least in a 32-bit application, as that comes out at about 1.5 GB of memory, but I got a valid HBITMAP back with 16 bpp:</p> <pre><code>BITMAPINFOHEADER bmi = { sizeof(bmi) }; bmi.biWidth = 20000; bmi.biHeight = 20000; bmi.biPlanes = 1; bmi.biBitCount = 16; HDC hdc = CreateCompatibleDC(NULL); BYTE* pbData = 0; HBITMAP hbm = CreateDIBSection(hdc, (BITMAPINFO*)&amp;bmi, DIB_RGB_COLORS, (void**)&amp;pbData, NULL, 0); DeleteObject(SelectObject(hdc, hbm)); </code></pre>
<p>If the image has to be this resolution - say a hi-res scan of an x-ray - then you might want to look at writing custom spooling routines for it - 1.5 gb is very expensive - even for modern desktops.</p> <p>If it is vector based then you can look at SVG as it supports view ports and most allow you to render to other formats. I use SVG to JPG via Batik (java) so it is possible to do.</p>
16,713
<p>In my experience Meta-templates are really fun (when your compilers are compliant), and can give good performance boosts, and luckily I'm surrounded by seasoned C++ programmers that also grok meta-templates, however occasionally a new developer arrives and can't make heads or tails of some of the meta-template tricks we use (mostly Andrei Alenxandrescu stuff), for a few weeks until he gets initiated appropriately. </p> <p>So I was wondering what's the situation for other C++ programmers out there? Should meta-template programming be something C++ programmers should be "required" to know (excluding entry level students of course), or not?</p> <p>Edit: Note my question is related to production code and not little samples or prototypes</p>
<p>If you can you find enough candidates who really know template meta-programing then by all means, require it. You will be showing a lot of qualified and potentially productive people the door (there are plenty of legitimate reasons not to know how to do this, namely that if you do it on a lot of platforms, you will create code that can't compile, or that average developers will have trouble understanding). Template meta-programming is great, but let's face it, it's pushing C++ to the limit. Now, a candidate should probably understand basics (compute n! at compile time, or at least explain how it works if they are shown the code). If your new developers are reliably becoming productive within a few weeks, then your current recruiting is probably pretty good.</p>
<p>It's not absolutely necessary to know how to use C++ templates. You can do most things without them. They are however a fantastic feature.</p> <p>Since you roll your own templates, anyone new is going to have to come up to speed with them just like the rest of your code which is going to be the bigger chunk of the learning.</p> <p>I encourage people to learn to use some of the features of the <strong>STL</strong>. I have used this library in production code and it does save time and simplify things quite a bit. I also roll my own when the need arises. </p> <p>I've also heard good things about the <strong>boost</strong> library.</p> <p>If I need to write portable code then I'll generally stick away from templates because many compilers still don't support them properly. If you need a portable STL then <strong>STLPort</strong> is the most portable.</p>
24,391
<p>"The Google" is very helpful... unless your language is called "R," in which case it spits out tons of irrelevant stuff.</p> <p>Anyone have any search engine tricks for "R"? There are some specialized websites, like those below, but how can you tell Google you mean "R" the language? If I'm searching for something specific, I'll use an R-specific term, like "cbind." Are there other such tricks?</p> <ul> <li><a href="http://rweb.stat.umn.edu/R/doc/html/search/SearchEngine.html" rel="noreferrer">rweb.stat.umn.edu</a></li> <li><a href="http://www.rseek.org/" rel="noreferrer">www.rseek.org</a></li> <li><a href="http://search.r-project.org/" rel="noreferrer">search.r-project.org</a> </li> <li><a href="http://www.dangoldstein.com/search_r.html" rel="noreferrer">www.dangoldstein.com/search_r.html</a></li> </ul>
<p><a href="http://rseek.org" rel="noreferrer">http://rseek.org</a> is a great search engine for R manuals, mailing lists, and various websites. It's a Google syndicated search app with specialized UI. I always use it.</p>
<p>You could always search for "R stats", considering R is a statistical program. </p> <p>Edit: <a href="http://www.google.com/search?source=ig&amp;hl=en&amp;rlz=&amp;q=R+stats&amp;btnG=Google+Search" rel="nofollow noreferrer">http://www.google.com/search?source=ig&amp;hl=en&amp;rlz=&amp;q=R+stats&amp;btnG=Google+Search</a></p> <p>The first page shows plenty of relevant results.</p>
12,758
<p><strong>When using the Entity Framework, does ESQL perform better than Linq to Entities?</strong> </p> <p>I'd prefer to use Linq to Entities (mainly because of the strong-type checking), but some of my other team members are citing performance as a reason to use ESQL. I would like to get a full idea of the pro's/con's of using either method.</p>
<p>The most obvious differences are:</p> <p>Linq to Entities is strongly typed code including nice query comprehension syntax. The fact that the “from” comes before the “select” allows IntelliSense to help you.</p> <p>Entity SQL uses traditional string based queries with a more familiar SQL like syntax where the SELECT statement comes before the FROM. Because eSQL is string based, dynamic queries may be composed in a traditional way at run time using string manipulation.</p> <p>The less obvious key difference is:</p> <p>Linq to Entities allows you to change the shape or "project" the results of your query into any shape you require with the “select new{... }” syntax. Anonymous types, new to C# 3.0, has allowed this.</p> <p>Projection is not possible using Entity SQL as you must always return an ObjectQuery&lt;T&gt;. In some scenarios it is possible use ObjectQuery&lt;object&gt; however you must work around the fact that .Select always returns ObjectQuery&lt;DbDataRecord&gt;. See code below...</p> <pre><code>ObjectQuery&lt;DbDataRecord&gt; query = DynamicQuery(context, "Products", "it.ProductName = 'Chai'", "it.ProductName, it.QuantityPerUnit"); public static ObjectQuery&lt;DbDataRecord&gt; DynamicQuery(MyContext context, string root, string selection, string projection) { ObjectQuery&lt;object&gt; rootQuery = context.CreateQuery&lt;object&gt;(root); ObjectQuery&lt;object&gt; filteredQuery = rootQuery.Where(selection); ObjectQuery&lt;DbDataRecord&gt; result = filteredQuery.Select(projection); return result; } </code></pre> <p>There are other more subtle differences described by one of the team members in detail <a href="http://blogs.msdn.com/diego/archive/2007/12/20/some-differences-between-esql-and-linq-to-entities-capabilities.aspx" rel="noreferrer">here</a> and <a href="http://blogs.msdn.com/diego/archive/2007/11/11/choosing-an-entity-framework-api.aspx" rel="noreferrer">here</a>.</p>
<p>For direct queries I'm using linq to entities, for dynamic queries I'm using ESQL. Maybe the answer isn't either/or, but and/also.</p>
5,957
<p>For example:</p> <pre><code>javac Foo.java Note: Foo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. </code></pre>
<p>This comes up in Java 5 and later if you're using collections without type specifiers (e.g., <code>Arraylist()</code> instead of <code>ArrayList&lt;String&gt;()</code>). It means that the compiler can't check that you're using the collection in a type-safe way, using <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html" rel="noreferrer">generics</a>.</p> <p>To get rid of the warning, you need to be specific about what type of objects you're storing in the collection. So, instead of</p> <pre><code>List myList = new ArrayList(); </code></pre> <p>use</p> <pre><code>List&lt;String&gt; myList = new ArrayList&lt;String&gt;(); </code></pre> <hr /> <p>In Java 7 you can shorten generic instantiation by using <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html" rel="noreferrer">Type Inference</a>.</p> <pre><code>List&lt;String&gt; myList = new ArrayList&lt;&gt;(); </code></pre>
<p>You can keep it in the generic form and write it as:</p> <pre><code>// list 2 is made generic and can store any type of Object ArrayList&lt;Object&gt; list2 = new ArrayList&lt;Object&gt;(); </code></pre> <p>Setting type of <code>ArrayList</code> as <code>Object</code> gives us the advantage to store any type of data. You don't need to use -Xlint or anything else.</p>
24,103
<p>All throughout an application wherever error messages (or other user messages) are used I typically hard-code a string. Obviosly this can be really bad (especially when you may have to come back and localize an app). What is the best approach to centralize these strings? A static class? Constants? An XML File? Or a combination (like creating a static class with constants that are used to read from an xml file).</p>
<p>Create the strings in a resource file. You can then localise by adding additional resource files.</p> <p>Check out <a href="https://web.archive.org/web/20190903233229/http://geekswithblogs.net/dotNETPlayground/archive/2007/11/09/116726.aspx" rel="nofollow noreferrer">http://geekswithblogs.net/dotNETPlayground/archive/2007/11/09/116726.aspx</a></p>
<p>.net has a pretty good support for so-called ressource-files where you can store all strings for one language.</p>
16,485
<p>The question is if a database connection should be passed in by reference or by value?</p> <p>For me I'm specifically questioning a PHP to MySQL connection, but I think it applies to all databases.</p> <p>I have heard that in PHP when you pass a variable to a function or object, that it is copied in memory and therefore uses twice as much memory immediately. I have also heard that it's only copied once changes have been made to the value (such as a key being added/removed from an array).</p> <p>In a database connection, I would think it's being changed within the function as the query could change things like the last insert id or num rows. (I guess this is another question: are things like num rows and insert id stored within the connection or an actual call is made back to the database?)</p> <p>So, does it matter memory or speed wise if the connection is passed by reference or value? Does it make a difference PHP 4 vs 5?</p> <pre><code>// $connection is resource function DoSomething1(&amp;$connection) { ... } function DoSomething2($connection) { ... } </code></pre>
<p>A PHP resource is a special type that already is a reference in itself. Passing it by value or explicitly by reference won't make a difference (ie, it's still a reference). You can check this for yourself under PHP4:</p> <pre><code>function get_connection() { $test = mysql_connect('localhost', 'user', 'password'); mysql_select_db('db'); return $test; } $conn1 = get_connection(); $conn2 = get_connection(); // "copied" resource under PHP4 $query = "INSERT INTO test_table (id, field) VALUES ('', 'test')"; mysql_query($query, $conn1); print mysql_insert_id($conn1)."&lt;br /&gt;"; // prints 1 mysql_query($query, $conn2); print mysql_insert_id($conn2)."&lt;br /&gt;"; // prints 2 print mysql_insert_id($conn1); // prints 2, would print 1 if this was not a reference </code></pre>
<p>i don't really have a specific answer for php, but in general it would seem to me that you would want to pass this by reference if you are not explicitly sure that you encounter performance issues when passing by value.</p>
29,869
<p>Does anybody has an experience with <a href="http://springframework.org/spring-integration" rel="nofollow noreferrer">Spring Integration</a> project as embedded ESB?</p> <p>I'm highly interesting in such use cases as:</p> <ul> <li>Reading files from directory on schedule basis</li> <li>Getting data from JDBC data source</li> <li>Modularity and possibility to start/stop/redeploy module on the fly (e.g. one module can scan directory on schedule basis, another call query from jdbc data source etc.)</li> <li>repeat/retry policy</li> </ul> <p><strong>UPDATE:</strong></p> <p>I found answers on all my questions except "Getting data from JDBC data source". Is it technically possible?</p>
<p>Remember, "ESB" is just a marketing term designed to sell more expensive software, it's not a magic bullet. You need to consider the specific jobs you need your software to do, and pick accordingly. If Spring Integration seems to fit the bill, I wouldn't be too concerned if it doesn't look much like an uber-expensive server installation.</p>
<p>This link describes the <a href="http://www.jroller.com/habuma/entry/spring_integration_return_of_the" rel="nofollow noreferrer">FileSucker</a> with Spring Integration. Read up on your Enterprise Integration patterns for more info I think.</p> <p>I kinda think you need to do a bit more investigation your self, or do a couple of tries on some of your usecases. Then we can discuss whats good and bad</p>
37,371
<p>So I have been working on a small web application (site) for a group of friends of mine and have come to the realization that things need to change. The application has two faces to it </p> <ol> <li>a public facing side that serves dynamic data to visitors and non admins, and </li> <li>an admin side where admins can update or create the dynamic data to be served.</li> </ol> <p>This application started off as a single webforms project sectioned off by separate pages and and web.config security of folders. Then it grew into separate projects (MVC admin side and webforms front end). I later had to bring it to where it is today, a single web app with a mix of MVC (admin) and webforms (public), due to deployment issues.</p> <p>Now I am looking at migrating it to a single MVC project. I would like to keep my administration functions desperate from my public facing side by URL like /Admin and am not sure how to do it. I have read a lot of topics on grouping controllers into modules but am not sure that is the right thing yet. </p> <ul> <li>Should I just create admin functions inline with the rest of the public app and determine if the user is logged in or not? </li> <li>Or should I create Admin controllers that are separate from the public controllers (EventAdminController vs CalendarController)?</li> <li>What have others done? </li> </ul> <p>Suggestions welcome, thanks stackoverflow.</p> <hr> <p>Yes I am using the ASP.Net MVC framework from Microsoft. Darryl, are you saying to place my views in an Admin folder and protect that it using a web.config (to check security and roles) or to place my controllers in an Admin folder?</p> <p>My assumptions was that you were saying to place the controllers in an Admin folder, say under controllers. This would still mean that HomeController in /Controllers is different than HomeAdminController in /Controllers/Admin. In this case you could configure specific routes for each but I don't see how simply putting a controller in a different folder would protect them (unless using the Authorize attribute on actions).</p> <p>As for placing the views in a different folder, I can see how that could work in theory. But wouldn't the controller (in theory without any authorize attributes) still execute up to the point that the view is returned? I would then either expect a redirect or an error. Either way I wouldn't want to execute my controller action if you can't get to the view, and would rather not do any internal action pre-checking.</p>
<p>We have a similar problem where we are creating a very large ASP.NET MVC application and to separate functionality into areas we are using a process very similar to <a href="http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx" rel="nofollow noreferrer">this post by Phil Haack</a>. By creating areas you can have unique controller names for each area instead for the whole application, you can separate your modules far more easily and you can share authentication and basic common functionality.</p>
<p>On a MVC project I am working on I put all the admin stuff in an admin folder. To see the admin folder you must be authenticated and in the correct role. My controllers tend to be very minimal, most logic is in a business layer that the controllers use. </p>
45,667
<p>I have a canvas in Flex that shall be able only to be scrolled in vertical direction, so I set the attributes of the canvas as follows:</p> <pre><code>verticalScrollPolicy="auto" horizontalScrollPolicy="off" </code></pre> <p>The problem here is that the vertical scrollbar covers the content when it appears - altough there is enough horizontal room left. I would have expected that the content size would have been automatically adjusted.</p> <p>When setting the vertical scroll policy to "on", no content is covered also.</p> <p>In case I set both scroll policies to 'auto' I also get a horizontal scroll bar just for scrolling to the area that is covered by the vertical scroll bar.</p> <p>Is there a workaround how I can relayout the content of the canvas when the vertical scroll bar is shown so that it does not cover any content?</p>
<p>It's a bug. See <em><a href="http://www.nbilyk.com/flex-scrollpolicy-bug" rel="noreferrer">Flex verticalScrollPolicy bug</a></em> for a workaround.</p>
<p>I'm, too. I usually have some problems with the verticalScrollBar in Flex, so I prefer to use the browser's scrollbar for scrolling the complete application. You can found a workaround here: <a href="http://www.davidortinau.com/blog/how_to_resize_the_flex_stage_and_use_the_browser_scrollbar/" rel="nofollow noreferrer">How to Resize the Flex Stage and Use the Browser Scrollbar</a>.</p> <p>The code I use:</p> <p>In Flex:</p> <pre><code>ExternalInterface.call("setInitialFlashHeight", this.height); </code></pre> <p>In my HTML (JavaScript):</p> <pre><code>function setInitialFlashHeight(newHeight) { document.getElementById('my_flash').style.height = newHeight + 'px'; } </code></pre> <p>And if you want to add (or remove) some height:</p> <pre><code>function addFlashHeight(height) { var divHeight; var obj = document.getElementById('my_flash'); if (obj.offsetHeight) { divHeight = obj.offsetHeight; } else if (obj.style.pixelHeight){ divHeight = obj.style.pixelHeight; } var newHeight = divHeight + height; document.getElementById('my_flash').style.height = newHeight + 'px'; } </code></pre> <p>To remove, you use "-" instead of "+".</p>
37,365
<p>Has anyone had luck with removing large amount of issues from a jira database instead of using the frontend? Deleting 60000 issues with the bulktools is not really feasible.</p> <p>Last time I tried it, the jira went nuts because of its own way of doing indexes.</p>
<p>We got gutsy and did a truncate on the jiraissues table and then use the rebuild index feature on the frontend. It looks like it's working!</p>
<p>This is old, but I see that this question was just edited recently, so to chime in:</p> <p>Writing directly to the JIRA database is problematic. The reindex feature suggested in the Oct 14 08 answer just rebuilds the Lucene index, so it is unlikely to clean up everything that needs to be cleaned up from the database on a modern JIRA instance. Off the top of my head, this will probably leave data lying around in the following tables, among others:</p> <ul> <li>custom field data (customfieldvalue table)</li> <li>issue links (issuelink table)</li> <li>versions and components (nodeassociation table, which contains other stuff too, so be careful!)</li> <li>remote issue links or wiki mentions (remotelink table)</li> </ul> <p>If one has already done such a manual delete on production, it's always a good idea to run the database integrity checker (YOURJIRAURL/secure/admin/IntegrityChecker!default.jspa) to make sure that nothing got seriously broken.</p> <p>Fast forwarding to 2014, the best solution is to write a quick shell script that uses the <a href="https://docs.atlassian.com/jira/REST/6.2.4/#d2e3848" rel="nofollow">REST API</a> to delete all of the required issues. (The <a href="https://bobswift.atlassian.net/wiki/display/JCLI/JIRA+Command+Line+Interface" rel="nofollow">JIRA CLI</a> plugin is usually a good option for automating certain types of tasks too, but as far as I can tell, it does not currently support the deletion of issues, so the REST API is your best bet.)</p>
24,510
<p>Is it even sensible to try forming a scrum when one of the participants is in India (+05:30), and others are in the US (-06:00 and -08:00)? There isn't a comfortable meeting time for everyone with that.</p>
<p>You might want to have everyone post status and questions to a wiki daily in addition to the scrum for the US participants. The point is daily communication in the most effective manner.</p>
<p>Make the process in such a way that the communication happens through one channel. Have scrum at each place and let them update it on to the Project portal(Wiki) or VSTS or any other single channel. So instead of just one morning scrum let this be two scrums per day so you guys will get the benefit of a 24 hours project running time per day.</p>
39,052
<h2>Problem</h2> <p>My CR-10 printer seems to be trying to print the model 4 or 5 layers too low. This means that for the first few layers, the printing nozzle is forced against the bed, preventing extrusion until the print reaches higher layers.</p> <h2>Outcome</h2> <p>This results in the bottom part of the print having the internal structure visible and the printing head deteriorating. I had to remove the old nozzle because it was clogged up with what I believe to be some residue that was picked up during preceding prints.</p> <p><a href="https://i.stack.imgur.com/mUfsT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mUfsT.jpg" alt="A print showing the structure inside the model because of missing layers"></a> <em>note: On this print, the top part is almost-well printed. It cannot be seen in pictures, but I say "almost" because the well-printed part is still much thinner than expected. This is the result of my purposeful mis-leveling the bed so that the part where the printer "homes" is higher than the lower part. I did this to see if there was any obvious bending of the printing bed. Doesn't look like there is.</em></p> <h2>Fix attempts</h2> <ul> <li>I have tried to re-level the bed multiple times, but it doesn't matter as the "too low" effect is independent from the location on the bed.</li> <li>I have tried using the printer's built-in Z-offset but to no avail. This might be due to the fact that I control the print through Ultimaker Cura 4, so I tried looking for the Z-offset property in Ultimaker Cura and even though internet says it exists, I failed to find it.</li> </ul> <h2>History</h2> <p>The printer used to work perfectly well and I do not remember having changed anything before the problem arose. I recently changed the nozzle and made sure to tighten it as high as possible but the Z-offset problem still persists.</p>
<p>Did you verify the Cura z-offset actually changed the corresponding G-Codes? </p> <p>I had the opposite problem on my RF1000. To fix the problem I added the following 2 lines to my start G-Codes:</p> <pre><code>M3001 ; Activate Z-Compensation M206 Z-0.3 ; Set z offset 0.3mm closer to the nozzle </code></pre> <p>The first line was default in some example prints and is (as far as I know) only used by Renkforce printers. The second line moves the nozzle closer to the bed. In your case you'd have to move it further away and would need a positive Z value.</p>
<p>Did you verify the Cura z-offset actually changed the corresponding G-Codes? </p> <p>I had the opposite problem on my RF1000. To fix the problem I added the following 2 lines to my start G-Codes:</p> <pre><code>M3001 ; Activate Z-Compensation M206 Z-0.3 ; Set z offset 0.3mm closer to the nozzle </code></pre> <p>The first line was default in some example prints and is (as far as I know) only used by Renkforce printers. The second line moves the nozzle closer to the bed. In your case you'd have to move it further away and would need a positive Z value.</p>
1,437
<p>I'm working on a fairly complex project, a custom encryption routine if you will (just for fun) and I've run into this issue in designing my code layout.</p> <p>I have a number of functions that I want to be able to call by index. Specifically, I need to be able to call one randomly for the encrypt process, but then address that by a specific index in the decrypt process.</p> <p>I was considering a classic function array, but my main concern is that a function array would be tricky to maintain, and a little ugly. (The goal is to get each function pair in a separate file, to reduce compile times and make the code easier to manage.) Does anyone have a more elegant C++ solution as an alternative to a function array? Speed isn't really an issue, I'm more worried about maintainability.</p> <p>-Nicholas</p>
<p>What's wrong with function array?</p> <p>You need to call functions by index. So they must be put into some "indexable by index" structure <em>somehow</em>. Array is probably the simplest structure that suits this need.</p> <p>Example (typing out of my head, might not compile):</p> <pre><code>struct FunctionPair { EncodeFunction encode; DecodeFunction decode; }; FunctionPair g_Functions[] = { { MyEncode1, MyDecode1 }, { MySuperEncode, MySuperDecode }, { MyTurboEncode, MyTurboDecode }, }; </code></pre> <p>What is "ugly" or "hard to maintain" in the approach above?</p>
<p>An object with an operator() method defined can act a lot like a function but be generally nicer to work with.</p>
15,311
<p>What is the difference in terms of functionality between the Apache HTTP Server and Apache Tomcat?</p> <p>I know that Tomcat is written in Java and the HTTP Server is in C, but other than that I do not really know how they are distinguished. Do they have different functionality?</p>
<p>Apache Tomcat is used to deploy your Java Servlets and JSPs. So in your Java project you can build your WAR (short for Web ARchive) file, and just drop it in the deploy directory in Tomcat.</p> <p>So basically Apache is an HTTP Server, serving HTTP. Tomcat is a Servlet and JSP Server serving Java technologies.</p> <p>Tomcat includes Catalina, which is a servlet container. A servlet, at the end, is a Java class. JSP files (which are similar to PHP, and older ASP files) are generated into Java code (HttpServlet), which is then compiled to .class files by the server and executed by the Java virtual machine. </p>
<p>Apache is an HTTP web server which serve as HTTP.</p> <p>Apache Tomcat is a java servlet container. It features same as web server but is customized to execute java servlet and JSP pages.</p>
5,051
<p>Rails uses the concept of migrations to deal with model changes using the ActiveRecord API.</p> <p>CouchDB uses JSON (nested maps and arrays) to represent its model objects.</p> <p>In working with CouchDB so far, I don't see good ways of recognizing when the document's structure has changed (other than being disciplined as a developer), or for migrating documents from an old to a new model.</p> <p>Are there existing features or do you have best practices for handling model changes in CouchDB?</p>
<p>Time for RDBMS de-brainwashing. :)</p> <p>One of the biggest points of couchdb's schema-less design is directly aimed at preventing the need for migrations. The JSON representation of objects makes it easy to just duck type your objects.</p> <p>For example, given that you have a blog type web app with posts and whatever fancy things people store in a blog. Your post documents have fields like author, title, created at, etc. Now you come along and think to yourself, "I should track what phase the moon is in when I publish my posts..." you can just start adding moon_phase as an attribute to new posts.</p> <p>If you want to be complete you'd go back and add moon_phase to old posts, but that's not strictly necessary.</p> <p>In your views, you can access moon_phase as an attribute. And it'll be null or cause an exception or something. (Not a JS expert, I think null is the right answer)</p> <p>Thing is, it doesn't really matter. If you feel like changing something just change it. Though make sure your views understand that change. Which in my experience doesn't really require much.</p> <p>Also, if you're really paranoid, you might store a version/type attribute, as in:</p> <pre><code>{ _id: "foo-post", _rev: "23490AD", type: "post", typevers: 0, moon_phase: "full" } </code></pre> <p>Hope that helps.</p>
<p>Check out <a href="https://github.com/arunthampi/activecouch/tree/master" rel="nofollow noreferrer">ActiveCouch</a>.</p> <p>CouchDB is schema-less on purpose, so there is not a 1-to-1 mapping of concepts from the ActiveRecord migrations to a CouchDB equivalent. However, ActiveCouch does include migrations for CouchDB's 'views'.</p>
15,798
<p>I'm using Visual Studio 2008 Professional Edition. In previous versions, there has been integration with VSS, through which one could "open from SourceSafe" and then, in the solution view, have the ability to interact with the source control by clicking on individual files. I seem to have some integration under 2008, namely there is a "Source Control" menu item under the File menu, but all I can do there is "Launch Microsoft Visual SourceSafe." How do I get the integration that I had in 2005?</p>
<p>You have to install the VSS client software, and if you want the auto check out, etc. the project has to be bound to the source control repository. </p> <p>Also try looking in the Tools -> Options -> Source control menu item.</p>
<p>I have tried all the settings in this dropdown.</p> <p>Until I find a way to get the solution explorer integration working correctly, I am running VSS client in a separate window and checking out files by hand.</p>
37,848
<p>Here is the input (html, not xml):</p> <pre><code>... html content ... &lt;tag1&gt; content for tag 1 &lt;/tag1&gt; &lt;tag2&gt; content for tag 2 &lt;/tag2&gt; &lt;tag3&gt; content for tag 3 &lt;/tag3&gt; ... html content ... </code></pre> <p>I would like to get 3 matches, each with two groups. First group would contain the name of the tag and the second group would contain the inner text of the tag. There are just those three tags, so it doesn't need to be universal.</p> <p>In other words:</p> <pre><code>match.Groups["name"] would be "tag1" match.Groups["value"] would be "content for tag 2" </code></pre> <p>Any ideas?</p>
<p>I don't see why you would want to use match group names for that.</p> <p>Here is a regular expression that would match tag name and tag content into numbered sub matches.</p> <pre><code>&lt;(tag1|tag2|tag3)&gt;(.*?)&lt;/$1&gt; </code></pre> <p>Here is a variant with .NET style group names</p> <pre><code>&lt;(?'name'tag1|tag2|tag3)&gt;(?'value'.*?)&lt;/\k'name'&gt;. </code></pre> <p>EDIT</p> <p>RegEx adapted as per question author's clarification.</p>
<p>This will give you named capture groups for what you want. It won't work for nested tags, however.</p> <p><code> /&lt;(?&lt;name&gt;[^&gt;]+)&gt;(?&lt;value&gt;[^&lt;]+)&lt;/\1&gt;/ </code></p>
24,467
<p>I've programmed C and C++ for a long time and so far I've never used exceptions and try / catch. What are the benefits of using that instead of just having functions return error codes? </p>
<p>Possibly an obvious point - a developer can ignore (or not be aware of) your return status and go on blissfully unaware that something failed.</p> <p>An exception needs to be acknowledged in some way - it can't be silently ignored without actively putting something in place to do so.</p>
<p>As @Martin pointed out throwing exceptions forces the programmer to handle the error. For example, not checking return codes is one of the biggest sources of security holes in C programs. Exceptions make sure that you handle the error (hopefully) and provide some kind of recover path for your program. And if you choose to ignore an exception rather than introduce a security hole your program crashes.</p>
23,878
<p>Is there a way to force a Samba process to close a given file without killing it?</p> <p>Samba opens a process for each client connection, and sometimes I see it holds open files far longer than needed. Usually i just kill the process, and the (windows) client will reopen it the next time it access the share; but sometimes it's actively reading other file for a long time, and i'd like to just 'kill' one file, and not the whole connection.</p> <p>edit: I've tried the 'net rpc file close ', but doesn't seem to work. Anybody knows why?</p> <p>edit: <a href="http://www.nabble.com/Fw:-Files-left-open-td5578614.html" rel="nofollow noreferrer">this</a> is the best mention i've found of something similar. It seems to be a problem on the win32 client, something that microsoft servers have a workaround for; but Samba doesn't. I wish the <code>net rpc file close &lt;fileid&gt;</code> command worked, I'll keep trying to find out why. I'm accepting LuckyLindy's answer, even if it didn't solve the problem, because it's the only useful procedure in this case.</p>
<p>This happens all the time on our systems, particularly when connecting to Samba from a Win98 machine. We follow these steps to solve it (which are probably similar to yours):</p> <ul> <li>See which computer is using the file (i.e. <code>lsof|grep -i &lt;file_name&gt;</code>)</li> <li>Try to open that file from the offending computer, or see if a process is hiding in task manager that we can close</li> <li>If no luck, have the user exit any important network programs</li> <li>Kill the user's Samba process from linux (i.e. <code>kill -9 &lt;pid&gt;</code>)</li> </ul> <p>I wish there was a better way!</p>
<p>If there isn't an explicit option in samba, that would be impossible to externally close an open file descriptor with standard unix interfaces.</p>
17,168
<p>I'm creating an app that holds loads of loads of user data in memory, and it's mostly keeping it all in List&lt;T&gt; structures (and some Dictionary&lt;T,T&gt; when I need lookup).</p> <p>And I'm wondering...</p> <p>How efficient are Lists? How much memory overhead do I get for each of them? (that is, memory space in addition to what the objects they contain would take) How much of a penalty do I pay every time I instance a new one?</p> <p>Is there a more efficient way?</p> <p>Dictionaries are just HashTables, right? Or are them a less efficient data structure?</p> <p>I'd like to use Arrays, but I have the typical problem of adding and removing things all the time from them, so having to grow / shrink them would be a pain.</p> <p>Any ideas/suggestions?</p> <hr> <p>Edit: I know my basic data structures 101, and why a Linked List is better for adding/removing, and a HashTable is better for Random Access.</p> <p>I'm mostly concerned about .Net's idionsyncracies. How much memory each of these structure wastes, for example. And time wasted on initializing / killing them.</p> <p>Things like, for example, if it takes a lot of time to instance/GC a List, but not much to clear it, maybe I should keep a little pool of Lists waiting for me, and clear them and send them back to the pool when done, instead of simply dereferencing them.</p> <p>Or, if Hashtables are faster for access but waste a lot of memory, I might prefer to use Lists and traverse them, for small item counts.</p> <p>And I'd also really like to focus on memory usage, since my app is hediously memory intensive (think memcached like)... Does anyone know where I can find such info?</p>
<p>Lists are arrays underneath, so the performance hit of adding an item, unless it is at the end, will be very costly.</p> <p>Otherwise they will be basically as fast as an array.</p>
<p>The .Net List doesn't use a linked list. It is an array, it starts with 4 positions by default and I think it doubles in size as you add things. So performance can vary a bit depending on how you use it.</p> <hr> <p>If your using VS 2008 run the profiler before you get too far down this rat hole. When we started actually looking at where we were losing time it didn't take long for use to figure out that debating the finer points of linked lists just really didn't matter. </p>
5,344
<p>Is there any commonly printed plastic which I can buy that might be transparent to UV light? </p> <p>I wish to print a mould, then pour in my plastic which requires a UV light to activate the curing process. </p>
<p>Have you tried printing with Form labs clear resin ? </p> <p>( This is assuming you have access to a desktop SLA like the Form2+ or Form 1 )</p> <p>The printed part itself gets hardened after exposure to uv light and actually can increase the life time of your mould .</p> <p>I have been using the Form labs Form 2+ a lot recently for small moulds and casting them with Polyurethane . They work amazing and the precision of the mould is high due to 0.05mm layer resolution that is achievable .</p> <p>Once hardened the UV light easily passes through it and does not degrade the part at all . </p> <p>Here is the material data sheet <a href="https://formlabs.com/media/upload/Clear-DataSheet.pdf" rel="noreferrer">https://formlabs.com/media/upload/Clear-DataSheet.pdf</a></p> <p>You can easily get a clear resin print done through a local 3D printing service bureau that you can find using 3D hubs . </p> <p>Prices for printing on a formlabs are comparable to FDM 3D printing , it really just depends on your supplier .</p> <p><strong>If the above doesn't cut it then ,</strong></p> <p>Use DSM Somos® WaterClear Ultra 10122 , please check below link and corresponding data sheet for technical specifications .</p> <p><a href="https://www.dsm.com/products/somos/en_US/products/offerings-somos-water-clear.html" rel="noreferrer">https://www.dsm.com/products/somos/en_US/products/offerings-somos-water-clear.html</a></p> <p>This can only be printed on a 3Ds systems viper , Envision tech preform series or other industrial 3D printers . </p> <p>Again you can head to 3D hubs or call up the closest industrial 3D printing service bureau and ask them for the above material . They should be able to hook you up easily .</p>
<p>This is more of a Chemistry question, but seeing as we love 3D printing with exotics, here are a few.</p> <p><a href="https://topas.com/uv-transmission?gclid=Cj0KCQjwy9LVBRDOARIsAGqoVnuAAAiwiHetZN76JqaRFnq7KKy6br9e6MLDQA4Zlrt01Ceh8GfQrzIaAu7xEALw_wcB" rel="nofollow noreferrer">Topas</a> olefin copolymer</p> <p>From the mfr description page,</p> <blockquote> <p>TOPAS cyclic olefin copolymer, or COC, is an incredibly pure polymer - in fact, it's purer than most grades of medical glass. Unlike glass, it has a non-ionic, inert surface to minimize reactivity, denaturation, agglomeration, delamination and other traditional glass concerns. And when it comes to maintaining purity, TOPAS medical grade plastics can be sterilized via all common methods. Leachables and extractables are extremely low. Reduce risk and increase performance by maintaining the benign, protective environment that TOPAS COC-based devices provide.</p> <p>Medical grades of TOPAS COC are extremely clear, and are optically suitable for replacing glass in many applications.</p> </blockquote> <p>I'm not sure of its melting point, or of the speed of solidification (which affects extruder rate, motion etc).</p> <p>Recommended at <a href="https://chemistry.stackexchange.com/questions/63912/uv-transparent-plastic">this Chem.SE question</a>, PMMA and others</p> <h2>edit</h2> <p>Because answers there have links of their own, I&quot;m not repeating the various technical leads available there.</p> <p>Now you will have to investigate their melting points and flow rates, etc. to see if these can be coerced to function in an extrusion printer.</p>
856
<p>I'm a 1-2 man band at work, and so far I've been using VSS for two reasons 1) the company was using that when I started a few months ago, and 2) it is friendly with Visual Studio.</p> <p>Needless to say, I would very much like to upgrade to a not-so-archaic source control system. However, I don't want to give up the friendliness with Visual Studio, and I'd like to be able to migrate the existing codebase over to a better source control system.</p> <p>I can't imagine I'm the only person in this situation. Does anyone have a success story they wouldn't mind sharing? </p>
<p>If you can pay for it, <a href="http://www.sourcegear.com/" rel="nofollow noreferrer">Source Gear Vault</a> is designed to be a drop-in replacement.</p> <p>If you can't pay, Subversion with AnkhSVN works well but is a bit different.</p>
<p>For one or two users, <a href="http://www.perforce.com" rel="nofollow noreferrer">perforce</a> is free as well. Once you need more that two users though, you have to start paying for it. They have a SCC plugin as well to allow integration into Visual Studio (and any other program that supports that interface).</p>
9,288
<p>I'm using some meta-programming to generate a bunch of methods in ruby like so:</p> <pre><code>class EmotionalObject def self.mood( name, *details ) define_method(name) do # ... end end mood :happy, #... mood :sad, #... mood :ebuillent, #... #... end </code></pre> <p>I know that I can pass <code>rdoc</code> '-A mood' to get it to recognize my mood generation code as attributes, which is handy, since then they at least get recognized.</p> <p>However, they're really more like regular methods than attributes, so I don't want them listed under the 'Attributes:' section when I look at the documentation using <code>ri</code>. I don't have any regular attributes, so is there any simple way I can just change the title of this section to be 'Moods:' or something like that, so my users are at least curious enough to type <code>ri EmotionalObject#happy</code>.</p>
<p>Here is a link on a very simple Forms Authentication implementation with roles. I believe this is the most basic Forms Authentication implementation: <a href="http://www.codeproject.com/KB/web-security/formsroleauth.aspx" rel="noreferrer">http://www.codeproject.com/KB/web-security/formsroleauth.aspx</a></p> <p>Here is one on the membership provider: <a href="http://www.asp.net/learn/moving-to-asp.net-2.0/module-08.aspx" rel="noreferrer">http://www.asp.net/learn/moving-to-asp.net-2.0/module-08.aspx</a> You might have to search for additional tutorials to get a clear idea on how to customize it.</p> <p>I prefer the membership provider because it allows you to override the defaults and supply your own datastore and methods used for the different authentication actions. I find it to be easier than using the basic implementation.</p>
<p>Personally if you are going to use the role management, and user functionality already presented in ASP.NET why try to hack together a solution that down the road will limit your ability to expand.</p> <p>Working with the default functionality for role assignment is easy, and you don't have to worry about the proper creation of the identity information for the user.</p>
42,283
<p>I want to check if a variable has a valid year using a regular expression. Reading the <a href="http://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html" rel="noreferrer">bash manual</a> I understand I could use the operator =~</p> <p>Looking at the example below, I would expect to see "not OK" but I see "OK". What am I doing wrong?</p> <pre><code>i="test" if [ $i=~"200[78]" ] then echo "OK" else echo "not OK" fi </code></pre>
<p>It was changed between 3.1 and 3.2:</p> <blockquote> <p>This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.</p> <p>Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.</p> </blockquote> <p>So use it without the quotes thus:</p> <pre><code>i=&quot;test&quot; if [[ $i =~ 200[78] ]] ; then echo &quot;OK&quot; else echo &quot;not OK&quot; fi </code></pre>
<p>You need spaces around the operator =~</p> <pre> i="test" if [[ $i =~ "200[78]" ]]; then echo "OK" else echo "not OK" fi </pre>
39,198
<p>I am trying to prevent data races in a multihreaded server. My problem is the following: there is a <code>List&lt;RServer&gt;</code>, the type <code>RServer</code> is a class with several fields. Now, the server has several threads all running at the same time and they can modify both the <code>List</code> (adding more items) and the individual <code>RServer</code> instances (changing the fields).</p> <p>So my strategy is to make a <code>readonly object RServerLock = new object( )</code> in each of the <code>RServer</code> instances and additionally a <code>readonly object RServerListLock = new object( )</code> and enclose all the code that modifies either (the <code>List</code> or a <code>RServer</code> instance) in a <code>lock</code>. Is this safe? What happens if a thread tries to lock a <code>RServerLock</code> <em>while</em> another one is locking it?</p>
<p>If you have a contended lock, the second thread has to wait until the first releases the lock.</p> <p>Your plan sounds <em>nearly</em> okay - but you need to lock when <em>reading</em> data as well, to make sure you get the most recent values, and consistent ones. Otherwise you could be half way through writing some values in one thread, and see some of the new values - but possibly not all - and the old values, all at the same time in a different thread.</p> <p>If you can avoid doing this as much as possible, your life will be easier :) Immutable types make threading a lot simpler.</p> <p>Don't forget that if you ever have code which will need two locks at the same time (e.g. adding one RServer and modifying another, atomically) you <em>must</em> make sure that you always aquire locks in the same order - if one thread tries to acquire lock B while it's holding lock A, and a different thread tries to acquire lock A while it's holding lock B, you'll end up with deadlock.</p> <p>See my <a href="http://pobox.com/~skeet/csharp/threads" rel="noreferrer">threading tutorial</a> or <a href="http://www.albahari.com/threading/default.aspx" rel="noreferrer">Joe Albahari's</a> for more details. Also, if you're interested in concurrency, Joe Duffy has an <a href="https://rads.stackoverflow.com/amzn/click/com/032143482X" rel="noreferrer" rel="nofollow noreferrer">excellent book</a> which is coming out very soon.</p>
<p>That is safe. If one thread has acquired the lock, other threads will have to wait until the lock is released.</p> <p>However, improbable as it is, you could hit a performance problem since the lock may be TOO global. It really depends on what your state is and how it is mutated by those threads, so I can't help you with that.</p>
27,627
<p>I have two html pages, when you click on something on the first html, it will go to the second one. What I want to do is to show text according to what you clicked on the first html. different texts are wrapped with different ids. Here's how I wrote:</p> <pre><code>&lt;a href="secondpage.html#one"&gt;&lt;/a&gt; &lt;a href="secondpage.html#two"&gt;&lt;/a&gt; &lt;a href="secondpage.html#three"&gt;&lt;/a&gt; </code></pre> <p>I'm expecting to see two.html load the text with id "one", but it doesn't work, does anyone know what I did wrong? </p> <p>Here's the code on second page:</p> <pre><code>&lt;ul id="menu" class="aaa"&gt; &lt;li&gt;&lt;a id="one" href="#"&gt;one&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id="two" href="#"&gt;two&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id="three" href="#"&gt;three&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And I have a JS file to modify each id:</p> <pre><code>$("one").observe('click', function() { $('Pic').writeAttribute('src',"picone.jpg"); $('Bio').update("texthere!"); }); </code></pre> <p>Same for two and three.</p> <p>Right now if I click on a button on the first page, it will always show the text and pic for "one", no matter which button I click.</p> <p>But I want to see the pic and text for "two" if i click on it.</p>
<p>What you want to do is simulate a click on your anchor when the page loads. Since you're using jQuery, the simplest approach (but far form best) would be the following:</p> <pre> $(window).observe('domready', function () { $(location.hash).click(); }); </pre> <p>attach ondomready-event to window. Fetch element with id=one (with jQuery this would be '#one', same as your location.hash would be, very handy in this case), trigger a click on it.</p> <p>You might need to replace $(location.hash).click(); with $(location.hash).get(0).click() since jQuery tend to return arrays of jQuery-objects. </p> <p>But a better solution in your case would be to have an event-handler that you can trigger manually, thus circumvent the need of firing events, aswell as drop the anchors and put onclick directly on your li's.</p> <p>And furthermore, why do you load a second page when all you seem to want to do is to show/hide content dynamically? Do it on the same page...</p>
<p>When you say "different ids" how are you setting up your anchors on the 2nd page? The anchor on the 2nd page should look like this:</p> <pre><code>&lt;a name='one'&gt;&lt;/a&gt; </code></pre> <p>Put this right above the text that you want to mark on the 2nd page.</p>
33,863
<p>How do I get the <a href="http://en.wikipedia.org/wiki/ASCII" rel="noreferrer">ASCII</a> value of a character as an <code>int</code> in Python?</p>
<p>From <a href="http://mail.python.org/pipermail/python-win32/2005-April/003100.html" rel="noreferrer">here</a>:</p> <blockquote> <p>The function <strong><code>ord()</code></strong> gets the int value of the char. And in case you want to convert back after playing with the number, function <strong><code>chr()</code></strong> does the trick.</p> </blockquote> <pre><code>&gt;&gt;&gt; ord('a') 97 &gt;&gt;&gt; chr(97) 'a' &gt;&gt;&gt; chr(ord('a') + 3) 'd' &gt;&gt;&gt; </code></pre> <p>In Python 2, there was also the <code>unichr</code> function, returning the <a href="http://en.wikipedia.org/wiki/Unicode" rel="noreferrer">Unicode</a> character whose ordinal is the <code>unichr</code> argument:</p> <pre><code>&gt;&gt;&gt; unichr(97) u'a' &gt;&gt;&gt; unichr(1234) u'\u04d2' </code></pre> <p>In Python 3 you can use <code>chr</code> instead of <code>unichr</code>.</p> <hr> <p><a href="https://docs.python.org/3/library/functions.html#ord" rel="noreferrer">ord() - Python 3.6.5rc1 documentation</a></p> <p><a href="https://docs.python.org/2/library/functions.html#ord" rel="noreferrer">ord() - Python 2.7.14 documentation</a></p>
<p>To get the ASCII code of a character, you can use the <code>ord()</code> function.</p> <p>Here is an example code:</p> <pre><code>value = input("Your value here: ") list=[ord(ch) for ch in value] print(list) </code></pre> <p>Output:</p> <pre><code>Your value here: qwerty [113, 119, 101, 114, 116, 121] </code></pre>
28,147
<p>I'm writing a function that fishes out the src from the first image tag it finds in an html file. Following the instructions in <a href="https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php">this thread</a> on here, I got something that seemed to be working:</p> <pre><code>preg_match_all('#&lt;img[^&gt;]*&gt;#i', $content, $match); foreach ($match as $value) { $img = $value[0]; } $stuff = simplexml_load_string($img); $stuff = $stuff[src]; return $stuff; </code></pre> <p>But after a few minutes of using the function, it started returning errors like this:</p> <blockquote> <p>warning: simplexml_load_string() [0function.simplexml-load-string0]: Entity: line 1: parser error : Premature end of data in tag img line 1 in path/to/script on line 42.</p> </blockquote> <p>and </p> <blockquote> <p>warning: simplexml_load_string() [0function.simplexml-load-string0]: tp://feeds.feedburner.com/~f/ChicagobusinesscomBreakingNews?i=KiStN" border="0"> in path/to/script on line 42.</p> </blockquote> <p>I'm kind of new to PHP but it seems like my regex is chopping up the HTML incorrectly. How can I make it more "airtight"?</p>
<p>These two lines of PHP code should give you a list of all the values of the src attribute in all img tags in an HTML file:</p> <pre><code>preg_match_all('/&lt;img\s+[^&lt;&gt;]*src=["\']?([^"\'&lt;&gt;\s]+)["\']?/i', $content, $result, PREG_PATTERN_ORDER); $result = $result[1]; </code></pre> <p>To keep the regex simple, I'm not allowing file names to have spaces in them. If you want to allow this, you need to use separate alternatives for quoted attribute values (which can have spaces), and unquoted attribute values (which can't have spaces).</p>
<p>Most likely because the "XML" being picked up by the regex isn't proper XML for whatever reason. I would probably go for a more complicated regex that would pull out the src attribute, instead of using SimpleXML to get the src. This REGEX might be close to what you need.</p> <pre><code>&lt;img[^&gt;]*src\s*=\s*['|"]?([^&gt;]*?)['|"]?[^&gt;]*&gt; </code></pre> <p>You could also use a real HTML Parsing library, but I'm not sure which options exist in PHP.</p>
42,248
<p>Is it possible to determine whether my web site is being accessed as a trusted site? In <a href="https://stackoverflow.com/questions/251696/best-way-to-readset-ie-options">another question</a> we determined that, in general, it is not prudent to have visibility to client IE settings. Would this qualify as an exception?</p> <p>The reason I'd like to do this is that some functions won't work unless the site is being accessed as a trusted site (e.g. client-side sendmail -- don't ask), and I'd like to be able to warn users. Despite many warnings in the pages, many users still don't read, and send us nastygrams. We'd like to reduce the email volume by detecting this condition and flashing a big warning that basically says "<strong>You didn't read the warnings, and what you're trying to do won't work until you change your settings!</strong>" Any ideas are welcome.</p> <p>EDIT: In our shop, client-side sendmail only works if the site is trusted, and I can't change that due to security requirements, nor can I switch to server-side sendmail. However, this is not the only reason that client-side sendmail will fail, so I can't simply catch a sendmail error to determine this. Also, I don't want this to degrade to a sendmail discussion.</p>
<p>Here's a test you could use:</p> <pre><code>function isTrustedIE(){ try{ var test=new ActiveXObject("Scripting.FileSystemObject"); } catch(e){ return false; } return true; } </code></pre> <p>This will, of course, fail if the user has disabled that particular object, even on a trusted site.</p>
<p>from my understanding this is not possible but you may have some luck testing for a more specific condition, such as the availability of the specific technology or technologies you need. What type of requirements does your client code place on the browser (ActiveX, Java, scripting etc)? Knowing that will be a very good start toward figuring out how to test the client browser for the environment required by your client code.</p>
31,779
<p>I'm trying to pick up ruby by porting a medium-sized (non-OO) perl program. One of my personal idioms is to set options like this:</p> <pre><code>use Getopt::Std; our $opt_v; # be verbose getopts('v'); # and later ... $opt_v &amp;&amp; print "something interesting\n"; </code></pre> <p>In perl, I kind of grit my teeth and let $opt_v be (effectively) a global. </p> <p>In ruby,the more-or-less exact equivalent would be </p> <pre><code>require 'optparse' opts.on("-v", "--[no-]verbose", TrueClass, "Run verbosely") { |$opt_verbose| } opts.parse! end </code></pre> <p>where $opt_verbose is a global that classes could access. Having classes know about global flags like that seems ... er ... wrong. What's the OO-idiomatic way of doing this?</p> <ul> <li>Let the main routine take care of all option-related stuff and have the classes just return things to it that it decides how to deal with?</li> <li>Have classes implement optional behaviour (e.g., know how to be verbose) and set a mode via an attr_writer sort of thing?</li> </ul> <p><em>updated:</em> Thanks for the answers suggesting optparse, but I should have been clearer that it's not <em>how</em> to process command-line options I'm asking about, but more the relationship between command-line options that effectively set a global program state and classes that should ideally be independent of that sort of thing.</p>
<p>A while back I ran across <a href="http://blog.toddwerth.com/entries/5" rel="nofollow noreferrer">this blog post</a> (by Todd Werth) which presented a rather lengthy skeleton for command-line scripts in Ruby. His skeleton uses a hybrid approach in which the application code is encapsulated in an application class which is instantiated, then executed by calling a "run" method on the application object. This allowed the options to be stored in a class-wide instance variable so that all methods in the application object can access them without exposing them to any other objects that might be used in the script.</p> <p>I would lean toward using this technique, where the options are contained in one object and use either attr_writers or option parameters on method calls to pass relevant options to any additional objects. This way, any code contained in external classes can be isolated from the options themselves -- no need to worry about the naming of the variables in the main routine from within the <code>thingy</code> class if your options are set with a <code>thingy.verbose=true</code> attr_writer or <code>thingy.process(true)</code> call.</p>
<p>The <a href="http://www.rubyinside.com/trollop-command-line-option-parser-for-ruby-944.html" rel="nofollow noreferrer">first hit</a> on google for "<a href="http://www.google.com/search?q=processing%20command%20line%20options%20in%20ruby&amp;sourceid=mozilla2&amp;ie=utf-8&amp;oe=utf-8" rel="nofollow noreferrer">processing command line options in ruby</a>" is an article about <a href="http://trollop.rubyforge.org/" rel="nofollow noreferrer">Trollop</a> which seems to be a good tool for this job.</p>
5,965
<p>I'm considering using Annotations to define my Hibernate mappings but have run into a problem: I want to use a base entity class to define common fields (including the ID field) but I want different tables to have different ID generation strategies:</p> <pre><code>@MappedSuperclass public abstract class Base implements Serializable { @Id @Column(name="ID", nullable = false) private Integer id; public Integer getId(){return id;} public void setId(Integer id){this.id = id;} ... } @Entity @Table(name="TABLE_A") public class TableA extends Base { // Table_A wants to set an application-defined value for ID ... } @Entity @Table(name="TABLE_B") public class TableB extends Base { // How do I specify @GeneratedValue(strategy = AUTO) for ID here? ... } </code></pre> <p>Is there some way to do this? I've tried including the following into <code>TableB</code> but hibernate objected to my having the same column twice and it seems wrong:</p> <pre><code>@Override // So that we can set Generated strategy @Id @GeneratedValue(strategy = AUTO) public Integer getId() { return super.getId(); } </code></pre>
<p>In the code above, it looks like you're mixing annotations on fields (superclass) and methods (subclass). The Hibernate <a href="http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/#entity-mapping-entity" rel="nofollow noreferrer">reference documentation</a> recommends avoiding this, and I suspect it might be causing the problem. In my experience with Hibernate, it's safer and more flexible to annotate getter/setter methods instead of fields anyway, so I suggest sticking to that design if you can.</p> <p>As a solution to your problem, I recommend removing the <strong>id</strong> field from your Base superclass altogether. Instead, move that field into the subclasses, and create abstract <strong>getId()</strong> and <strong>setId()</strong> methods in your Base class. Then override/implement the <strong>getId()</strong> and <strong>setId()</strong> methods in your subclasses and annotate the getters with the desired generation strategy.</p> <p>Hope this helps.</p>
<p>If you put your annotations on the getter rather than the field, when you override the method in the subclass, the annotations placed there will be used rather than the ones in the superclass.</p>
42,535
<p>There are some fairly powerful tools like <a href="http://www.culater.net/software/SIMBL/SIMBL.php" rel="nofollow noreferrer">SIMBL</a> or <a href="http://rogueamoeba.com/airfoil/mac/index.php" rel="nofollow noreferrer">Airfoil/Instant Hijack</a> which use code injection.<br> As far as I understand this, these tools inject their own code in other programs. This idea sounds dangerous to me as this seems to have the potential to make perfectly stable software fragile and "buggy". Also this seems to pose security risks.</p> <p>Should these tools be avoided for stability or security reasons?</p>
<p>It depends on what you're using it for and the quality of the code that is being injected. It's possible to have perfectly stable injected code. In fact, when I used to develop third party anti-cheat software for games, code injection was a big part of it, and I was often able to make the games more stable by eliminating bugs and exploits that the original game developers never fixed and no longer supported the game.</p> <p>On the other hand, I would probably be skeptical of injecting third-party code into enterprise security, auditing or accounting software.</p>
<p>I believe it does not just refer to that <a href="http://en.wikipedia.org/wiki/Code_injection" rel="nofollow noreferrer">kind of code injection</a> for hacking or cracking a system.</p> <p>It is also a technique often used in java world, with tools like <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming" rel="nofollow noreferrer">AOP</a> or <a href="http://felix.apache.org/site/ipojo-concepts-overview.html" rel="nofollow noreferrer">IPojo</a>.</p> <p>When they make sense, they complement the current code, allowing them:</p> <ul> <li>to function within a given framework (OSGI Declarative Services for IPojo)</li> <li>to add functionalities (logging services for AOP)</li> </ul> <p>As long as the initial code can run without that code injection, the stability is less an issue. </p> <p>Stability and security - in the case of those two benevolent usages of code injection - of the injected code should be evaluated in a separate test code.</p>
26,402
<p>I am using MySQL and PHP for a project I am working. I have created separate users for carrying out different functions (one for running select queries, one for running update queries, etc.) to provide an extra layer of security. This way, I figure if someone does manage to carry out an injection attack (which is unlikely since I am using prepared statements), whatever they are able to do will be limited to the type of query that was originally meant to be run. Is this a good practice or is it not worth the trouble? </p>
<p>Aside from the extended logic, you will also have different connections and essential overhead in that area.</p> <p>IMHO it's wise to not do all your queries in a webapp with the root user and if the data is so <em>hot</em>, then make sure the designated user has no DROP, DELETE etc. priviledges. You could implement soft-delete if it's necessary in your application.</p> <p>Last but not least, make sure to sanitize all GPC and make sure to properly quote/escape files in your queries. Using prepared statements can be one thing, but in the end it can be as simple as using <a href="http://php.net/manual/en/function.mysql-real-escape-string.php" rel="noreferrer">mysql_real_escape_string()</a> or whatever quoting-methods your DBAL/ORM offer.</p>
<p>I personally don't think it's worth the bother, since it's trickier to code, test and deploy. Make sure your software is immune to SQL injection instead.</p>
17,826
<p>Basically I need a hosted solution, where one can create an account for a project and the distributed team members can interact through that site during the project implementation. I know a lot of such software but not a hosted one.</p>
<p>I think <a href="http://basecamphq.com" rel="nofollow noreferrer">Basecamp</a> is the most popular one.</p>
<p>I use <strong>codeplex.com</strong> from Microsoft and find it excellent, it now accepts svn connections as well as Team System.</p> <p>An excellent alternative would be <strong>code.google.com</strong>, which I've not found wanting.</p> <p>I would propose that both of these are very popular and of the highest quality and many will have opinions on which better suits your needs. I can't give a narrower answer without knowing more of your particular needs and preferences.</p>
29,214
<p><strong>Situation:</strong></p> <p>I have a simple <em>XML</em> document that contains image information. I need to transform it into <em>HTML</em>. However, I can't see where the open tag is and when I use the <em>XSL</em> code below, it shows the following error message: </p> <blockquote> <p>"Cannot write an attribute node when no element start tag is open."</p> </blockquote> <p><strong>XML content:</strong></p> <pre><code>&lt;root&gt; &lt;HeaderText&gt; &lt;HeaderText&gt;Dan Testing&lt;/HeaderText&gt; &lt;/HeaderText&gt; &lt;Image&gt; &lt;img width="100" height="100" alt="FPO lady" src="/uploadedImages/temp_photo_small.jpg"/&gt; &lt;/Image&gt; &lt;BodyText&gt; &lt;p&gt;This is a test of the body text&lt;br /&gt;&lt;/p&gt; &lt;/BodyText&gt; &lt;ShowLinkArrow&gt;false&lt;/ShowLinkArrow&gt; &lt;/root&gt; </code></pre> <p><strong>XSL code:</strong></p> <pre><code>&lt;xsl:stylesheet version="1.0" extension-element-prefixes="msxsl" exclude-result-prefixes="msxsl js dl" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:js="urn:custom-javascript" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:dl="urn:datalist"&gt; &lt;xsl:output method="xml" version="1.0" omit-xml-declaration="yes" indent="yes" encoding="utf-8"/&gt; &lt;xsl:template match="/" xml:space="preserve"&gt; &lt;img&gt; &lt;xsl:attribute name="width"&gt; 100 &lt;/xsl:attribute&gt; &lt;xsl:attribute name="height"&gt; 100 &lt;/xsl:attribute&gt; &lt;xsl:attribute name="class"&gt; CalloutRightPhoto &lt;/xsl:attribute&gt; &lt;xsl:attribute name="src"&gt; &lt;xsl:copy-of select="/root/Image/node()"/&gt; &lt;/xsl:attribute&gt; &lt;/img&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre>
<p>Just to clarify the problem here - the error is in the following bit of code:</p> <pre><code>&lt;xsl:attribute name="src"&gt; &lt;xsl:copy-of select="/root/Image/node()"/&gt; &lt;/xsl:attribute&gt; </code></pre> <p>The instruction xsl:copy-of takes a node or node-set and makes a copy of it - outputting a node or node-set. However an attribute cannot contain a node, only a textual value, so xsl:value-of would be a possible solution (as this returns the textual value of a node or nodeset).</p> <p>A MUCH shorter solution (and perhaps more elegant) would be the following:</p> <pre><code>&lt;img width="100" height="100" src="{/root/Image/node()}" class="CalloutRightPhoto"/&gt; </code></pre> <p>The use of the {} in the attribute is called an Attribute Value Template, and can contain any XPATH expression.</p> <p>Note, the same XPath can be used here as you have used in the xsl_copy-of as it knows to take the textual value when used in a Attribute Value Template.</p>
<p>The other option to try is a straightforward </p> <pre><code>&lt;img width="100" height="100" src="/root/Image/image.jpeg" class="CalloutRightPhoto"/&gt; </code></pre> <p>i.e. without {} but instead giving the direct image path</p>
6,792
<p>When Xdebug is installed/enabled, standard PHP errors (when set to display in the browser) are replaced with more informative messages that include stack traces for each. Also, I've noticed that it also seems to improve output in other areas such as the var_dump() function, formatting/color-coding the output to make it more readable.</p> <p>Are there any 3rd party packages that offer similar functionality? I tend to prefer using Zend Debugger for debugging and would love to find something like this that doesn't depend on Xdebug. Certainly I could write my own error handler, a custom var_dump() function, etc., but I would love to find something that transparently integrates itself into PHP the way Xdebug's functionality does.</p> <p><strong>Edit:</strong> I should emphasize that I'm not looking for a debugger, but for the "extras" that Xdebug offers.</p>
<p>As for your debugging you'll only find access through PHP extensions, regardless of what IDE you are using.</p> <p>Xdebug is the most popular due to it's extra features, beyond that of what you've even described. Xdebug will do profiling (tracing) into the valgrind format that you can use programs like Kcachegrind and wincachegrind to evaluate.</p> <p>Your only other real alternative to the debugging facilities Xdebug provides is Zend Debugger which is a part of the Zend Platform (again available as an extension).</p> <p>As for the replacements, you won't find any other extensions that do the var_dump and error reporting replacements. And especially won't find (beyond Zend Debugger) a debugging protocol, and definitely won't find any other extension that does profiling.</p>
<p>Try NuSphere's PHP IDE. It has an integrated debugger also, and you can get a demo version free if you like.</p> <p><a href="http://www.nusphere.com/" rel="nofollow noreferrer">http://www.nusphere.com/</a></p>
27,457
<p>I'm making a method combining Scrum with the OpenUP lifecycle and deliverables. I also want to keep the OpenUP disciplines apart from "Project Management". I can "hide" it so that it's not immediately obvious in my generated method site. But when you then navigate to the "Risk List" artefact for example the PM is still seen as contributing, and if you click on the link, you get taken to the PM Discipline page.</p> <p>How can I remove it completely from my method without deleting it from the OpenUP library which I'm consuming?</p>
<p>I've never used EPF Composer.</p> <p>I did a little bit of google searches and I understand what you are looking for can be done through Configurations (select OpenUP in your Library view) and published View definitions.</p> <p>See slide 83 and 84 of this PPT document. You should be able to take it from there.</p> <p><a href="http://www.google.com/url?sa=t&amp;rct=j&amp;q=%22epf%20composer%22%20%22standard%20categories%22&amp;source=web&amp;cd=9&amp;ved=0CFoQFjAI&amp;url=http://www.mountainview-itsm.com/Mountainview/downloads/An_Introduction_to_EPF.ppt&amp;ei=p9tVUfTwD4-i8gTFroEY&amp;usg=AFQjCNGlAoGW_ujO2uRyTa_h9jYwJq2YfA" rel="nofollow">An Introduction to the Eclipse Process Framework</a>.</p> <p>In case the link does not work, I searched for "EPF Composer" "Standard categories" on google and the document is at the bottom of the first results page.</p> <p>Good luck.</p>
<p>To those who are to lazy <a href="https://www.google.co.uk/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=5&amp;ved=0ahUKEwiUr9P6prjJAhVM2RoKHeQ7AWgQFgg0MAQ&amp;url=http%3A%2F%2Fwww.mountainview-itsm.com%2Fitil-training%2Fdownloads%2FAn_Introduction_to_EPF.ppt&amp;usg=AFQjCNHCNYUI70q5JaQKxZbpqMtdUIAu_w&amp;cad=rja" rel="nofollow noreferrer">to search and browse slides</a>:</p> <p>Slide 83:<br> Select sub-set of method library for publishing to HTML or exporting to MS. Use “Content” selections for course grain (Plug-in and package level) configuration. Use “Add/Subtract these Categories” for fine grain (element level) configuration.</p> <p><a href="https://i.stack.imgur.com/RJvxQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RJvxQ.png" alt="enter image description here"></a></p> <p>Slide 84:<br> Categories group related elements<br> Views defined by selecting Categories<br> <a href="https://i.stack.imgur.com/7iyuV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7iyuV.png" alt="enter image description here"></a></p>
9,683
<p>Instead of just filling out the form in HTML it should also be possible to just send a post request containing the params.. Is it possible to turn off the authenticity token if, for example, the Accept flag is set to 'application/JSON' in the HTTP header?</p>
<p>The request forgery protection works on the basis of checking the content-type of requests and it only checks the requests that can be made by a browser. No browser is able to generate a request with the content-type set to "application/json" for example. That's why the rails forgery protection routine won't check it. So, if you want to make a json request to your application, set the content-type header to "application/json" and it should work. </p>
<blockquote> <p>Wouldn't it be easier to just add the authenticity token to every json request?</p> </blockquote> <p>Yes, but then the client would have to send a request first just to get the token and then another with the actual POST request, which does not make sense IMHO..</p>
45,405
<p>What is the equivalent to web controls in frameworks other than ASP.Net?</p> <p>Specifically I'd like to know about Java, PHP and Ruby on Rails.</p> <p>What are the relative merits/faults of each of these frameworks for web development?</p> <p>I've had some exposure to ASP.Net and have been asked to look into developing an app that will have configurable controls on it. I know how I'd do this in ASP.Net, but it's to run on a linux box and in my experience Mono is not mature/stable when running ASP.Net.</p> <p><strong>Clarification</strong></p> <p>Basicly what I mean by webcontrols is a set of reusable componenet that I can initialize with various values.</p> <p>So if for example I want to have a reusable component which draws a graph of some kind on the page. and i want to lay out several of these to graph different things.</p>
<p>I believe there aren't.</p> <p>ASP.NET Web controls are a hodgepodge of <code>&lt;input&gt;</code> and <code>&lt;submit&gt;</code> HTML elements put together to make use of the ASP.NET Web Forms Page Lifecycle. This in turn to facilitate windows-forms like behavior in a web application.</p> <p>AFAIK in other frameworks they still make use of the plain HTML control elements coupled with Javascript to modify behavior.</p>
<p>There aren't any. But many high level frameworks define their type of web ui widgets.</p>
31,086
<p>Is it possible to make a big 50MB database native on the iPhone? So that it can be searched very quickly in a smart way? With SQlite?</p>
<p>Yes, you can use SQLite on the iPhone. Since the database is just a file, you can add the 50 MB file to your application, and that's it. SQLite's performance on the iPhone is good, in my experience, although YMMV depending on your exact table layout and indexes.</p> <p>In my opinion, it's definitely worth checking out the FMDB wrapper suggested by Galwegian; it makes the programming quite a bit easier than directly using SQLite library itself.</p> <p>Although 50 MB is way below the limit, be aware that a 50 MB application will take some time to download for people, and people cannot install it from the AppStore without either a WiFi connection or iTunes.</p>
<p>I know the OP probably has long found their solution by now, but I thought I'd add (for the sake of anyone landing here from a google search) our database SDK, RDM Embedded, from Raima, as another possible solution.</p> <p>As far as I can tell, it's the only other native database (not a wrapper) alternative to SQLite on the iPhone, and the only one to support both network and relational database models.</p> <p>We have some info at <a href="http://www.raima.com/iphone" rel="nofollow noreferrer" title="RDM Embedded for iPhone">raima.com/iphone</a></p>
41,913
<p>How would I go about spawning a separate process using a SQL Server 05/08 trigger? Ideally, I would like to spawn the process and have SQL Server not wait on the process to finish execution. I need to pass a couple parameters from the insert that is triggering the process, but the executable would take care of the rest.</p>
<p>a bit of CLR Integration, combined with SQL Service Broker can help you here.</p> <p><a href="http://microsoft.apress.com/feature/70/asynchronous-stored-procedures-in-sql-server-2005" rel="nofollow noreferrer">http://microsoft.apress.com/feature/70/asynchronous-stored-procedures-in-sql-server-2005</a></p>
<p>you want to use the system stored procedure xp_cmdshell </p> <p>info here: <a href="http://msdn.microsoft.com/en-us/library/ms175046.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms175046.aspx</a></p>
15,668
<p>Given the URL (single line):<br> <a href="http://test.example.com/dir/subdir/file.html" rel="noreferrer">http://test.example.com/dir/subdir/file.html</a></p> <p>How can I extract the following parts using regular expressions:</p> <ol> <li>The Subdomain (test)</li> <li>The Domain (example.com)</li> <li>The path without the file (/dir/subdir/)</li> <li>The file (file.html)</li> <li>The path with the file (/dir/subdir/file.html)</li> <li>The URL without the path (<a href="http://test.example.com" rel="noreferrer">http://test.example.com</a>)</li> <li>(add any other that you think would be useful)</li> </ol> <p>The regex should work correctly even if I enter the following URL: </p> <pre><code>http://example.example.com/example/example/example.html </code></pre>
<blockquote> <p>A single regex to parse and breakup a full URL including query parameters and anchors e.g.</p> <p><a href="https://www.google.com/dir/1/2/search.html?arg=0-a&amp;arg1=1-b&amp;arg3-c#hash" rel="noreferrer">https://www.google.com/dir/1/2/search.html?arg=0-a&amp;arg1=1-b&amp;arg3-c#hash</a> </p> <p><code>^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$</code></p> <p>RexEx positions:</p> <p>url: RegExp['$&amp;'], </p> <p>protocol:RegExp.$2,</p> <p>host:RegExp.$3, </p> <p>path:RegExp.$4,</p> <p>file:RegExp.$6, </p> <p>query:RegExp.$7,</p> <p>hash:RegExp.$8</p> </blockquote> <p>you could then further parse the host ('.' delimited) quite easily.</p> <p>What <strong>I</strong> would do is use something like this:</p> <pre><code>/* ^(.*:)//([A-Za-z0-9\-\.]+)(:[0-9]+)?(.*)$ */ proto $1 host $2 port $3 the-rest $4 </code></pre> <p>the further parse 'the rest' to be as specific as possible. Doing it in one regex is, well, a bit crazy.</p>
<pre><code>String s = "https://www.thomas-bayer.com/axis2/services/BLZService?wsdl"; String regex = "(^http.?://)(.*?)([/\\?]{1,})(.*)"; System.out.println("1: " + s.replaceAll(regex, "$1")); System.out.println("2: " + s.replaceAll(regex, "$2")); System.out.println("3: " + s.replaceAll(regex, "$3")); System.out.println("4: " + s.replaceAll(regex, "$4")); </code></pre> <p>Will provide the following output:<br> 1: https://<br> 2: www.thomas-bayer.com<br> 3: /<br> 4: axis2/services/BLZService?wsdl<br> <br> If you change the URL to <br> String s = "<a href="https://www.thomas-bayer.com?wsdl=qwerwer&amp;ttt=888" rel="nofollow">https://www.thomas-bayer.com?wsdl=qwerwer&amp;ttt=888</a>"; the output will be the following :<br> 1: https://<br> 2: www.thomas-bayer.com<br> 3: ?<br> 4: wsdl=qwerwer&amp;ttt=888<br></p> <p>enjoy..<br> Yosi Lev</p>
4,741
<p>What advantage, if any, is provided by formatting C code as follows:</p> <pre><code>while(lock_file(lockdir)==0) { count++; if(count==20) { fprintf(stderr,"Can't lock dir %s\n",lockdir); exit(1); } sleep(3); } if(rmdir(serverdir)!=0) { switch(errno) { case EEXIST: fprintf(stderr,"Server dir %s not empty\n",serverdir); break; default: fprintf(stderr,"Can't delete dir %s\n",serverdir); } exit(1); } unlock_file(lockdir); </code></pre> <p>versus something more typical such as</p> <pre><code>while(lock_file(lockdir)==0) { count++; if(count==20) { fprintf(stderr,"Can't lock dir %s\n",lockdir); exit(1); } sleep(3); } if(rmdir(serverdir)!=0) { switch(errno) { case EEXIST: fprintf(stderr,"Server dir %s not empty\n",serverdir); break; default: fprintf(stderr,"Can't delete dir %s\n",serverdir); } exit(1); } unlock_file(lockdir); </code></pre> <p>I just find the top version difficult to read and to get the indenting level correct for statements outside of a long block, especially for longs blocks containing several nested blocks.</p> <p>Only advantage I can see is just to be different and leave your fingerprints on code that you've written.</p> <p>I notice vim formatting would have to be hand-rolled to handle the top case.</p>
<p>The top example is know as "Whitesmiths style". <a href="http://en.wikipedia.org/wiki/Indent_style" rel="noreferrer">Wikipedia's entry on Indent Styles</a> explains several styles along with their advantages and disadvantages.</p>
<p>Its just another style--people code how they like to code, and that is one accepted style (though not my preferred). I don't think it has much of a disadvantage or advantage over the more common style in which brackets are not indented but the code within them is. Perhaps one could justify it by saying that it more clearly delimits code blocks.</p>
9,633
<p>I have a large source repository split across multiple projects. I would like to produce a report about the health of the source code, identifying problem areas that need to be addressed.</p> <p>Specifically, I'd like to call out routines with a high cyclomatic complexity, identify repetition, and perhaps run some lint-like static analysis to spot suspicious (and thus likely erroneous) constructs.</p> <p>How might I go about constructing such a report?</p>
<p>For measuring cyclomatic complexity, there's a nice tool available at <a href="http://www.traceback.org/2008/03/31/measuring-cyclomatic-complexity-of-python-code/" rel="noreferrer">traceback.org</a>. The page also gives a good overview of how to interpret the results.</p> <p>+1 for <a href="http://www.logilab.org/project/pylint" rel="noreferrer">pylint</a>. It is great at verifying adherence to coding standards (be it <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP8</a> or your own organization's variant), which can in the end help to reduce cyclomatic complexity.</p>
<p>There is a tool called <a href="http://clonedigger.sourceforge.net/" rel="nofollow noreferrer">CloneDigger</a> that helps you find similar code snippets.</p>
12,560
<p>I have developed a simple mechanism for my mvc website to pull in html via jquery which then populates a specified div. All is well and it looks cool.<br> My problem is that i'm now creating html markup inside of my controller (Which is very easy to do in VB.net btw) I'd rather not mix up the sepparation of concerns.</p> <p>Is it possible to use a custom 'MVC View User Control' to suit this need? Can I create an instance of a control, pass in the model data and render to html? It would then be a simple matter of rendering and passing back to the calling browser.</p>
<p>This is a solution that is working with ASP.Net MVC 1.0 (many that claim to work with beta 3 don't work with 1.0), doesn't suffer of the 'Server cannot set content type after HTTP headers have been sent' problem and can be called from within a controller (not only a view):</p> <pre><code>/// &lt;summary&gt; /// Render a view into a string. It's a hack, it may fail badly. /// &lt;/summary&gt; /// &lt;param name="name"&gt;Name of the view, that is, its path.&lt;/param&gt; /// &lt;param name="data"&gt;Data to pass to the view, a model or something like that.&lt;/param&gt; /// &lt;returns&gt;A string with the (HTML of) view.&lt;/returns&gt; public static string RenderPartialToString(string controlName, object viewData) { ViewPage viewPage = new ViewPage() { ViewContext = new ViewContext() }; viewPage.Url = GetBogusUrlHelper(); viewPage.ViewData = new ViewDataDictionary(viewData); viewPage.Controls.Add(viewPage.LoadControl(controlName)); StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) { using (HtmlTextWriter tw = new HtmlTextWriter(sw)) { viewPage.RenderControl(tw); } } return sb.ToString(); } public static UrlHelper GetBogusUrlHelper() { var httpContext = HttpContext.Current; if (httpContext == null) { var request = new HttpRequest("/", Config.Url.ToString(), ""); var response = new HttpResponse(new StringWriter()); httpContext = new HttpContext(request, response); } var httpContextBase = new HttpContextWrapper(httpContext); var routeData = new RouteData(); var requestContext = new RequestContext(httpContextBase, routeData); return new UrlHelper(requestContext); } </code></pre> <p>It's a static method you can drop somewhere you find it convenient. You can call it this way:</p> <pre><code>string view = RenderPartialToString("~/Views/Controller/AView.ascx", someModelObject); </code></pre>
<p>In rails this is called rendering a partial view, and you do it with <code>render :partial =&gt; 'yourfilename'</code>. I believe ASP.NET MVC has a similar <code>RenderPartial</code> method, but I can't find the official docs for MVC to confirm or deny such a thing.</p>
36,354
<p>This I think is related to my use of the nlog C++ API (and my question on the nlog forum is <a href="http://www.nabble.com/NLogC-problems-with-VB6-IDE-tt19662300s6167.html" rel="nofollow noreferrer">here</a>); the purpose of my asking this question here is to get a wider audience to my problem and perhaps to also get some more general ideas behind the VB6 IDE's failure to build in my particular scenario.</p> <p>Briefly, the problem that I am having is that I am having trouble building VB6 components which reference unmanaged C++ components which have calls to nlog's C\C++ API (which is defined in NLogC.DLL). The build problems are not occurring during compile time, they are occurring when the binary is being built which suggests to me that it's some kind of linker type problem? Don't know enough about how VB6 binaries are produced to tell. The VB6 binary is produced, but it is corrupted and crashes shortly after it is invoked.</p> <p>Has anyone had any similar experiences with VB6 (doesn't have to be related to nlog or C++)? </p> <p>edit: Thanks for all the responses to this rather obscure problem. Still no headway unfortunately; my findings since I posted this:</p> <ol> <li>'Tweaking' the compile options doesn't appear to help in this problem.</li> <li>Adding a reference to the nlog-enabled C++ component from a 'blank' VB6 project doesn't crash it or cause weird build problems. So it isn't a 'native' VB6 issue, possibly an issue with the interaction between nlog and the various components and 3rd party libraries used by other referenced components?</li> <li>As for C++ calling conventions: the nlog-enabled C++ component is - as far as I can see - compliant to these conventions and indeed works fine when referenced by VB6 as long as it is not making any nlog API calls. Not sure if the nlogc.DLL itself is VB6 compliant but I would have thought that that is immaterial since the API calls are being made from the C++ component; VB6 shouldn't know or care about what the C++ component is referencing (that's as far as my understanding on this goes...)</li> </ol> <p>edit2: I should also note that the error message obtained during build is: "Errors during load. Please refer to "xxx" for details". When I bring up the log file, all that there is in there is: "Cannot load control xxx". Interestingly, all references to that particular control disappears from that particular project resulting in compile errors if I were to try to build again.</p>
<p>Got around the problem by using NLog's COM interface (NLog.ComInterop.DLL) from my unmanaged C++ code. Not as easy to do as the C\C++ API but at least it doesn't crash my VB6 components.</p>
<p>I would try tweaking some of the <strong>Compile</strong> options found in the <strong>Project</strong>, <strong>Properties</strong> menu, <strong>Compile</strong> panel to see if they yield any additional hints as to what is going wrong.</p> <p>For example if you compile the executable to <strong>p-code</strong> rather than <strong>native code</strong> does it still crash on startup.</p>
15,943
<p>We use BigIP to load balance between our two IIS servers. We recently deployed a WCF service hosted on by IIS 6 onto these two Windows Server 2003R2 servers.</p> <p>Each server is configured with two host headers: one for the load balancer address, and then a second host header that points only to that server. That way we can reference a specific server in the load balanced group for debugging.</p> <p>So when we run We immediately got the error:</p> <blockquote> <p><strong>This collection already contains an address with scheme http. There can be at most one address per scheme in this collection. Parameter name: item</strong></p> </blockquote> <p>I did some research and we can implement a filter to tell it to ignore the one of the hosts, but then we cannot access the server from that address. </p> <pre><code>&lt;serviceHostingEnvironment&gt; &lt;baseAddressPrefixFilters&gt; &lt;add prefix="http://domain.com:80"/&gt; &lt;/baseAddressPrefixFilters&gt; &lt;/serviceHostingEnvironment&gt; </code></pre> <p>What is the best solution in this scenario which would allow us to hit a WCF service via <a href="http://domain.com/service.svc" rel="nofollow noreferrer">http://domain.com/service.svc</a> and <a href="http://server1.domain.com/service.svc" rel="nofollow noreferrer">http://server1.domain.com/service.svc</a>?</p> <p>If we should create our own ServiceFactory as some sites suggest, does anyone have any sample code on this?</p> <p>Any help is much appreciated.</p> <p>EDIT: We will need to be able to access the WCF service from either of the two addresses, if at all possible.</p> <p>Thank you.</p>
<p>On your bigIP Create 2 new virtual servers <a href="http://server1.domain.com/" rel="nofollow noreferrer">http://server1.domain.com/</a> <a href="http://server2.domain.com/" rel="nofollow noreferrer">http://server2.domain.com/</a></p> <p>create a pool for each VS with only the specific server in it - so there will be no actual load balancing and access it that way. If you are short on external IP'S you can still use the same IP as your production domain name and just use an irule to direct traffic to the appropriate pool</p> <p>Hope this helps</p>
<p>The URL it uses is based on the bindings in IIS. Does the website have more than one binding? If it does, or is the WCF service used by multiple sites? If it is, then you are SOL AFAIK. We ran into this issue. Basically, there can be only one IIS binding for HTTP, otherwise it bombs.</p> <p>Also, here's info on <a href="http://www.robzelt.com/blog/2007/01/24/WCF+This+Collection+Already+Contains+An+Address+With+Scheme+Http.aspx" rel="nofollow noreferrer">implementing a ServiceHostFactory</a>. That WILL work if it's possible that your WCF service only be accessible through 1 address (unfortunately for us, this was not possible).</p>
14,922
<p>I am writing code in VS2005 using its STL. I have one UI thread to read a vector, and a work thread to write to a vector. I use ::boost::shared_ptr as vector element.</p> <pre><code>vector&lt;shared_ptr&lt;Class&gt;&gt; vec; </code></pre> <p>but I find, if I manipulate the vec in both thread in the same time(I can guarantee they do not visit the same area, UI Thread always read the area that has the information)</p> <p>vec.clear() seem can not release the resource. problem happend in shared_ptr, it can not release its resource.</p> <p>What is the problem? Does it because when the vector reach its order capacity, it reallocates in memory, then the original part is invalidated.</p> <p>As far as I know when reallocating, iterator will be invalid, why some problem also happened when I used vec[i]. //-----------------------------------------------</p> <p>What kinds of lock is needed? I mean: If the vector's element is a shared_ptr, when a thread A get the point smart_p, the other thread B will wait till A finishes the operation on smart_p right? Or just simply add lock when thread is trying to read the point, when the read opeation is finished, thread B can continu to do something.</p>
<p>When you're accessing the same resource from more than one thread, locking is necessary. If you don't, you have all sorts of strange behaviour, like you're seeing.</p> <p>Since you're using Boost, an easy way to use locking is to use the Boost.Thread library. The best kind of locks you can use for this scenario are reader/writer locks; they're called <a href="http://www.boost.org/doc/libs/1_37_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex" rel="nofollow noreferrer"><code>shared_mutex</code></a> in Boost.Thread.</p> <p>But yes, what you're seeing is essentially undefined behaviour, due to the lack of synchronisation between the threads. Hope this helps!</p> <p>Edit to answer OP's second question: You should use a reader lock when reading the smart pointer out of the vector, and a writer lock when writing or adding an item to the vector (so, the mutex is for the vector only). If multiple threads will be accessing the <em>pointed-to</em> object (i.e., what the smart pointer points to), then separate locks should be set up for them. In that case, you're better off putting a mutex object in the object class as well.</p>
<p>Another alternative is to eliminate the locking altogether by ensuring that the vector is accessed in only one thread. For example, by having the worker thread send a message to the main thread with the element(s) to add to the vector.</p>
33,650
<p>Let's say I'm building a data access layer for an application. Typically I have a class definition for a each kind of object that is stored in the database. Of course, the actual data access retrieves data in the form of a datareader, typed or untyped dataset, or similar, usually with the data needed to create one object per row in the results.</p> <p>How would you go about creating your object instances in the data layer? Would have a constructor that accepts a datarow? If so, how would you make that type-safe? Or would you have your constructor list out one parameter for each field you want to instantiate, even if there could be many fields? Would you mark this constructor 'internal'?</p>
<p>If you aren't content with DataRow or SqlDataReader, you should look at an ORM system like Linq to Sql or nHibernate, instead of re-inventing the wheel yourself.</p> <p>(By the way, this is called the "ActiveRecord" pattern)</p>
<p>@Joel (re: complex queries, joins, etc)</p> <p>The NHibernate and Castle ActiveRecord tool can handle very complex queries and joins via class relationships and a thorough 'Expression' class (which you can add to the query methods) or the use of the 'Hibernate Query Language' (HQL).</p> <p>You can Google any of these details, check the official <a href="http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/" rel="nofollow noreferrer">documentation</a>, or see the awesome <a href="http://www.summerofnhibernate.com/" rel="nofollow noreferrer">Summer of NHibernate</a> screencasts.</p>
6,151
<p>How do I raise an event from a user control that was created dynamically?</p> <p>Here's the code that I'm trying where Bind is a public EventHandler</p> <pre><code>protected indDemographics IndDemographics; protected UserControl uc; override protected void OnInit(EventArgs e) { uc = (UserControl)LoadControl("indDemographics.ascx"); IndDemographics.Bind += new EventHandler(test_handler); base.OnInit(e); } </code></pre> <p>I get a null object for IndDemographics. Can anyone point me to a complete code sample? Thanks in advance...</p>
<p>First off, you'll need to make sure that you have the event defined in your usercontrol's code.</p> <p>for example:</p> <pre><code>public class MyUserControl Inherits UserControl Public Event Bind(sender as object, e as EventArgs) public sub SomeFunction() RaiseEvent Bind(me, new EventArgS()) End Sub End Class </code></pre> <p>After this, then you can bind to the Event. Now,for your other issue, are you loading this control dynamically or is it declared on your ASPX side? If it's on your ASPX side, then you don't need the LoadControl, as declaring an object as <strong>Runat=Server</strong> on the ASPX side instantiates an instance of said class.</p> <p>If not, then you'll need to make sure you're using the Virtual Path for the location of the ASCX file. (in your example, you'd use <strong>"~/indDemographics.ascx"</strong> if the ASCX was at the root of the website). At this point you'd need to add it to the page (or a placeholder or some other container object).</p> <p>Regardless, of which way you instantiate an instance of the UserControl, you then associate the Event Handler to the Event of the instance of the class. For example:</p> <pre><code>Dim btn As New Button; AddHandler btn.Click, AddressOf MyButtonClickEventHandler </code></pre> <p>Now, for the reason that you're getting a NULL reference in the example code. </p> <p>When you use the LoadControl reference, then the instance of your object is in the <strong>UC</strong> variable. In the example, you declare two objects, UC as a type of UserControl and indDemographics as a type of indDemographics. </p> <p>When you use the LoadControl, you're instantiating an instance of indDemographics and assigning it to UC. When you try to assign the event handler to the IndDemographics variable, it has never actually been instantiated.</p> <p>Ultimately, your code should look more along these lines:</p> <pre><code>protected indDemographics IndDemographics; override protected void OnInit(EventArgs e) { indDemographics = LoadControl("~/indDemographics.ascx"); IndDemographics.Bind += new EventHandler(test_handler); base.OnInit(e); } </code></pre>
<p>I see it (IndDemographics) declared but never actually created, so I'd expect it to be null with just this code.</p>
44,083
<p>Is there a way (preferrably using JavaScript) to determine whether a URL is to a SWF or a JPG? </p> <p>The obvious answer is to sniff the filename for ".jpg" or ".swf" but I'm dealing with banners that are dynamically decided by the server and usually have a lot of parameters and generally don't include an extension. </p> <p>so i'm wondering if I could load the file first and then read it somehow to determine whether it's SWF or JPG, and then place it, because the JavaScript code I'd need to display a JPG vs a SWF is very different. </p> <p>Thanks! </p>
<p>You could use javascript to detect if it is a image by creating a dynamic img-tag.</p> <pre><code>function isImage(url, callback) { var img = document.createElement('img'); img.onload = function() { callback(url); } img.src = url; } </code></pre> <p>And then calling it with:</p> <pre><code>isImage('http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/bald-eagle-head.jpg', function(url) { alert(url + ' is a image'); }); </code></pre> <p><strong>Update</strong> This version will always execute the callback with a boolean value.</p> <pre><code> function isImage(url) { var img = document.createElement('img'); img.onload = function() { isImageCallback(url, true); } img.onerror = function() { isImageCallback(url, false); } img.src = url; } function isImageCallback(url, result) { if (result) alert(url + ' is an image'); else alert(url + ' is not an image'); } </code></pre> <p>Put your logic in the isImageCallback function.</p>
<p>If the URL doesn't have an extension then there is no way to tell without requesting the file from the server.</p>
33,378
<p>We need to develop some kind of buffer management for an application we are developing using C#.</p> <p>Essentially, the application receives messages from devices as and when they come in (there could be many in a short space of time). We need to queue them up in some kind of buffer pool so that we can process them in a managed fashion.</p> <p>We were thinking of allocating a block of memory in 256 byte chunks (all messages are less than that) and then using buffer pool management to have a pool of available buffers that can be used for incoming messages and a pool of buffers ready to be processed.</p> <p>So the flow would be "Get a buffer" (process it) "Release buffer" or "Leave it in the pool". We would also need to know when the buffer was filling up. </p> <p>Potentially, we would also need a way to "peek" into the buffers to see what the highest priority buffer in the pool is rather than always getting the next buffer.</p> <p>Is there already support for this in .NET or is there some open source code that we could use?</p>
<p>C# sharps memory management is actually quite good, so instead of having a pool of buffers, you could just allocate exactly what you need and stick it into a queue. Once you are done with buffer just let the garbage collector handle it.</p> <p>One other option (knowing only very little about your application), is to process the messages minimally as you get them, and turn them into full fledged objects (with priorities and all), then your queue could prioritize them just by investigating the correct set of attributes or methods.</p> <p>If your messages come in too fast even for minimal processing you could have a two queue system. One is just a queue of unprocessed buffers, and the next queue is the queue of message objects built from the buffers.</p> <p>I hope this helps.</p>
<p>I'm doing something similar. I have messages coming in on MTA threads that need to be serviced on STA threads. </p> <p>I used a <a href="http://blogs.msdn.com/pfxteam/" rel="nofollow noreferrer">BlockingCollection</a> (part of the parallel fx extensions) that is monitored by several STA threads (configurable, but defaults to xr * the number of cores). Each thread tries to pop a message off the queue. They either time out and try again or successfully pop a message off and service it. </p> <p>I've got it wired with perfmon counters to keep track of idle time, job lengths, incoming messages, etc, which can be used to tweak the queue's settings. </p> <p>You'd have to implement a custom collection, or perhaps extend BC, to implement queue item priorities.</p> <p>One of the reasons why I implemented it this way is that, as I understand it, <a href="http://en.wikipedia.org/wiki/Queueing_theory" rel="nofollow noreferrer">queueing theory</a> generally favors single-line, multiple-servers (why do I feel like I'm going to catch crap about that?). </p>
35,688
<p>Is there a way to tunnel a proxy to access a remote sql server database on visual studio 2008? I'm working in a project at college that uses a sql server database but the access is restricted to the internal network. I'd like to access the database from my home too. Thanks in advance.</p>
<p>You can <a href="https://stackoverflow.com/questions/68799/setting-up-a-vpn">setup a VPN</a> easily...</p> <p>Take a look to <a href="http://secure.logmein.com/products/hamachi/vpn.asp?lang=es" rel="nofollow noreferrer">Hamachi</a> and <a href="http://www.remobo.com/" rel="nofollow noreferrer">Rebombo</a>, very easy 0 configuration vpn...</p>
<p>If the colledge has VPN set up, you can set up the VPN on your computer to access the database from home.</p>
31,991
<p>I have HTML that includes symbols such as the Trademark "TM" as superscript (&trade;). In normal HTML, I would use <code>"&amp;trade;"</code> or <code>&amp;#153;</code> to display the Trademark TM. However, I can find no way to import HTML like this into Flex and have it displayed correctly. I am having similar issues with the <code>&lt;li&gt;</code> tag.</p> <p>My HTML:</p> <pre><code>&lt;p&gt;This information is intellectual property of My Company&amp;#153;.&lt;/p&gt; &lt;p&gt;Available features:&lt;/p&gt; &lt;li&gt;Feature 1&lt;/li&gt; &lt;li&gt;Feature 2&lt;/li&gt; &lt;li&gt;Feature 3&lt;/li&gt; &lt;li&gt;Feature 4&lt;/li&gt; &lt;p&gt;COPYRIGHT INFORMATION:&lt;/p&gt; &lt;p&gt;Copyright &amp;#169; 2008, My Company. All rights reserved.&lt;/p&gt; </code></pre> <p>The only way that I've gotten this to work is by copying and pasting the content directly into Flex:</p> <pre><code>&lt;mx:Text width="100%" height="100%"&gt; &lt;mx:htmlText&gt; &lt;![CDATA[ This information is intellectual property of My Company™. Available features: • Feature 1 • Feature 2 • Feature 3 • Feature 4 COPYRIGHT INFORMATION: Copyright © 2008, My Company. All rights reserved. ]]&gt; &lt;/mx:htmlText&gt; &lt;/mx:Text&gt; </code></pre> <p>I want to use an external HTML file that I can import into my Flex App at run time, so that I don't have to recompile the app for a simple content change. </p> <p>I've heard of too many issues with the iFrame option, so I want to avoid that, if possible.</p> <p>Does anyone have any other good suggestions for dealing with this issue?</p> <p>Thank you.</p>
<p>Okay, this is a tricky one. I just finished a project where we used this open-source library to display HTML: <a href="http://code.google.com/p/flex-htmlfilter" rel="nofollow noreferrer">http://code.google.com/p/flex-htmlfilter</a></p> <p>It handles lists, tables, etc, and is pretty easy to work with. But, I don't think it supports the trademark symbol. It does support some of the others, though.</p> <p>I'm using it to pull content from a CMS and display in my flash movie. It has worked great, and allows me all the flash styling flexibility I need.</p>
<p>I don't know if this is a good solution for all problems, but if you want to use a RichText control you can load FlowText in to it which allows you to use more HTML, including superscript and other glyphs, like the ones you want to use.</p> <p><a href="https://stackoverflow.com/questions/4601507/how-to-use-superscripting-in-flex/13164076#13164076">How to use superscripting in flex?</a></p>
39,928
<p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p> <ul> <li><p><strong>Firstly</strong>: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li> <li><p><strong>Secondly</strong>: When writing a program from scratch in python, what are some good ways to greatly improve performance?</p></li> </ul> <p>For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?</p>
<p>The usual suspects -- profile it, find the most expensive line, figure out what it's doing, fix it. If you haven't done much profiling before, there could be some big fat quadratic loops or string duplication hiding behind otherwise innocuous-looking expressions.</p> <p>In Python, two of the most common causes I've found for non-obvious slowdown are string concatenation and generators. Since Python's strings are immutable, doing something like this:</p> <pre><code>result = u"" for item in my_list: result += unicode (item) </code></pre> <p>will copy the <em>entire</em> string twice per iteration. This has been well-covered, and the solution is to use <code>"".join</code>:</p> <pre><code>result = "".join (unicode (item) for item in my_list) </code></pre> <p>Generators are another culprit. They're very easy to use and can simplify some tasks enormously, but a poorly-applied generator will be much slower than simply appending items to a list and returning the list.</p> <p>Finally, <strong>don't be afraid to rewrite bits in C!</strong> Python, as a dynamic high-level language, is simply not capable of matching C's speed. If there's one function that you can't optimize any more in Python, consider extracting it to an extension module.</p> <p>My favorite technique for this is to maintain both Python and C versions of a module. The Python version is written to be as clear and obvious as possible -- any bugs should be easy to diagnose and fix. Write your tests against this module. Then write the C version, and test it. Its behavior should in all cases equal that of the Python implementation -- if they differ, it should be very easy to figure out which is wrong and correct the problem.</p>
<p>A couple of ways to speed up Python code were introduced after this question was asked:</p> <ul> <li><strong>Pypy</strong> has a JIT-compiler, which makes it a lot faster for CPU-bound code.</li> <li>Pypy is written in <a href="https://code.google.com/p/rpython/" rel="nofollow"><strong>Rpython</strong></a>, a subset of Python that compiles to native code, leveraging the LLVM tool-chain.</li> </ul>
20,809
<p>I admit - I'm a complete novice when it comes to unit testing. I can grasp the concepts easily enough (test one thing, break-fix-test-repeat, etc.), but I'm having a bit of a problem getting my mind around this one...</p> <p>I've been tasked with rewriting a large section of our application, and I've got the class structure down pretty well. We have our test projects mixed right in with the rest of the solution, and all the references are lining up the way we want them to. Unfortunately, there are a few Friend classes that can only be accessed from inside the same namespace. As it stands, the test class is not a member of this namespace, so I cannot get direct access to any of those underlying methods, which <strong>REALLY</strong> need to be tested. </p> <p>From what I've been reading, I could create a public mockup of the classes in question and test it that way, but I'm concerned that down the road someone will make a change in the production code and not copy it out to the test code, defeating the purpose of testing entirely. Another option would be to change the access level on the classes themselves, but that would involve a lot of overhead and fiddling with the code already in place. The idea of writing an interface has also come up, but creating a whole structure of interfaces for the sake of testing hasn't flown in management.</p> <p>Am I just missing something here? What would be the best way to make sure those underlying classes are indeed functioning correctly without changing the access to them?</p>
<p>You can also make a subclass of the test-subject that is in the same namespace as the test-subject, and the subclass could expose whatever features necessary for testing. </p> <p>Assuming you have some way of giving this subclass a "test" scope, you're home free. (You dont want this class in your regular code since it breaks encapsulation)</p>
<p>I think that your unit tests should not <em>require</em> anything of the source code, so the first answer certainly works. Have you considered using Reflection? I think it gets around changing the source code; there's a good discussion of this here: <a href="http://www.codeproject.com/KB/cs/testnonpublicmembers.aspx" rel="nofollow noreferrer">CodeProject</a></p>
29,877
<p>I have been looking for a quadtree/quadtree node implementation on the net for ages. There is some basic stuff but nothing that I would be able to really use it a game.</p> <p>My purpose is to store objects in a game for processing things such as collision detection. I am not 100% certain that a quadtree is the best data structure to use, but from what I have read it is. I have already coded a Red-Black tree, but I don't really know if the performance would be good enough for my game (which will be an adventure 3rd person game like Ankh).</p> <p>How would I write a basic but complete quadtree class (or octree) in C++? How would you use the quad tree for collisions?</p>
<p>Quadtrees are used when you only need to store things that are effectively on a plane. Like units in a classic RTS where they are all on the ground or just a little bit above it. Essentially each node has links to 4 children that divide the node's space up into evenly distributed quarters.</p> <p>Octrees do the same but in all three dimensions rather than just two, and thus they have 8 child nodes and partition the space up into eights. They should be used when the game entities are distributed more evenly among all three dimensions.</p> <p>If you are looking for a binary tree - like a red-black tree - then you want to use a data structure called a binary space partitioning tree (BSP tree) or a version of it called the KD Tree. These partition space into halves using a plane, in the KD tree the planes are orthogonal (on the XZ, XY, ZY axes) so sometimes it works better in a 3D scene. BSP trees divide the scene up using planes in any orientation, but they can be quite useful, and they were used as far back as Doom.</p> <p>Now because you've partitioned the game space you now don't have to test every game entity against every other game entity to see if they collide, which is an O(n^2) algorithm at best. Instead you query the data structure to return the game entities within a sub-region of the game space, and only perform collision detection for those nodes against each other.</p> <p>This means that collision detection for all game entities should be n O(nlogn) operation (at worst).</p> <p>A couple of extra things to watch out for:</p> <ul> <li>Make sure you test game entities from adjacent nodes, not just the ones in the current node, since they could still collide.</li> <li>Rebalance the data structure after the entities have moved since you may have empty nodes in the data structure now, or ones that contain too many entities for good performance (also the degenerate case of all entities being in the same node).</li> </ul>
<p>Trees in general are problematic for this in that any item inserted can lie on a boundary, and all the methods of dealing with that situation are fairly unsatisfactory.</p> <p>You'll most likely want to sort your objects into moveable and static, and check anything that moved on a given frame against the static objects.</p> <p>BSP Trees are the accepted solution for static geometry (boundary cases handled by splitting the object into two pieces), for dynamic try something like Sort and Sweep (also known as Sweep and Prune).</p>
48,546
<p>I have a image upload form that should take image types (PNG, JPEG, GIF), resize it and then save it to a path. </p> <p>For some reason I can't get the PNG file types to work, it works fine with JPEG/GIF and the file is copied so it looks like it's something to do with how I'm creating the PNG. </p> <p>Does PNG creation in PHP require different parameters or options? Some sample code of lines that do image creation:</p> <pre><code>$src = imagecreatefrompng($uploadedfile); imagecreatetruecolor($newWidth,$newHeight) imagecopyresampled($tmp,$src,0,0,0,0,$newWidth,$newHeight,$width,$height); imagepng($tmp,$destinationPath."/".$destinationFile,100); </code></pre> <p>The same commands work for JPG and GIF.</p>
<p>You need to look how your PHP is built.. Eg:</p> <pre><code>GD Support enabled GD Version bundled (2.0.28 compatible) PNG Support enabled </code></pre> <p>If you don't have PNG support compiled in, you'll need to have that updated.</p>
<p>Are you starting with PNG-8 images? There are some issues with PNG-8 vs PNG-24 when working with PHP. Make sure PNG support is compiled in, then take a <a href="http://www.php.net/manual/en/function.imagecreatefrompng.php#71091" rel="nofollow noreferrer">look at this persons solution to the PNG-8 problem</a>.</p>
21,261
<p>For the life of me, I can't remember how to set, delete, toggle or test a bit in a bitfield. Either I'm unsure or I mix them up because I rarely need these. So a "bit-cheat-sheet" would be nice to have.</p> <p>For example: </p> <pre><code>flags = flags | FlagsEnum.Bit4; // Set bit 4. </code></pre> <p>or</p> <pre><code>if ((flags &amp; FlagsEnum.Bit4)) == FlagsEnum.Bit4) // Is there a less verbose way? </code></pre> <p>Can you give examples of all the other common operations, preferably in C# syntax using a [Flags] enum?</p>
<p><strong>I did some more work on these extensions - <a href="http://hugoware.net:4000/blog/enumeration-extensions-2-0" rel="noreferrer" >You can find the code here</a> </strong></p> <p>I wrote some extension methods that extend System.Enum that I use often... I'm not claiming that they are bulletproof, but they have helped... <em>Comments removed...</em></p> <pre><code>namespace Enum.Extensions { public static class EnumerationExtensions { public static bool Has&lt;T&gt;(this System.Enum type, T value) { try { return (((int)(object)type &amp; (int)(object)value) == (int)(object)value); } catch { return false; } } public static bool Is&lt;T&gt;(this System.Enum type, T value) { try { return (int)(object)type == (int)(object)value; } catch { return false; } } public static T Add&lt;T&gt;(this System.Enum type, T value) { try { return (T)(object)(((int)(object)type | (int)(object)value)); } catch(Exception ex) { throw new ArgumentException( string.Format( &quot;Could not append value from enumerated type '{0}'.&quot;, typeof(T).Name ), ex); } } public static T Remove&lt;T&gt;(this System.Enum type, T value) { try { return (T)(object)(((int)(object)type &amp; ~(int)(object)value)); } catch (Exception ex) { throw new ArgumentException( string.Format( &quot;Could not remove value from enumerated type '{0}'.&quot;, typeof(T).Name ), ex); } } } } </code></pre> <p>Then they are used like the following</p> <pre><code>SomeType value = SomeType.Grapes; bool isGrapes = value.Is(SomeType.Grapes); //true bool hasGrapes = value.Has(SomeType.Grapes); //true value = value.Add(SomeType.Oranges); value = value.Add(SomeType.Apples); value = value.Remove(SomeType.Grapes); bool hasOranges = value.Has(SomeType.Oranges); //true bool isApples = value.Is(SomeType.Apples); //false bool hasGrapes = value.Has(SomeType.Grapes); //false </code></pre>
<p>C++ operations are: &amp; | ^ ~ (for and, or, xor and not bitwise operations). Also of interest are >> and &lt;&lt;, which are bitshift operations.</p> <p>So, to test for a bit being set in a flag, you would use: if (flags &amp; 8) //tests bit 4 has been set</p>
11,935
<p>Following on from <a href="https://stackoverflow.com/questions/223832/check-a-string-to-see-if-all-characters-are-hexadecimal-values">this question</a> what would be the best way to write a Char.IsHex() function in C#. So far I've got this but don't like it:</p> <pre><code>bool CharIsHex(char c) { c = Char.ToLower(c); return (Char.IsDigit(c) || c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f') } </code></pre>
<p>From <a href="https://stackoverflow.com/questions/223832/check-a-string-to-see-if-all-characters-are-hexadecimal-values#223854">my answer</a> to the question you linked to:</p> <pre><code>bool is_hex_char = (c &gt;= '0' &amp;&amp; c &lt;= '9') || (c &gt;= 'a' &amp;&amp; c &lt;= 'f') || (c &gt;= 'A' &amp;&amp; c &lt;= 'F'); </code></pre>
<p>You can use regular expressions in an extension function:</p> <pre><code>using System.Text.RegularExpressions; public static class Extensions { public static bool IsHex(this char c) { return (new Regex("[A-Fa-f0-9]").IsMatch(c.ToString())); } } </code></pre>
28,276
<p>I have a base class object array into which I have typecasted many different child class objects and am passing it to a sub vi. Is there any way by which I can find out the original type of the object of each individual elements in the array?</p> <p>Thanks ...</p>
<p>For posterity, this was crossposted to the <a href="http://forums.lavag.org/Finding-Object-type-t12034.html&amp;p=52521#entry52521" rel="nofollow noreferrer" title="LAVA">LAVA</a> forums. The user Aristos Queue, one of the developers of LabVIEW's native OO features, answered with the following:</p> <blockquote> <p>Using a dynamic dispatch method in every class is the recommended way of handling this, although the recommendation is to create a method that does whatever it is you're trying to do. I'm guessing that you're thinking of a dynamic dispatch method that returns a name or ID of the object so you can say, "Is it equal to this? Ok, then it must be this class..." and then you do Action X if it is that class. If you write a dynamic dispatch method ActionX.vi and then override it appropriately, you'll save yourself on performance and have much easier time for code maintenance in the future. </p> <p>You can also use the To More Specific node to test if a given object can be downcast to a given type -- this allows for inheritance testing as opposed to the name or ID comparison that only does type equivalence. If the To More Specific node returns an error then it is not of the destination type. </p> <p>So your options are (in order of preference):</p> <ul> <li>dynamic dispatch method that does the action</li> <li>To More Specific node to do type testing</li> <li>dynamic dispatch method that returns name/ID of the class of the object</li> <li>Get Path of LabVIEW Object.vi (shipped in vi.lib in LabVIEW 8.5 but not added to the palettes until LabVIEW 8.6) </li> </ul> </blockquote>
<p>NI has a good <a href="http://zone.ni.com/devzone/cda/tut/p/id/3574" rel="nofollow noreferrer">overview of LVOOP</a> that is a must-read, since OO is implemented in a unique way for LabVIEW.</p> <p>Have you tried the '<a href="http://zone.ni.com/reference/en-XX/help/371361B-01/glang/to_more_generic_class/" rel="nofollow noreferrer">to more generic class</a>' and '<a href="http://zone.ni.com/reference/en-XX/help/371361D-01/glang/to_more_specific_class/" rel="nofollow noreferrer">to more specific class</a>' functions, on the application control palette?</p>
16,792
<p>I'm fairly new to c# so that's why I'm asking this here.</p> <p>I am consuming a web service that returns a long string of XML values. Because this is a string all the attributes have escaped double quotes</p> <pre><code>string xmlSample = "&lt;root&gt;&lt;item att1=\"value\" att2=\"value2\" /&gt;&lt;/root&gt;" </code></pre> <p>Here is my problem. I want to do a simple string.replace. If I was working in PHP I'd just run strip_slashes().</p> <p>However, I'm in C# and I can't for the life of me figure it out. I can't write out my expression to replace the double quotes (") because it terminates the string. If I escape it then it has incorrect results. What am I doing wrong?</p> <pre><code> string search = "\\\""; string replace = "\""; Regex rgx = new Regex(search); string strip = rgx.Replace(xmlSample, replace); //Actual Result &lt;root&gt;&lt;item att1=value att2=value2 /&gt;&lt;/root&gt; //Desired Result &lt;root&gt;&lt;item att1="value" att2="value2" /&gt;&lt;/root&gt; </code></pre> <blockquote> <p>MizardX: To include a quote in a raw string you need to double it. </p> </blockquote> <p>That's important information, trying that approach now...No luck there either There is something going on here with the double quotes. The concepts you all are suggesting are solid, BUT the issue here is dealing with the double quotes and it looks like I'll need to do some additional research to solve this problem. If anyone comes up with something please post an answer.</p> <pre><code>string newC = xmlSample.Replace("\\\"", "\""); //Result &lt;root&gt;&lt;item att=\"value\" att2=\"value2\" /&gt;&lt;/root&gt; string newC = xmlSample.Replace("\"", "'"); //Result newC "&lt;root&gt;&lt;item att='value' att2='value2' /&gt;&lt;/root&gt;" </code></pre>
<p>the following statement in C# </p> <pre><code>string xmlSample = "&lt;root&gt;&lt;item att1=\"value\" att2=\"value2\" /&gt;&lt;/root&gt;" </code></pre> <p>will actually store the value </p> <pre><code>&lt;root&gt;&lt;item att1="value" att2="value2" /&gt;&lt;/root&gt; </code></pre> <p>whereas </p> <pre><code>string xmlSample = @"&lt;root&gt;&lt;item att1=\""value\"" att2=\""value2\"" /&gt;&lt;/root&gt;"; </code></pre> <p>have the value of </p> <pre><code>&lt;root&gt;&lt;item att1=\"value\" att2=\"value2\" /&gt;&lt;/root&gt; </code></pre> <p>for the second case, you need to replace the slash () by empty string as follow</p> <pre><code>string test = xmlSample.Replace(@"\", string.Empty); </code></pre> <p>the result will be </p> <pre><code>&lt;root&gt;&lt;item att1="value" att2="value2" /&gt;&lt;/root&gt; </code></pre> <p>P.S. </p> <ol> <li>slash (<code>\</code>) is default escape character in C#</li> <li>to ignore slashes, use @ at the beginning of string </li> <li>if @ is used, the escape character is double quote (")</li> </ol>
<p>If you are getting an XML string why not use XML instead strings?</p> <p>you will have access to all elements and attributes and it will be much easier and extremely fast if using the System.Xml namespace</p> <p>in your example you are getting this string:</p> <pre><code>string xmlSample = "&lt;root&gt;&lt;item att1=\"value\" att2=\"value2\" /&gt;&lt;/root&gt;"; </code></pre> <p>All you need to do is convert that string into a XML Document and use it, like:</p> <pre><code>System.Xml.XmlDocument xml = new System.Xml.XmlDocument(); xml.LoadXml(xmlSample); System.Xml.XmlElement _root = xml.DocumentElement; foreach (System.Xml.XmlNode _node in _root) { Literal1.Text = "&lt;hr/&gt;" + _node.Name + "&lt;br/&gt;"; for (int iAtt = 0; iAtt &lt; _node.Attributes.Count; iAtt++) Literal1.Text += _node.Attributes[iAtt].Name + " = " + _node.Attributes[iAtt].Value + "&lt;br/&gt;"; } </code></pre> <p>in ASP.NET this will output to the Literal1 something like:</p> <pre><code>item att1 = value att2 = value2 </code></pre> <p>once you have the element in a XmlElement, it is very easy to search and get the values and names for what's in that element.</p> <p>give it a try, I use it a lot when retrieving WebServices responses and when I store something in a XML file as settings for a small application for example.</p>
36,261
<p>I have a CSS like this</p> <pre><code>ul { list-style-image:url(images/bulletArrow.gif); } ul li { background: url(images/hr.gif) no-repeat left bottom; padding: 5px 0 7px 0; } </code></pre> <p>But the bullet image doesn't align properly in IE (it's fine in Firefox). I already have a background image for li, so I can't use the bullet image as a background. Is there any solution to this?</p> <p>Thanks in advance.</p>
<p>There is a good explanation and solution of this here: <a href="http://css.maxdesign.com.au/listutorial/master.htm" rel="noreferrer">http://css.maxdesign.com.au/listutorial/master.htm</a></p> <p>It says that using <code>list-style-image</code> results in inconsistent placement of the image with different browsers. Then it explains how to use background images for the bullets for a better result.</p>
<p>I see you're removing left padding for list items. For IE, you need to do the same with the left margin - either completely remove it (set to zero) or make it something smaller than the default. Then your list items will align nicely.</p>
34,901
<p>I'm just beginning to learn ASP.NET MVC and I've run into a question. I'm trying to determine whether I should use HtmlHelper to create client controls or if I should just roll my own. My gut wants to lean towards just rolling my own because it gives me total control - and use jQuery to decorate and add cross-browswer functionality. But then I can see advantages of using HtmlHelper for various complex controls that may involve things like paging.</p> <p>I'm looking for experiences about when it was better to use HtmlHelper and when it was better to roll your own.</p>
<p>The more they add to HtmlHelper the more I end up using them myself.</p> <p>Take a look at these posts from ScottGu: <a href="http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx" rel="nofollow noreferrer">MVC Preview 5</a> and <a href="http://weblogs.asp.net/scottgu/archive/2008/10/16/asp-net-mvc-beta-released.aspx" rel="nofollow noreferrer">MVC Beta</a></p> <p>If you don't use the HtmlHelper versions of the input boxes, you won't get the nice, free validation.</p> <p>Also, I'm not sure what prevents you from decorating the HtmlHelper controls with whatever you need to make them usable for jQuery.</p> <p>You can add whatever attributes you need using the htmlAttributes overload like so:</p> <pre><code>&lt;%= Html.TextBox("LastName", ViewData.Model.LastName, new { @class = "required" })%&gt; </code></pre> <p>The interesting part for what I'm talking about is the anonymous object you see there (new { @class = "required" }).</p> <p>You can put anything in there you'd need, and it gets slapped onto the attribute section of the control.</p> <p>Good luck!</p>
<p>I created a fluent interface for HTML, and I have decided to share it <a href="http://code.google.com/p/mvcfluenthtml/" rel="nofollow noreferrer">here</a>. Maybe you will find it a good alternative. I also wrote a <a href="http://lunaverse.wordpress.com/2008/11/24/mvcfluenthtml-fluent-html-interface-for-ms-mvc/" rel="nofollow noreferrer">blog post</a> about it. </p> <p>Here's a teaser:</p> <pre><code>&lt;%=this.TextBox(x =&gt; x.FirstName).Class("required").Label("First Name:")%&gt; &lt;%=this.CheckBox("enabled").LabelAfter("Enabled").Title("Click to enable.").Styles(vertical_align =&gt; "middle")%&gt; </code></pre> <p>Critique and contributions are welcome.</p>
41,075
<p>We have an application which needs to use Direct3D. Specifically, it needs at least DirectX 9.0c version 4.09.0000.0904. While this should be present on all newer XP machines it might not be installed on older XP machines. How can I programmatically (using C++) determine if it is installed? I want to be able to give an information message to the user that Direct3D will not be available.</p>
<p>Call DirectXSetupGetVersion: <a href="http://msdn.microsoft.com/en-us/library/microsoft.directx_sdk.directsetup.directxsetupgetversion" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/microsoft.directx_sdk.directsetup.directxsetupgetversion</a></p> <p>You'll need to include dsetup.h</p> <p>Here's the sample code from the site:</p> <pre><code>DWORD dwVersion; DWORD dwRevision; if (DirectXSetupGetVersion(&amp;dwVersion, &amp;dwRevision)) { printf("DirectX version is %d.%d.%d.%d\n", HIWORD(dwVersion), LOWORD(dwVersion), HIWORD(dwRevision), LOWORD(dwRevision)); } </code></pre>
<p>According to the DirectX 9.0 SDK (summer 2004) documentation, see the GetDXVer SDK sample at \Samples\Multimedia\DXMisc\GetDXVer.</p>
10,515
<p>Are there any browser extensions or printers with OctoPrint built in that would allow me to print straight from the browser?</p> <p>Thinking of a workflow like this:</p> <ol> <li>Make something with Tinkercad (or other online service)</li> <li>download stl or obj</li> <li>select print from bookmark or dropdown menu</li> <li>print is sent to printer and starts printing</li> </ol>
<p>There was the <a href="https://plugins.octoprint.org/plugins/curalegacy/" rel="nofollow noreferrer">CuraEngine</a> plugin, but it's not really maintained anymore. It should still work though</p>
<p>This works for OctoPI (OctoPrint on a Raspberry Pi).</p> <ol> <li>Add the Samba package to your OctoPrint machine.</li> <li>open an SMB connection to that machine from your browser machine</li> <li>Save your STL to <code>/home/pi/.octoprint/uploads</code> on the Raspberry Pi.</li> </ol> <p>You can save directly from your slicer the same way.</p>
1,475
<p>How do I convert a string to the variable name in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="noreferrer">Python</a>?</p> <p>For example, if the program contains a object named <code>self.post</code> that contains a variable named, I want to do something like:</p> <pre><code>somefunction("self.post.id") = |Value of self.post.id| </code></pre>
<p>As referenced in Stack&nbsp;Overflow question <em><a href="https://stackoverflow.com/questions/295028/">Inplace substitution from ConfigParser</a></em>, you're looking for <code>eval()</code>:</p> <pre><code>print eval('self.post.id') # Prints the value of self.post.id </code></pre>
<p>Use this</p> <pre><code>var=&quot;variable name&quot; def returnvar(string): exec(f&quot;&quot;&quot;global rtn rtn={string}&quot;&quot;&quot;) return rtn </code></pre> <p>var will be your string and run returnvar(var) will to return variable</p>
37,683
<p>Modifying the HTTP Response Using Filters</p>
<p>I think the question relates to ASP.NET, not Java. This might help:</p> <p><a href="http://professionalaspnet.com/archive/2008/04/13/What-is-the-Difference-between-an-httpModule-and-an-httpHandler_3F00_.aspx" rel="nofollow noreferrer">http://professionalaspnet.com/archive/2008/04/13/What-is-the-Difference-between-an-httpModule-and-an-httpHandler_3F00_.aspx</a></p>
<p>Use:</p> <blockquote> <h2>response</h2> <p><strong>Purpose</strong></p> <p>The response object is an instance of the Servlet API's <code>HttpServletResponse</code> class</p> <p><strong>Examples</strong></p> <pre><code>class BookController { def downloadFile = { byte[] bytes = // read bytes response.outputStream &lt;&lt; bytes } } </code></pre> <p><strong>Description</strong></p> <p>The Servlet API's <code>HttpServletResponse</code> class can be used within Grails to perform all typical activities such as writing out binary data, writing directly to the response and sending error response codes to name but a few.</p> </blockquote> <p>Quoted from <a href="http://www.grails.org/doc/1.3.x/ref/Servlet%20API/response.html" rel="nofollow noreferrer">here</a>.</p>
45,376
<p>I have a client which is shipping via UPS, and therefore cannot deliver to Post Office boxes. I would like to be able to validate customer address fields in order to prevent them from entering addresses which include a PO box. It would be best if this were implemented as a regex so that I could use a client-side regex validation control (ASP.NET).</p> <p>I realize there's probably no way to get a 100% detection rate, I'm just looking for something that will work most of the time.</p>
<p>This should get you started. Test to see if the Address field matches this regex.</p> <pre><code>"^P\.?\s?O\.?\sB[Oo][Xx]." </code></pre> <p>Translation to English: That's a P at the beginning of the line, followed by an optional period and space, followed by an O, followed by an optional period, followed by a space, followed by "Box", followed by anything else.</p>
<p>I'd start with a regex ala Lizard (but use the "ignore case" flag :)), test on historical data, then iterate as you see what invalid inclusions and exclusions you see in testing.</p>
35,660
<p>Ever since the publication of <a href="https://rads.stackoverflow.com/amzn/click/com/0321200683" rel="nofollow noreferrer" rel="nofollow noreferrer">Enterprise Integration Patterns</a> people have been using the notation introduced in that book for documenting asynchronous heterogenous messaging systems.</p> <p>But our shop is more or less standardized around a proprietary documentation tool that does exclusively UML. Is one of the standard UML diagrams appropriate for documenting asynchronous messaging systems, including transformers, routers et al.? If yes, which one? If not, what would be a killer argument against the tweaking of UML for this purpose?</p>
<p>UML provides a mechanism for extension through <a href="http://en.wikipedia.org/wiki/Profile_%28UML%29" rel="nofollow noreferrer">profiles</a></p> <p>A profile allows you to specify stereotypes, tagged values, and constraints.</p> <p>Every stereotype can have an optional stereotype icon.</p> <p>Perhaps there is an EIP profile for UML you could download?</p> <p>If not, you can build your own profile if your UML tool supports this, and use the icons available as Visio shapes from <a href="http://www.eaipatterns.com/downloads.html" rel="nofollow noreferrer">Gregor Hohpe's website</a></p> <p>Hope this helps.</p>
<p>I think toolkit hit the nail on the head. The authors of EIP themselves refer to a UML profile in the <a href="http://www.eaipatterns.com/Introduction.html" rel="nofollow noreferrer">introduction to their book</a>. The link they give is broken though, follow instead this link to the OMG's <a href="http://www.omg.org/technology/documents/formal/eai.htm" rel="nofollow noreferrer">UML Enterprise Application Integration</a> profile.</p>
41,980
<p>I'm implementing a social networking site. I hope to use drupal or elgg and am trying out both. I'm stuck on customizing the registration to include a neighborhood in addition to city and state.</p> <p>I want to have drop-down menus customize the local information based on the more global information. So, once you choose the state, the city list is populated in a drop-down menu.</p> <p>I am building a list of the interesting neighborhoods, and can load that into a db table or whatever is convenient.</p> <p>What do you suggest?</p> <p>Javascript and/or php is fine.</p>
<p>You're going to want a module like <a href="http://drupal.org/project/activeselect" rel="nofollow noreferrer">Active Select</a> (<a href="http://drupal.org/node/298230" rel="nofollow noreferrer">Drupal 6 port here</a>) that provides that sort of functionality to the Forms API.</p>
<p>for elgg .. there are two plugins you will find usefull.</p> <ol> <li><p>forms - <a href="http://community.elgg.org/pg/plugins/kevin/read/97061/form-and-related-plugins-for-elgg-15-and-higher" rel="nofollow noreferrer">http://community.elgg.org/pg/plugins/kevin/read/97061/form-and-related-plugins-for-elgg-15-and-higher</a></p></li> <li><p>flex profiles - <a href="http://groups.google.com/group/elgg-development/browse_thread/thread/15bb22b7b5fc665e" rel="nofollow noreferrer">http://groups.google.com/group/elgg-development/browse_thread/thread/15bb22b7b5fc665e</a></p></li> </ol> <p>hope this points you in a helpful direction.</p> <p>you can even use csv and this plugin... to fill out all the info dynamically. </p> <p><a href="http://community.elgg.org/pg/plugins/naakka/read/165550/upload-users" rel="nofollow noreferrer">http://community.elgg.org/pg/plugins/naakka/read/165550/upload-users</a></p>
47,436
<p>Does anybody know a good tutorial about Squid plug-in development?</p>
<p>There is one in the squid documentation. IIRC it's fairly straightforward - squid forks a process and passes data down a pipe to the process. A somewhat out-of-date but still relevant programmer's guide can be found <a href="http://old.squid-cache.org/Doc/Prog-Guide/" rel="nofollow noreferrer">Here</a>.</p>
<p>You might also find the <a href="http://wiki.squid-cache.org/Features/AddonHelpers?highlight=%28%5CbCategoryFeature%5Cb%29%7C%28faqlisted.yes%29" rel="nofollow">Add-On Helpers for Request Manipulation</a> topic useful.</p>
16,728
<p>I'm storing some files in my database and since I'm storing them in binary format and not keeping any other information, I have to make sure that all of them are in the same format so that I'll be able to "serve" them later (If there's a <strong><em>simple</em></strong> way to infer the file type from a byte array, please tell, but that's not the focus here).</p> <p>So, what I need to do is validate every file that is uploaded to make sure it's on the required format.</p> <p>I've set up a FieldTemplate with a FileUpload control and a CustomValidator:</p> <pre><code>&lt;asp:FileUpload ID="FileUpload" runat="server" /&gt;&amp;nbsp; &lt;asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="PDF only." ControlToValidate="FileUpload" OnServerValidate="CustomValidator1_ServerValidate"&gt; &lt;/asp:CustomValidator&gt; </code></pre> <p>What I'm missing is the code to place in that CustomValidator1_ServerValidate method that checks the uploaded file to make sure it's in the right format (PDF in this case).</p> <p>Thanks in advance.</p>
<p>Use the FileUpload.PostedFile.ContentType property to validate the MIME type ( should be application/pdf ). For security reasons, also validate that the file extension is appropriate ( .pdf ). You could have a static hashtable containing mappings from MIME type to file extension(s) and use as lookup to validate an extension.</p>
<p>The FileUpload.PostedFile.ContentType was exactly what I was looking for.</p> <p>Just a heads-up to whoever is trying to do the same thing: it seems that the MIME type for PDF files can be "application/pdf" or "text/pdf", so be sure to check for both.</p>
38,506
<p>What's the best framework for creating mock objects in Java? Why? What are the pros and cons of each framework?</p>
<p>I've had good success using <a href="https://github.com/mockito/mockito" rel="noreferrer">Mockito</a>.</p> <p>When I tried learning about JMock and EasyMock, I found the learning curve to be a bit steep (though maybe that's just me).</p> <p>I like Mockito because of its simple and clean syntax that I was able to grasp pretty quickly. The minimal syntax is designed to support the common cases very well, although the few times I needed to do something more complicated I found what I wanted was supported and easy to grasp.</p> <p>Here's an (abridged) example from the Mockito homepage:</p> <pre><code>import static org.mockito.Mockito.*; List mockedList = mock(List.class); mockedList.clear(); verify(mockedList).clear(); </code></pre> <p>It doesn't get much simpler than that.</p> <p>The only major downside I can think of is that it won't mock static methods.</p>
<p>I started using mocks through JMock, but eventually transitioned to use EasyMock. EasyMock was just that, --easier-- and provided a syntax that felt more natural. I haven't switched since.</p>
4,273
<p>Can you use CMFCVisualManager with a dialog based application to change the applications appearance? If so how is it done?</p> <p>The idea is to change the shape, colour etc. of controls such as push buttons using the MFC Feature Pack released with MSVC 2008.</p>
<p>No, can't be done, at least not if you're talking about the Feature Pack version. Version 10 of the BCGSoft libraries do have this functionality, see for example: <a href="http://www.bcgsoft.com/bcgcontrolbarpro-versions.htm" rel="nofollow noreferrer">http://www.bcgsoft.com/bcgcontrolbarpro-versions.htm</a> and <a href="http://www.bcgsoft.com/images/SkinnedBuiltInDlgs.jpg" rel="nofollow noreferrer">http://www.bcgsoft.com/images/SkinnedBuiltInDlgs.jpg</a>. The MFC feature pack is more or less the previous version of the BCGSoft libraries, MS bought a license from them.</p>
<p>You need to add the Common Controls manifest to your project resources. Here is the code for the manifest file:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"&gt; &lt;assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="Program Name" type="win32" /&gt; &lt;description&gt;Description of Program&lt;/description&gt; &lt;dependency&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*" /&gt; &lt;/dependentAssembly&gt; &lt;/dependency&gt; &lt;/assembly&gt; </code></pre>
9,820
<p>I've tried the tools listed <a href="http://wiki.postgresql.org/wiki/Converting_from_other_Databases_to_PostgreSQL" rel="noreferrer">here</a>, some with more success than others, but none gave me valid postgres syntax I could use (tinyint errors etc.)</p>
<p>There's a <code>mysqldump</code> option which makes it output PostgreSQL code:</p> <pre> mysqldump --compatible=postgresql ... </pre> <p>But that doesn't work too well.</p> <p>Instead, please see the <a href="https://github.com/maxlapshin/mysql2postgres" rel="nofollow noreferrer">mysql-to-postgres</a> tool as <a href="https://stackoverflow.com/a/15670452/19163">described in Linus Oleander's answer</a>.</p>
<p>you will most likely never get a tool for such task which would do all of your job for you. be prepared to do some refactoring work yourself.</p>
11,755
<p>I'm in the process of extending and improving a website that has quite a few structural problems. It looks very much like the developers before me had heard of MVC but didn't understand the ideas of abstraction or modularity. So the MVC "framework" is a) bespoke b) broken c) patched and d) there are several in use all at once. I intend to fix that.</p> <p>This is not the first time I've re-built a site's framework, BTW, but it is the first time I've had to fix an MVC framework. However, I'm coming up against some missing holes in the MVC knowledge here on SO. </p> <p>The first is how closely programmers seem to tie their SQL database with their models. This doesn't make sense to me: do programmers normally have the model looking after the data abstraction? (To me this is little better than putting SQL in raw PHP code.) Or is there a data access layer normally employed that "Does SQL"? I know from experience that the latter means the calling code doesn't have to worry about where the data is, or how to get it or how to write it: the API handles that. </p> <p>But what about the Models? Are they intended to be re-usable amongst different pages? Should they care about just where the data is stored? Shouldn't they be more concerned with handling the logic between data-fetch and data-show (e.g. turning a contact's group ID into a displayable name)? And data-save and data-write (e.g. figuring out how to turn $_POST values into savable data)?</p> <p>Maybe the MVC model really be DMVC - Data-Model-View-Controller.</p> <p>Lastly, although this is from a PHP point-of-view, how well do these concepts translate to a JSP site?</p>
<p><strong>But what about the Models? Are they intended to be re-usable amongst different pages?</strong></p> <p>Yes.</p> <p><strong>Should they care about just where the data is stored?</strong> </p> <p>No. They need not know it. All this kinda information is necessary for persistence layer or data layer.</p> <p><strong>Shouldn't they be more concerned with handling the logic between data-fetch and data-show (e.g. turning a contact's group ID into a displayable name)?</strong> </p> <p>No. They are just concerned about the business logic. Some usual application I have found the folks make the model dumb, just having attributes/properties and nothing else. The typical example in Java would be POJO, with getters/setters. We call them TOs (Transfer Objects), and use them everywhere, as a data holder. I am not really in the accord of this, IMO, there should be some methods, business related, which are appropriate and qualify to be in there. Don't make it so dumb. The new Entity Beans (EJB3) are the good example of this.</p> <p>BTW, data show is the work of a presentation layer. In java JSP is the part of view technology.</p> <p><strong>And data-save and data-write (e.g. figuring out how to turn $_POST values into savable data)?</strong></p> <p>No. This is generally done in our controllers, most of the time using some utility classes.</p>
<p>You'll find more than one thread here about whether to start work from the database schema or the user interface. There's one place to look.</p> <p>I can think of far more than one tool that takes a schema and builds your CRUD UI for you ("scaffolding") than vice versa. There's another place to look. (Poster-child: Ruby on Rails and its cognitive offspring).</p> <p>When discussing ORM tools, there are too many times (but not all by any means) when the preferred acronym would be "ROM".</p> <p>We have a lot of tools that encourage us in our evil propensity for "Ready, Fire, Aim". For management, it's the shortest line between "Proof of Concept" and "RC1".</p>
45,757
<p>How do we assign null value to int column in LINQ. eg.</p> <pre><code> SQLDBDataContext sqlD = new SQLDBDataContext(); var result = from p in sqlD.loadsRadius(Convert.ToInt32(Request["radius"]), ..... </code></pre> <p>here if Request["radius"] is null gives an error.</p> <p>I could pass 0 via this but I need to change in many already existing procedures.</p> <p>Thanks in advance.<br> <a href="http://www.ade-technologies.com" rel="nofollow noreferrer">Anil</a></p>
<p>If the exception is a FormatException, my guess is that the value returned by Request["radius"] is actually the string "null". If Request["radius"] actually returned null, Convert.ToInt32() would return zero. You may try using using int.TryParse() to avoid the exception.</p>
<p>as suggested by Codechef..</p> <pre><code>int radius = -1; int.TryParse(Request["radius"],out radius) if(radius &gt; 0) // you can remove this clause if you don't want this { SQLDBDataContext sqlD = new SQLDBDataContext(); var result = from p in sqlD.loadsRadius(radius) } </code></pre>
46,414
<p>You are given a 32-bit unsigned integer array with length up to 2<sup>32</sup>, with the property that more than half of the entries in the array are equal to N, for some 32-bit unsigned integer N. Find N looking at each number in the array only once and using at most 2 kB of memory.</p> <p>Your solution must be deterministic, and guaranteed to find N.</p>
<p>Keep one integer for each bit, and increment this collection appropriately for each integer in the array.</p> <p>At the end, some of the bits will have a count higher than half the length of the array - those bits determine N. Of course, the count will be higher than the number of times N occurred, but that doesn't matter. The important thing is that any bit which isn't part of N <em>cannot</em> occur more than half the times (because N has over half the entries) and any bit which is part of N <em>must</em> occur more than half the times (because it will occur every time N occurs, and any extras).</p> <p>(No code at the moment - about to lose net access. Hopefully the above is clear enough though.)</p>
<p>I have recollections of this algorithm, which might or might not follow the 2K rule. It might need to be rewritten with stacks and the like to avoid breaking the memory limits due to function calls, but this might be unneeded since it only ever has a logarithmic number of such calls. Anyhow, I have vague recollections from college or a recursive solution to this which involved divide and conquer, the secret being that when you divide the groups in half, at least one of the halves still has more than half of its values equal to the max. The basic rule when dividing is that you return two candidate top values, one of which is the top value and one of which is some other value (that may or may not be 2nd place). I forget the algorithm itself.</p>
35,169
<p>We are trying to create a web-service that we plan to pass a variable amount of variables to it.</p> <p>Can this be done?</p> <p>Basically instead of pass all possible parameters we wish to pass only the set values and use the defaults set in the web-service.</p> <p>Here is an example of the XML we are looking to send, we would sent an unknown amount of functions depending on the needed return.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;soap:Body&gt; &lt;WebMethod xmlns="http://tempuri.org/"&gt; &lt;domains&gt; &lt;function1&gt; &lt;title&gt;Some Title&lt;/title&gt; &lt;type&gt;25&lt;/type&gt; &lt;/function1&gt; &lt;function2 /&gt; &lt;function3&gt; &lt;param&gt;13&lt;/param&gt; &lt;/function3&gt; &lt;/domains&gt; &lt;/WebMethod&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre> <p>Will this work or should we do a different way?</p>
<p>I would pass in an xml document instead of doing concreate functions for this. </p> <p>The webservice in your example is leaky - the consumer needs to know too much about this interface and the implementation of the webservice internally. </p> <p>XML Document and then tie that with an XSD. That way you can prevalidte the input to the webservice. </p> <p>Take a look at these</p> <p><a href="http://www.ibm.com/developerworks/webservices/library/ws-docstyle.html" rel="nofollow noreferrer">IBM Developer</a> <a href="http://forums.asp.net/p/1253455/2323689.aspx#2323689" rel="nofollow noreferrer">ASP.NET Forum</a></p> <p>I would also recommend using this for testing webservices and its free <a href="http://www.codeplex.com/wsstudioexpress" rel="nofollow noreferrer">WSStudio</a></p>
<p>You can simply pass a variable-length array as a parameter.</p>
5,431
<p>In the following code doesn't work as </p> <pre><code>public void Foo() { CompanyDataContext db = new CompanyDataContext(); Client client = (select c from db.Clients ....).Single(); Bar(client); } public void Bar(Client client) { CompanyDataContext db = new CompanyDataContext(); db.Client.Attach(client); client.SomeValue = "foo"; db.SubmitChanges(); } </code></pre> <p>This doens't work, I get error msg. "An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported."</p> <p>How do you work with DataContexts throughout an application so you don't need to pass around a reference? </p> <p>What</p>
<p>They really mean it with 'This is not supported.'. Attaching to an object fetched from another data context is not implemented. </p> <p>There are a number of workarounds to the problem, the recommended way is by serializing objects, however this is not easy nor a clean approach.</p> <p>The most simple approach I found is to use a readonly DataContext for fetching objects like this:</p> <pre><code> MyDataContext dataContext = new MyDataContext() { DeferredLoadingEnabled = false, ObjectTrackingEnabled = false }; </code></pre> <p>The objects obtained from this context can be attached to another context but only applies to some scenarios.</p>
<p>I've created data access classes that encapsulate all the communication with Linq2Sql. These classes have their own datacontext that they use on their objects.</p> <pre><code>public class ClientDataLogic { private DataContext _db = new DataContext(); public Client GetClient(int id) { return _db.Clients.SingleOrDefault(c =&gt; c.Id == id); } public void SaveClient(Client c) { if (ChangeSetOnlyIncludesClient(c)) _db.SubmitChanges(); } } </code></pre> <p>Ofcourse you will need to keep this object instantiated as long as you need the objects. </p> <p>Checking if only the rigth object has been changed is altso somewhat bothersom, you could make methods like</p> <pre><code>void ChangeClientValue(int clientId, int value); </code></pre> <p>but that can become a lot of code.</p> <p>Attaching and detaching is a somewhat missing feature from Linq2Sql, if you need to use that a lot, you sould probably use Linq2Entities.</p>
49,891
<p>How do you unit test a <code>HttpModule</code> in asp.net given that <code>HttpApplication</code> and <code>HttpContext</code> do no implement an interface ?</p>
<p>In the past before moving to ASP.NET MVC, I used <a href="http://haacked.com/archive/2007/09/09/ihttpcontext-and-other-interfaces-for-your-duck-typing-benefit.aspx" rel="nofollow noreferrer">this library</a> Phil Haack created for Unit Testing anything that used the HttpApplication and HttpContext. It in turned used a <a href="http://www.deftflux.net/blog/page/Duck-Typing-Project.aspx" rel="nofollow noreferrer">Duck Typing library</a>.</p> <p>Unfortunately, this was the best way to do it. ASP.NET was not made to be easily testable. When they worked on ASP.NET MVC, one of the goals is to get rid of these headaches by making the framework more testable.</p>
<p>You can use an Isolation (mocking) framework. I know of two tools that enable you to fake/mock any .NET objects - <a href="http://www.typemock.com/typemock-isolator-product3" rel="nofollow">Typemock Isolator</a> and <a href="http://www.telerik.com/products/mocking.aspx" rel="nofollow">Telerik JustMock</a> i think that you can also use <a href="http://social.msdn.microsoft.com/Forums/en/pex/thread/d73f730b-37df-40f9-8c62-afb76993fbbe" rel="nofollow">Moles</a>.</p> <p>All of the above will enable you to fake any .NET object event if it does not implement an interface or even have a public c'tor.</p>
4,488
<p>Does anyone know what this means. Getting this in C# winforms applications:</p> <blockquote> <p>Not a legal OleAut date</p> </blockquote>
<p>It means that somewhere in the program is attempting to convert to or from an OLE Automation Date outside the valid range 1-January-4713 BC to 31-December-9999 AD. It might have slipped through because OLE Automation Dates are represented as a <strong>double</strong>.</p> <p>Start by looking for any uses of the methods:</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.datetime.fromoadate.aspx" rel="noreferrer">DateTime.FromOADate</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/system.datetime.tooadate.aspx" rel="noreferrer">DateTime.ToOADate</a></p>
<p>Others have struggled with this. I suggest looking at these threads on <a href="http://www.dotnetnuke.com/Community/ForumsDotNetNuke/tabid/795/forumid/8/threadid/64010/scope/posts/Default.aspx" rel="nofollow noreferrer">DotNetNuke</a> and <a href="http://forums.devshed.com/net-development-87/not-a-legal-oleaut-date-error-337459.html" rel="nofollow noreferrer">DevShed</a>.</p>
40,037
<p>My class is implementing a super-class method which which returns <code>List&lt;JComponent&gt;</code>. The list being returned is read-only:</p> <pre><code>public abstract class SuperClass { public abstract List&lt;JComponent&gt; getComponents(); } </code></pre> <p>In my class, I want to return a field which is declared as List - i.e. a sub-list:</p> <pre><code>public class SubClass extends SuperClass { private List&lt;JButton&gt; buttons; public List&lt;JComponent&gt; getComponents() { return buttons; } } </code></pre> <p>This generates a compiler error, as <code>List&lt;JButton&gt;</code> is not a subtype of <code>List&lt;JComponent&gt;</code>.</p> <p>I can understand why it doesn't compile, as it shouldn't be allowed to add a JTextField to a List of JButtons.</p> <p>However, as the list is read-only, then "conceptually" this should be allowed. But, of course, the compiler doesn't know that it is read-only.</p> <p>Is there any way to achieve what I want to achieve, without changing the method declaration in the super-class, and the field declaration in the sub-class?</p> <p>Thanks, Calum</p>
<p>Declare <code>getComponents()</code> as:</p> <pre><code>public List&lt;? extends JComponent&gt; getComponents() </code></pre>
<p>You could do the cast with <code>@SuppressWarnings</code>. I believe that would be appropriate in this case, just make sure you document why in a comment.</p> <p>Alternately, do the following:</p> <pre><code>public List&lt;JComponent&gt; getComponents() { return new ArrayList&lt;JComponent&gt;( buttons ); } </code></pre> <p>Yes I know this makes a copy and the list is already read-only. But until the profiler tells you otherwise, I would assume the penalty is small.</p> <p>@Calum: I agree that using ?-expressions in return types is bad form because calling code is unable to do this for example:</p> <pre><code>List&lt;JComponent&gt; list = obj.getComponents(); </code></pre>
27,618
<p>I have a linux box with a bank of modems and need to create demand-dial (outbound) PPP connections to a very large set of remote machines. Since I have far more remotes than local modems, I'd like to launch one or more instances of <code>pppd</code> in <code>demand</code> mode, but not allocate a particular modem until a connection is requested. When the connection becomes idle, I'd like <code>pppd</code> to release the modem so it can be used for a connection to a different remote.</p> <p>I've been through the <code>pppd man</code> pages and understand the concepts of the <code>call</code> and <code>connect</code> options, as well as the <code>options.DEVICE</code> files and the <code>/etc/ppp/peers</code> directory. Lock files will tell me which modems are in use or available. And I'm able to connect to multiple remote peers as long as I hard-code the modem assignments. But I haven't found a way to assign them dynamically, say by calling a <code>get_available_modem</code> script when <code>pppd</code> needs to dial. Google doesn't seem to know, either.</p> <p>A work-around might be to detect the need to demand-dial with an external mechanism, and then launch <code>pppd</code> to service it, but it seems cleaner to leverage the facility within <code>pppd</code> itself.</p> <p>Any pointers or ideas are appreciated. Thanks for your thoughts!</p>
<p>This is the solution I'm going with:</p> <ul> <li>Enumerate the modems as <code>/dev/modem0</code>, <code>/dev/modem1</code>, ...</li> <li>Start an instance of <code>pppd</code> in demand-dial mode for each peer, but instead of a "real" modem, attach it to <code>/dev/modem.</code><em>peer</em>, which the "ppp-on-dialer" script soft-links to the first available modem dynamically.</li> <li>When the connection times out and the modem goes offline, soft link <code>/dev/modem.</code><em>peer</em> to <code>/dev/null</code> so the modem can be re-used for a connection to a different peer.</li> </ul> <p>Thanks for your comments!</p>
<p>Does it have to be directly driven by the Linux box, or could you use something like the old Lucent Portmaster boxen?</p>
39,492
<p>I remember hearing Joel say he has 2 different locations where the servers are located, each location has 2 front end servers and 1 back end server.</p> <ol> <li><p>If a one of the hosting facilities goes down, how can he switch over to the other one? (Or is it just going to be a DNS change that will take 24-72 hours to propagate?).</p></li> <li><p>How can a single SQL Server instance have so many databases on it? FB has a completely separate database per account. I can't see a single SQL Server instance having more than say 200-250 databases on it! And I'm sure they have more customers than that.</p></li> </ol>
<p>They talked about this in one of the Stack Overflow podcasts, but I can't find it in the transcripts.</p> <p>1) Each of the two centers handles approximately 1/2 of the users. Fairly often (hourly, I think Joel said) they ship transaction logs to the other site. If site A goes down, they bring up the db backups on site B, and do the DNS switchover. It won't be instantaneous or automated, nor do they want it to be, because they'll be coming up with slightly stale data, and want to avoid that if it's at all possible to bring the broken site back up.</p> <p>I'm not sure how they handle the DNS situation, but you can set the TTL on DNS records to mere seconds to limit caching, and have failover occur very quickly.</p> <p>2) Why not? I'm not sure of the hard limit of databases per instance, but there's also nothing keeping you from running multiple instances of SQL Server on your box. I would imagine you're more limited by hardware than software. (You can also run Fogbugz with a MySQL database backend).</p>
<p>Got a few questions in here so I'll break these out:</p> <p><strong>If a one of the hosting facilities goes down, how can he switch over to the other one?</strong></p> <p>There's several ways to do this, including database mirroring (new in SQL Server 2005), log shipping, and replication. I've recorded a <a href="http://sqlserverpedia.com/wiki/Log_Shipping" rel="nofollow noreferrer">podcast on SQL Server high availability and disaster recovery options</a> at SQLServerPedia.</p> <p><strong>(Or is it just going to be a DNS change that will take 24-72 hours to propagate?)</strong></p> <p>Like the other post mentioned, you can set your DNS time-to-live numbers very slow, but the cooler method uses database mirroring. With mirroring, you can set both the primary and secondary server names in your connection string, and your application will automatically try the second server when the first one doesn't respond.</p> <p><strong>How can a single SQL Server instance have so many databases on it? FB has a completely separate database per account. I can't see a single SQL Server instance having more than say 200-250 databases on it! And I'm sure they have more customers than that.</strong></p> <p>The largest SQL Server I've worked with had over a thousand databases, and I've talked to a couple of other DBAs who have worked on systems with more than 2,000 databases on a server. It certainly makes management much more challenging, that's for sure.</p>
30,129
<p>This may not be possible, but I figured I'd ask...</p> <p>Is there any way anyone can think of to track whether or not an automatic variable has been deleted without modifying the class of the variable itself? For example, consider this code:</p> <pre><code>const char* pStringBuffer; { std::string sString( "foo" ); pStringBuffer = sString.c_str(); } </code></pre> <p>Obviously, after the block, pStringBuffer is a dangling pointer which may or may not be valid. What I would like is a way to have a wrapper class which contains pStringBuffer (with a casting operator for const char*), but asserts that the variable it's referencing is still valid. By changing the type of the referenced variable I can certainly do it (boost shared_ptr/weak_ptr, for example), but I would like to be able to do it without imposing restrictions on the referenced type.</p> <p>Some thoughts:</p> <ul> <li>I'll probably need to change the assignment syntax to include the referenced variable (which is fine)</li> <li>I might be able to look at the stack pointer to detect if my wrapper class was allocated "later" than the referenced class, but this seems hacky and not standard (C++ doesn't define stack behavior). It could work, though.</li> </ul> <p>Thoughts / brilliant solutions?</p>
<p>In general, it's simply not possible from within C++ as pointers are too 'raw'. Also, looking to see if you were allocated later than the referenced class wouldn't work, because if you change the string, then the c_str pointer may well change.</p> <p>In this particular case, you could check to see if the string is still returning the same value for c_str. If it is, you are probably still valid and if it isn't then you have an invalid pointer.</p> <p>As a debugging tool, I would advise using an advanced memory tracking system, like valgrind (available only for linux I'm afraid. Similar programs exist for windows but I believe they all cost money. This program is the only reason I have linux installed on my mac). At the cost of much slower execution of your program, valgrind detects if you ever read from an invalid pointer. While it isn't perfect, I've found it detects many bugs, in particular ones of this type.</p>
<p>One technique you may find useful is to replace the <code>new</code>/<code>delete</code> operators with your own implementations which mark the memory pages used (allocated by your <code>operator new</code>) as non-accessible when released (deallocated by your <code>operator delete</code>). You will need to ensure that the memory pages are never re-used however so there will be limitations regarding run-time length due to memory exhaustion.</p> <p>If your application accesses memory pages once they've been deallocated, as in your example above, the OS will trap the attempted access and raise an error. It's not exactly tracking per se as the application will be halted immediately but it does provide feedback :-)</p> <p>This technique is applicable in narrow scenarios and won't catch all types of memory abuses but it can be useful. Hope that helps.</p>
25,839
<p>I have the following XAML code:</p> <pre><code>&lt;Window x:Class="RichText_Wrapping.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1"&gt; &lt;Grid&gt; &lt;RichTextBox Height="100" Margin="2" Name="richTextBox1"&gt; &lt;FlowDocument&gt; &lt;Paragraph&gt; This is a RichTextBox - if you don't specify a width, the text appears in a single column &lt;/Paragraph&gt; &lt;/FlowDocument&gt; &lt;/RichTextBox&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>... If you create this window in XAML, you can see that when you don't specify a width for the window, it wraps the text in a single column, one letter at a time. Is there something I'm missing? If it's a known deficiency in the control, is there any workaround?</p>
<p>This is a confirmed bug with the WPF RichTextBox. To fix it, Bind the PageWidth of the FlowDocument to the RichTextBox width, i.e.</p> <pre><code>&lt;RichTextBox Name="rtb"&gt; &lt;FlowDocument Name="rtbFlowDoc" PageWidth="{Binding ElementName=rtb, Path=ActualWidth}" /&gt; &lt;/RichTextBox&gt; </code></pre> <hr> <p>EDIT: Give the FlowDocument a name so that you can access it in the code behind and never new the flow document in codebehind.</p>
<p>I copy pasted your code and its not in a single column, Do you have a width somewhere that is small? Maybe defined on the code behind for instance.</p>
45,673
<p>What is the best way to use PyGame (SDL) within a PyGTK application?</p> <p>I'm searching for a method that allows me to have a drawing area in the GTK window and at the same time being able to manage both GTK and SDL events.</p>
<p>I've never attempted it myself, but hearing plenty about other people who've tried, it's not a road you want to go down.</p> <p>There is the alternative of putting the gui in pygame itself. There are plenty of gui toolkits built specifically for pygame that you could use. Most of them are rather unfinished, but there are 2 big, actively maintained ones: <a href="http://www.pygame.org/project/108/" rel="nofollow noreferrer">PGU</a> and <a href="http://www.pygame.org/project/125/" rel="nofollow noreferrer">OcempGUI</a>. The full list on the pygame site is <a href="http://www.pygame.org/tags/gui" rel="nofollow noreferrer">here</a>.</p>
<p>I tried doing this myself a while ago, and I never got it to work perfectly. Actually I never got it to work at all under Windows, as it kept crashing the entire OS and I ran out of patience. I continued to use it though as it was only important it ran on Linux, and was only a small project. I'd strongly recommend you investigate alternatives. It always felt like a nasty hack, and made me feel dirty.</p>
4,527
<p>Using .Net (C#), how can you work with USB devices? </p> <p>How can you detect USB events (connections/disconnections) and how do you communicate with devices (read/write).</p> <p>Is there a native .Net solution to do this?</p>
<p>There is no <em>native</em> (e.g., System libraries) solution for this. That's the reason why <a href="http://www.icsharpcode.net/OpenSource/SharpUSBLib/" rel="nofollow noreferrer">SharpUSBLib</a> exists as mentioned by <a href="https://stackoverflow.com/questions/68749/working-with-usb-devices-in-net#68777">moobaa</a>.</p> <p>If you wish to roll your own handler for USB devices, you can check out the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport" rel="nofollow noreferrer">SerialPort class of System.IO.Ports</a>.</p>
<p>Most USB chipsets come with drivers. <a href="https://www.silabs.com/products/mcu/usb/Pages/default.aspx" rel="nofollow noreferrer">Silicon Labs</a> has one.</p>
9,429
<p>I noticed that writing to a file, closing it and moving it to destination place randomly fails on Vista. Specifically, MoveFileEx() would return <code>ERROR_ACCESS_DENIED</code> for no apparent reason. This happens on Vista SP1 at least (32 bit). Does not happen on XP SP3.</p> <p>Found <a href="http://groups.google.com/group/microsoft.public.windows.file_system/browse_thread/thread/e9774e86e98eb623/3348d92b8ba5858d?lnk=raot&amp;pli=1" rel="nofollow noreferrer">this thread</a> on the internets about exactly the same problem, with no real solutions. So far it looks like the error is caused by Vista's search indexer, see below.</p> <p>The code example given there is enough to reproduce the problem. I'm pasting it here as well:</p> <pre><code>#include &lt;windows.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; bool test() { unsigned char buf[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99 }; HANDLE h; DWORD nbytes; LPCTSTR fn_tmp = "aaa"; LPCTSTR fn = "bbb"; h = CreateFile(fn_tmp, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_ALWAYS, 0, 0); if (h == INVALID_HANDLE_VALUE) return 0; if (!WriteFile(h, buf, sizeof buf, &amp;nbytes, 0)) goto error; if (!FlushFileBuffers(h)) goto error; if (!CloseHandle(h)) goto error; if (!MoveFileEx(fn_tmp, fn, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)) { printf("error=%d\n", GetLastError()); return 0; } return 1; error: CloseHandle(h); return 0; } int main(int argc, char** argv) { unsigned int i; for (i = 0;; ++i) { printf("*%u\n", i); if (!test()) return 1; } return 0; } </code></pre> <p>Build this as console app with Visual Studio. Correct behaviour would be infinite loop that prints test numbers. On Vista SP1, the program exits after random number of iterations (usually before 100 iterations are made).</p> <p>This does not happen on Windows XP SP2. There's no antivirus running at all; and no other strange background processes (machine is pretty much vanilla OS install + Visual Studio).</p> <p><strong>Edit</strong>: Digging further via Process Monitor (thanks @sixlettervariables), I can't see anything particularly bad. Each test iteration results in 176 disk operations, majority of them coming from SearchProtocolHost.exe (search indexer). If search indexing service is stopped, no errors occur, so it looks like it's the culprit.</p> <p>At the time of failure (when the app gets <code>ERROR_ACCESS_DENIED</code>), SearchProtocolHost.exe has two CreateFile(s) to the detination file (bbb) open with read/write/delete share modes, so it should be ok. One of the opens is followed by opportunistic lock (<code>FSCTL_REQUEST_FILTER_OPLOCK</code>), maybe that's the cause?</p> <p>Anyway, I found out that I can avoid the problem by setting <code>FILE_ATTRIBUTE_TEMPORARY</code> and <code>FILE_ATTRIBUTE_NOT_CONTENT_INDEXED</code> flags on the file. It looks like <code>FILE_ATTRIBUTE_NOT_CONTENT_INDEXED</code> is enough by itself, but marking file as temporary also dramatically cuts down disk operations caused by search indexer.</p> <p>But this is <strong>not a real solution</strong>. I mean, if an application can't expect to be able to create a file and rename it because some Vista's search indexer is messing with it, <strong>it's totally crazy</strong>! Should it keep retrying? Yell at the user (which is very undesirable)? Do something else?</p>
<p>I suggest you use <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow noreferrer">Process Monitor</a> <em>(edit: the artist formerly known as FileMon)</em> to watch and see which application exactly is getting in the way. It can show you the entire trace of file system calls made on your machine.</p> <p><em>(edit: thanks to @moocha for the change in application)</em></p>
<p>That usually means something else has an open handle on the file in question, maybe an active virus scanner running? Have you tried running something like Process Monitor from the <a href="http://technet.microsoft.com/en-us/sysinternals/default.aspx" rel="nofollow noreferrer">Sysinternals</a> site? You should be to filter all file operations and get a better picture of whats going on underneath the hood.</p>
18,494
<p>I'm personally an advocate of the <a href="https://en.wikipedia.org/wiki/%3F:" rel="nofollow noreferrer">ternary operator</a>: <code>() ? : </code></p> <p>I do realize that it has its place, but I have come across many programmers that are completely against ever using it, and some that use it too often.</p> <p>What are your feelings on it? What interesting code have you seen using it?</p>
<p>Use it for <strong>simple expressions only</strong>:</p> <pre><code>int a = (b &gt; 10) ? c : d; </code></pre> <p><strong>Don't chain or nest</strong> ternary operators as it hard to read and confusing:</p> <pre><code>int a = b &gt; 10 ? c &lt; 20 ? 50 : 80 : e == 2 ? 4 : 8; </code></pre> <p>Moreover, when using ternary operator, consider formatting the code in a way that improves readability:</p> <pre><code>int a = (b &gt; 10) ? some_value : another_value; </code></pre>
<p>I'm a big fan of it ... when appropriate.</p> <p>Stuff like this is great, and, personally, I don't find it too hard to read/understand:</p> <pre><code>$y = ($x == &quot;a&quot; ? &quot;apple&quot; : ($x == &quot;b&quot; ? &quot;banana&quot; : ($x == &quot;c&quot; ? &quot;carrot&quot; : &quot;default&quot;))); </code></pre> <p>I know that probably makes a lot of people cringe, though.</p> <p>One thing to keep in mind when using it in PHP is how it works with a function that returns a reference.</p> <pre><code>class Foo { var $bar; function Foo() { $this-&gt;bar = &quot;original value&quot;; } function &amp;tern() { return true ? $this-&gt;bar : false; } function &amp;notTern() { if (true) return $this-&gt;bar; else return false; } } $f = new Foo(); $b =&amp; $f-&gt;notTern(); $b = &quot;changed&quot;; echo $f-&gt;bar; // &quot;changed&quot; $f2 = new Foo(); $b2 =&amp; $f-&gt;tern(); $b2 = &quot;changed&quot;; echo $f2-&gt;bar; // &quot;original value&quot; </code></pre>
19,376
<p>We use a modified version of the IE engine (the COM version in a C# wrapper) to display a lot of the formatted content in our application. The problem, however, is you don't have a lot of control of any printout of such documents. For example, you can't force a color printout without accessing the registry or directing the user to their Internet Explorer options. So, we've been investigating the new WPF WebBrowser control, which might better suit our purposes.</p> <p>The problem is (other than Microsoft called it the same name as the Windows Forms version of the control making Google searches less useful than I like) I can't seem to find any good guidelines on how to print the contents of the control. The Document returned from the object isn't paginated, making it hard to use with the PrintDialog. Similar, sending the Visual to PrintDialog doesn't seem like a good idea. Sizing the control properly in this context seems dubious, particularly when you consider paging. </p> <p>There has to be some good documentation on this somewhere. Can someone direct me to it or provide a good suggestion on how to do this?</p>
<p>mshtml.IHTMLDocument2 doc = webBrowser.Document as mshtml.IHTMLDocument2; doc.execCommand("Print", true, null);</p>
<p>I'm pretty sure the WPF WebBrowser control is just the ActiveX control wrapped up nicely for use in WPF. (The class derives from <code>ActiveXHost</code>).</p>
45,083
<p>I decided to learn <a href="http://en.wikipedia.org/wiki/C++" rel="nofollow noreferrer">C++</a> (I program in <a href="http://en.wikipedia.org/wiki/C_%28programming_language%29" rel="nofollow noreferrer">C</a> at work), and I have been reading some tutorials (and lots of posts here on Stack&nbsp;Overflow). OK, so I typed in the standard C++ "hello word", compiled with <a href="http://en.wikipedia.org/wiki/GNU_Compiler_Collection" rel="nofollow noreferrer">GCC</a> on my <a href="http://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29" rel="nofollow noreferrer">Ubuntu</a> machine as "test".</p> <p>Then I tried to run it by typing "test" and hitting enter. Nothing. It turns out I must run it with "./test". OK, fine, I'll do that from now on. But why? The "./" just says that what I should run is in the current directory... Is the current directory not always part of the PATH when the <a href="http://en.wikipedia.org/wiki/Operating_system" rel="nofollow noreferrer">OS</a> is searching for something to run? Can I make it so? </p>
<p>Yes, the current directory is not part of your PATH. You don't want it to be, because then you could be in a directory that had a malicious program you didn't know about that you run.</p> <p>What if you were used to running /usr/bin/grep, but you happened to be in a directory that a Bad Person put a malicious copy of grep in, and this time you run grep, and you're running grep out of the current directory, rather than /usr/bin/grep.</p> <p>You certainly can add ./ to your PATH in your ~/.profile or ~/.bash_profile, but I don't recommend it.</p> <p>And if it makes you feel any better, I had the same frustration 15 years ago when I started using Unix-like systems.</p>
<p>Not having '.' (the current directory) in the PATH is a minor security measure. You could always add it in if you'd like, though it's not a best practice. </p>
32,946
<p>Is there a way to assign a process to a core (or more than one core) on a multi-core system running Windows XP?</p> <p>An answer using a GUI is acceptable.</p>
<p>You can set a process's affinity using task manager. Right click on the process in the "Processes" tab, and select "Set Affinity...". The, uncheck all the processors you don't want it to run on.</p>
<p>Sure thing. Open the Windows Task manager, right click on the process, and select "set affinity".</p>
22,890
<p>I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.</p> <p>Does anyone have a preferred way to do Python code folding in Vim? I.e, </p> <ul> <li>Do you have a particular Vim plugin that you use and like?</li> <li>Do you use manual folding or do you place markers in comments?</li> <li>Any other recommended ways to do code folding for Python in Vim?</li> </ul>
<p>Personally I can't convince myself to litter my code with the markers. I've become pretty used to (and efficient) at using indent-folding. Together with my mapping of space bar (see below) to open/close folds and the zR and zM commands, I'm right at home. Perfect for Python!</p> <pre><code>set foldmethod=indent nnoremap &lt;space&gt; za vnoremap &lt;space&gt; zf </code></pre>
<p>Based on <a href="https://stackoverflow.com/a/21112061/10247460">the answer by @Genma</a> I glued together the following syntax rules which just need to be added as <code>.vim/after/syntax/python.vim</code></p> <pre><code>syn keyword pythonStatement class def syn match pythonFunction &quot;\h\w*&quot; containedin=pythonFold syn region pythonFold fold transparent \ start = &quot;\(^\z(\s*\)\v%(def|class|if|elif|else|for|while|try|except|finally|with)&gt;)@&lt;=&quot; \ end = &quot;\v\ze%(\s*\n)+%(\z1\s)@!.&quot; syn region pythonCurlyBrace start=&quot;{&quot; end=&quot;}&quot; fold transparent syn region pythonSquareBrace start=&quot;\[&quot; end=&quot;\]&quot; fold transparent </code></pre>
46,654