instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown?</p> <p>See the example below:</p> <pre><code> try { // code that may or may not throw an exception } finally { SomeCleanupFunctionThatThrows(); // if currently executing an exception, exit the program, // otherwise just let the exception thrown by the function // above propagate } </code></pre> <p>or is ignoring one of the exceptions the only thing you can do?</p> <p>In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.</p>
<p>Set a flag variable, then check for it in the finally clause, like so:</p> <pre><code>boolean exceptionThrown = true; try { mightThrowAnException(); exceptionThrown = false; } finally { if (exceptionThrown) { // Whatever you want to do } } </code></pre>
<p>No I do not believe so. The catch block will run to completion before the finally block.</p> <pre><code>try { // code that may or may not throw an exception } catch { // catch block must exist. finally { SomeCleanupFunctionThatThrows(); // this portion is ran after catch block finishes } </code></pre> <p>Otherwise you can add a synchronize() object that the exception code will use, that you can check in the finally block, which would help you identify if in a seperate thread you are running an exception.</p>
9,215
<p>I have written a simple PowerShell filter that pushes the current object down the pipeline if its date is between the specified begin and end date. The objects coming down the pipeline are always in ascending date order so as soon as the date exceeds the specified end date I know my work is done and I would like to let tell the pipeline that the upstream commands can abandon their work so that the pipeline can finish its work. I am reading some very large log files and I will frequently want to examine just a portion of the log. I am pretty sure this is not possible but I wanted to ask to be sure.</p>
<p>It is possible to break a pipeline with anything that would otherwise break an outside loop or halt script execution altogether (like throwing an exception). The solution then is to wrap the pipeline in a loop that you can break if you need to stop the pipeline. For example, the below code will return the first item from the pipeline and then break the pipeline by breaking the outside do-while loop:</p> <pre><code>do { Get-ChildItem|% { $_;break } } while ($false) </code></pre> <p>This functionality can be wrapped into a function like this, where the last line accomplishes the same thing as above:</p> <pre><code>function Breakable-Pipeline([ScriptBlock]$ScriptBlock) { do { . $ScriptBlock } while ($false) } Breakable-Pipeline { Get-ChildItem|% { $_;break } } </code></pre>
<p>Another option would be to use the <code>-file</code> parameter on a <code>switch</code> statement. Using <code>-file</code> will read the file one line at a time, and you can use <code>break</code> to exit immediately without reading the rest of the file.</p> <pre class="lang-powershell prettyprint-override"><code>switch -file $someFile { # Parse current line for later matches. { $script:line = [DateTime]$_ } { } # If less than min date, keep looking. { $line -lt $minDate } { Write-Host "skipping: $line"; continue } # If greater than max date, stop checking. { $line -gt $maxDate } { Write-Host "stopping: $line"; break } # Otherwise, date is between min and max. default { Write-Host "match: $line" } } </code></pre>
35,174
<p>How can I use .NET DataSet.Select method to search records that match a DateTime? What format should I use to enter my dates in?</p>
<p>The best method is dd MMM yyyy (ie 15 Sep 2008). This means there is no possiblity of getting it wrong for different Locals.</p> <pre><code>ds.select(DBDate = '15 Sep 2008') </code></pre> <p>You can use the DateFormat function to convert to long date format as well and this will work fine too.</p>
<p>I use the following for the SQL Select:</p> <pre><code> public string BuildSQL() { // Format: CAST('2000-05-08 12:35:29' AS datetime) StringBuilder sb = new StringBuilder("CAST('"); sb.Append(_dateTime.ToString("yyyy-MM-dd HH:mm:ss")); sb.Append("' AS datetime)"); return sb.ToString(); } </code></pre>
9,322
<p>I have a lot of buttons and by clicking on different button, different image and text would appear. I can achieve what I want, but the code is just so long and it seems very repetitive. For example:</p> <pre><code> var aaClick = false; $("aa").observe('click', function() { unclick(); $('characterPic').writeAttribute('src',"aa.jpg"); $('characterBio').update("aatext"); $('aa').setStyle({ color: '#FFFFFF' }); aaClick = true; }); $("aa").observe('mouseover', function() { if (!aaClick) $('aa').setStyle({ color: '#FFFFFF' }); }); $("aa").observe('mouseout', function() { if (!aaClick) $('aa').setStyle({ color: '#666666' }); }); function unclick() { aaClick = false; $('aa').setStyle({ color: '#666666' }); } </code></pre> <p>same thing with bb, cc, etc. and every time I add a new button, I need to add it to unclick function as well. This is pretty annoying and I tried to google it, and I only found observe click on all listed items, so I still couldn't figure out since what I want involves button up when other buttons are clicked. </p> <p>Is there any way to just have a generic function that takes different id but do the exact same thing? Because from what I can see, if I can just replace aa with other id, I can reduce a lot of code. Thanks!!!</p>
<p>Build it all into a function where you can simply pass it the names of the DIVs you want to register. As long are you are consistent with your .jpg names, it should work.</p> <pre><code>var clicks = [] function regEvents(divName) { $(divName).observe('click', function() { unclick(divName); $('characterPic').writeAttribute('src',divName+".jpg"); $('characterBio').update(divName"text"); $(divName).setStyle({ color: '#FFFFFF' }); clicks[divName] = true }); $(divName).observe('mouseover', function() { if (!clicks[divName]) $(divName).setStyle({ color: '#FFFFFF' }); }); $(divName).observe('mouseout', function() { if (!clicks[divName]) $(divName).setStyle({ color: '#666666' }); }); } function unclick(divName) { clicks[divName] = false; $(clicks[divName]).setStyle({ color: '#666666' }); } </code></pre>
<p>Do the buttons share a common container? Then the following code works:</p> <pre><code>$(container).childElements().each(function(element) { $(element).observe('click', function () { … }); … }); </code></pre> <p>Alternatively, you can also do this:</p> <pre><code>["aa", "bb", "cc"].each(function(element) { … same code … }); </code></pre>
33,411
<p>I thought I could easily answer this question by searching the web, but my Google-fu has failed me. So I turn to you, oh mighty stackoverflowers, and beseech you for enlightenment:</p> <p><strong>What is the quickest and best way to generate a visual site map (e.g. flowchart, mind map, IA diagram) of an existing website?</strong></p> <p>Additional context: my client has been asked by <em>their</em> client to redesign their website. The art directors understandably asked for information on the current site architecture, to which the client had nothing(!). So they have asked me to automagically produce a visual site map by somehow crawling the client's site.</p> <p>I have found various free/shareware apps that do this, but have been unable to find reviews or best practices. I'd prefer to make a robust recommendation rather than grab the first shareware app that seems to do the trick. So, how would you recommend generating a visual site map?</p> <p>Much appreciated!</p>
<p>It's not free, but Visio has a web site map diagram type that will go spider a site and generate a nice pretty diagram of the results.</p>
<p>In order to visualize site map as a flowchart, you can use Site Visualizer software. It has 30-days full-featured trial period, so you can create visual map of any existing website absolutely for free.</p> <p>After installation, create new project, type website URL you need to crawl, then lick Start tool button. After the crawling will be done, click Draw button on the <a href="http://site-visualizer.com/visual-sitemap" rel="nofollow noreferrer" title="Site Flowchart">Visual Sitemap</a> tab. When the visualization will be drawn, you can highlight links of any page by clicking on its rectangle. Outboind links with rel="nofollow" attribute draws with dotted line:</p> <p><img src="https://i.stack.imgur.com/w7ddt.png" alt="visual sitemap"> Click on Save button in order to save the visual sitemap to an image file: PNG, JPG, BMP, etc. More info you can find at the <a href="http://site-visualizer.com/help/quick-start-guide" rel="nofollow noreferrer" title="quick start guide">Quick Start Guide</a>.</p>
41,175
<p>I've recently gotten my hobby java project embedded into a page <a href="https://stackoverflow.com/questions/138157/java-console-like-web-applet">thanks to this very site</a>, but now I'm having some security issues.</p> <p>I have the include:</p> <pre><code>import java.sql.*; </code></pre> <p>and the line:</p> <pre><code>Class.forName("com.mysql.jdbc.Driver").newInstance(); </code></pre> <p>as well as a mysql .jar file in my src directory, it works from the console, and in the applet works fine from the applet - up until that forName() line in my code, where it throws the exception:</p> <pre> Exception: com.mysql.jdbc.Driverjava.lang.ClassNotFoundException: com.mysql.jdbc.Driver java.security.AccessControlException: access denied (java.lang.RuntimePermission exitVM.-1) at java.security.AccessControlContext.checkPermission(Unknown Source) at java.security.AccessController.checkPermission(Unknown Source) at java.lang.SecurityManager.checkPermission(Unknown Source) at java.lang.SecurityManager.checkExit(Unknown Source) at java.lang.Runtime.exit(Unknown Source) at java.lang.System.exit(Unknown Source) at applet.Database.connectDB(Database.java:80) etc... </pre> <p>I think I may be able to fix it with a client.policy file, otherwise I might need to write an abstraction layer which uses a server-client network connection to query from the server-side...</p> <p>I'm sure the Java gurus here probably know the best way about it.</p>
<p>I think the security exception is actually from a System.exit() call in your applet, after the Class.forName(). Generally you are not allowed to call System.exit() in unsigned applets as it shuts the whole JVM down. Have you checked if line 80 is actually the Class.forName() line, or does line 80 have some kind of exception handler which tries to call System.exit() if the driver does not load?</p> <p>Anyway, in order to load the mysql jar file in your applet, you need to include it in an ARCHIVE attribute like this:</p> <pre><code>&lt;APPLET ARCHIVE="mysql.jar" CODEBASE="./src/" ... </code></pre> <p>Once you get past this stage, you will still need to host the mysql server at the same IP number/hostname as the webserver, and open it to all the same people who can access your applet. As Tony said, this isn't how people normally do it, for security reasons. Better to write something on the server side, if you have control of the app server, and use XML or some other data exchange method to get the data out to the applet. Of course if you are just experimenting to learn about applets, then it's probably fine - but do take care to keep mysql behind your firewall if possible.</p>
<p>Try getting rid of the <code>newInstance()</code> part. I think just having the <code>Class.forName()</code> does it for loading the driver.</p>
25,927
<p>I haven't really done any Windows scripting at all, so I am at a loss on how to pull this one off. Anyway, basically what we want to do is have a script that will take an argument on which IIS AppPool to recycle. I have done some research on Google and haven't had much success on getting things to work.</p> <p>Here is what I am trying now:</p> <pre><code>$appPoolName = $args[0] $appPool = get-wmiobject -namespace "root\MicrosoftIISv2" -class "IIsApplicationPools" Where-Object {$_.Name -eq "W3SVC/APPPOOLS/$appPoolName"} $appPool.Recycle() </code></pre> <p>and the error I get:</p> <pre><code>Get-WmiObject : A parameter cannot be found that matches parameter name '$_.Name -eq "W3SVC/APPPOOLS/$appPoolName"'. </code></pre> <p>Anyway, it would be nice if I also knew how to debug things like this. I already fixed one bug with the original script by doing gwmi -namespace "root\MicrosoftIISv2" -list. Any other tips like that one would be great.</p> <p>Thanks!</p> <p><strong>Update</strong>: Here is some more info</p> <pre><code>$appPool = gwmi -namespace "root\MicrosoftIISv2" -class "IISApplicationPools" | Get-Member . TypeName: System.Management.ManagementObject#root\MicrosoftIISv2\IIsApplicationPools Name MemberType Definition ---- ---------- ---------- Caption Property System.String Caption {get;set;} Description Property System.String Description {get;set;} InstallDate Property System.String InstallDate {get;set;} Name Property System.String Name {get;set;} Status Property System.String Status {get;set;} __CLASS Property System.String __CLASS {get;set;} __DERIVATION Property System.String[] __DERIVATION {get;set;} __DYNASTY Property System.String __DYNASTY {get;set;} __GENUS Property System.Int32 __GENUS {get;set;} __NAMESPACE Property System.String __NAMESPACE {get;set;} __PATH Property System.String __PATH {get;set;} __PROPERTY_COUNT Property System.Int32 __PROPERTY_COUNT {get;set;} __RELPATH Property System.String __RELPATH {get;set;} __SERVER Property System.String __SERVER {get;set;} __SUPERCLASS Property System.String __SUPERCLASS {get;set;} ConvertFromDateTime ScriptMethod System.Object ConvertFromDateTime(); ConvertToDateTime ScriptMethod System.Object ConvertToDateTime(); Delete ScriptMethod System.Object Delete(); GetType ScriptMethod System.Object GetType(); Put ScriptMethod System.Object Put(); gwmi -namespace "root\MicrosoftIISv2" -class "IISApplicationPools" __GENUS : 2 __CLASS : IIsApplicationPools __SUPERCLASS : CIM_LogicalElement __DYNASTY : CIM_ManagedSystemElement __RELPATH : IIsApplicationPools.Name="W3SVC/AppPools" __PROPERTY_COUNT : 5 __DERIVATION : {CIM_LogicalElement, CIM_ManagedSystemElement} __SERVER : IRON __NAMESPACE : root\MicrosoftIISv2 __PATH : \\IRON\root\MicrosoftIISv2:IIsApplicationPools.Name="W3SVC/A ppPools" Caption : Description : InstallDate : Name : W3SVC/AppPools Status : </code></pre>
<p><strong>Where-Object</strong> is a filter that expects something as in input. There seems to be a missing <strong>pipe</strong>, before the <em>where filter</em>. </p> <p>Try:</p> <pre><code>$appPoolName = $args[0] $appPool = get-wmiobject -namespace "root\MicrosoftIISv2" -class "IIsApplicationPool" | Where-Object {$_.Name -eq "W3SVC/APPPOOLS/$appPoolName"} $appPool.Recycle() </code></pre> <p><strong>Edit</strong>: I noticed that the WMI class was <em>IISApplicationPools</em>, which as you saw, did not show us the Recycle method when piped to <strong>Get-Member</strong>. This needs to be changed to <em>IISApplicationPool</em> (non-plural). With that change, you are able to use the Recycle method. The code above has been updated.</p>
<p>With IIS 8.0 I've found I had to use <code>-namespace root\webadministration -class ApplicationPool</code></p> <p>For example, to recycle an Application Pool in IIS 8 remotely using PowerShell:</p> <p>As always, please test this first by listing the application pools. Just remove the <code>| where</code> and the first <code>(</code> from the command:</p> <pre><code>gwmi -comp WebServer01 -namespace root\webadministration -class ApplicationPool #Recycle app pool by name. (gwmi -comp WebServer01 -namespace root\webadministration -class ApplicationPool | ` where {$_.Name -eq 'YourAppPool'}).recycle() </code></pre> <p>And on one line:</p> <pre><code>(gwmi -comp WebSserver01 -namespace root\webadministration -class ApplicationPool | where {$_.Name -eq 'YourAppPool'}).recycle() </code></pre>
24,202
<p>I'm building a PHP page with data sent from MySQL.</p> <p>Is it better to have</p> <ul> <li>1 <code>SELECT</code> query with 4 table joins, or</li> <li>4 small <code>SELECT</code> queries with no table join; I do select from an ID</li> </ul> <p>Which is faster and what is the pro/con of each method? I only need one row from each tables.</p>
<p>You should run a profiling tool if you're truly worried cause it depends on many things and it can vary but as a rule its better to have fewer queries being compiled and fewer round trips to the database.</p> <p>Make sure you filter things as well as you can using your where and join on clauses.</p> <p>But honestly, it usually doesn't matter since you're probably not going to be hit all that hard compared to what the database can do, so unless optimization is your spec you should not do it prematurely and do whats simplest.</p>
<p>Be careful when dealing with a merge table however. It has been my experience that although a single join can be good in most situations, when merge tables are involved you can run into strange situations.</p>
7,926
<p>Im having problems displaying records to my view when passing viewdata to a user control. This is only apparent for linq to sql objects where I am using table joins.</p> <p>The exception I receive is "Unable to cast object of type '&lt;>f__AnonymousType4<code>10[System.String,System.Int32,System.Nullable</code>1[System.DateTime],System.String,System.String,System.String,System.String,System.String,System.Nullable<code>1[System.Single],System.Nullable</code>1[System.Double]]' to type App.Models.table1."</p> <p>I have searched for a fix to this issue but not too familiar on whats wrong here for me to search for the right subject. This should be working in theory and this works for single table retrieving but when I added a join in their I ran into problems. I am currently using a foreach statement to query through my data via single table declaration. Any help would be greatly appreciated. Thanks in advance.</p> <p>My current setup is:</p> <p>CViewDataUC.cs(my class to hold viewdata and data connections specifically for user controls)</p> <pre><code>public void Info(ViewDataDictionary viewData, int id) { var dataContext = new testDataContext(); var info = from table1 in dataContext.table1 join table2 in dataContext.table2 on table1.type_id equals table2.type_id join table3 in dataContext.table3 on table1.id equals table3.id join table4 in dataContext.table4 on table1.id equals table4.id where table1.id == id select new { table1.column1, table1.column2, table1.column3, table1.column4, table1.column5, table1.column6, table1.column7, table2.column1, table3.column1, table4.column1 }; viewData["vd_Info"] = info; } </code></pre> <p>HomeController.cs(Controller)</p> <pre><code>public ActionResult Information(int id) { ViewData["Title"] = "Information"; CViewDataUC o_info = new CViewDataUC(); o_info.Info(this.ViewData, id); return View(); } </code></pre> <p>Information.aspx(View)</p> <pre><code>&lt;%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Info.aspx.cs" Inherits="App.Views.Info" %&gt; &lt;asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"&gt; &lt;%Html.RenderPartial("~/Views/UserControls/Info.ascx", ViewData["vd_Info"]);%&gt; &lt;/asp:Content&gt; </code></pre> <p>Info.ascx(User Control)</p> <pre><code>&lt;%foreach (table1 m in (IEnumerable)ViewData.Model) { %&gt; &lt;div class="left"&gt; &lt;br /&gt; &lt;br /&gt; &lt;p id="medium"&gt; Column 1 &lt;br /&gt; &lt;%= Html.TextBox("column1", m.column1, new {@class = "textBox", @readonly = "readonly" })%&gt; Column 1 &lt;br /&gt; &lt;%= Html.TextBox("column2", m.column2, new {@class = "textBox", @readonly = "readonly" })%&gt; &lt;br /&gt; Column 1 &lt;br /&gt; &lt;%= Html.TextBox("column3", m.column3, new {@class = "textBox", @readonly = "readonly" })%&gt; &lt;/p&gt; &lt;/div&gt; &lt;%}%&gt; </code></pre>
<pre><code>foreach (table1 m in (IEnumerable)ViewData.Model) </code></pre> <p><code>m</code> is not of type <code>table1</code>. It is an anonymous type (<code>select new { ... }</code> in CViewDataUC.cs).</p> <p>You should create a class that represents the type of the model objects you are passing from controller to view.</p>
<p>Thanks, this has helped me a lot!</p> <p>One small comment, you have to use angle brackets:</p> <pre><code>IQueryable&lt;CInformation&gt; info = from table1 in dataContext.table1 </code></pre>
35,228
<p>Can the glTF format be used for 3D printing?</p> <p>If not, is there any tool can convert it to another format such as STL, OBJ, STEP, and IGES? </p>
<p>As far as can be found it should be possible to convert glTF into STL (or OBJ).</p> <p>You could try to use an online converter to do this, e.g. <a href="http://www.greentoken.de/onlineconv/" rel="nofollow noreferrer">this one (greentoken)</a>; and <a href="http://assimp.sourceforge.net/main_features_formats.html" rel="nofollow noreferrer">this (assimp)</a> may be useful too. </p> <p>According to <a href="https://b2b.partcommunity.com/community/faq/view/211/95/105/0/how-to-convert-3d-models-between-file-formats-i-e-fbx-to-obj-o" rel="nofollow noreferrer">this</a> greentoken supports glTF as input and STL as output, but it is reported by @Trish that that does not work. Assimp could output STL files which then could be used by slicer programs to generate the specific G-code file to print the model on your printer.</p>
<p>No, <code>gltf</code> is not a format that slicers accept commonly, and indeed, it is not even intended to be reverseable in the 1.0 format version. This has changed a little for the 2.0 standard. Some programs that allow exporting into the sliceable <code>stl</code> and <code>obj</code> formats can also import <code>gltf</code>:</p> <ul> <li><a href="https://www.blender.org/" rel="nofollow noreferrer">blender</a> has an <a href="https://github.com/KhronosGroup/glTF-Blender-IO" rel="nofollow noreferrer">importer plugin</a> - more info <a href="https://blender.stackexchange.com/questions/93415/how-to-open-a-glb-or-gltf-file-in-blender">here</a></li> <li><a href="https://www.sketchup.com/" rel="nofollow noreferrer">SketchUpp</a> has an <a href="https://www.simlab-soft.com/3d-plugins/GLTF_Importer_For_Sketchup-main.aspx" rel="nofollow noreferrer">importer plugin</a></li> </ul> <p>You have to be careful though: formats like <code>dae</code> or <code>stl</code> are meant to transfer 3d objects usually without the loss of information or with just a minimal loss (stl, for example, does technically not contain a <em>scale</em> natively), while <code>gltf</code> is end users and <a href="https://stackoverflow.com/questions/40549453/is-there-a-way-to-convert-gltf-to-dae">does not contain all the information</a>. This can lead to models getting distorted and destroyed on importing them into a rendering or modeling software.</p>
1,037
<p>I'm currently adding some new extended classes to this code:</p> <pre><code>foreach (BaseType b in CollectionOfExtendedTypes) { if (b is ExtendedType1) { ((ExtendedType1) b).foo = this; } else if (b is ExtendedType2) { ((ExtenedType2) b).foo = this; } else { b.foo = this; } } </code></pre> <p>and was curious if there is a way to use the <code>is</code> keyword functionality in a switch statement?</p>
<p>This really looks like a situation for a good polymorphic implementation. If you override the appropriate methods in the derived classes, you may not need the checks in the loop at all.</p>
<p>In C#, I believe the switch statement only works with integers and strings.</p>
27,619
<p>When I set trust connection = yes in my web.config, what user account does it use?</p> <p>Is it the 'NT AUTHORITY\NETWORK SERVICE'?</p> <p>Because I under security in Sql management, I see: NtAuthority/System only??</p>
<p>It uses the user that your Application Pool is running as, the default being 'NT AUTHORITY\NETWORK SERVICE'</p> <p>The title of the question should be "What user account will ASP.NET use when I connect to SQL Server using trusted___connection". Trusted_connection uses the current process' (or impersonated) credentials.</p> <p>Your .NET code runs inside the Application Pool. You can configure the user account the Application Pool runs under within IIS configuration. Best practices is to run your Application Pool under a restricted user account, and grant that user login to the database.</p> <p>Don't confuse this with the IIS Anonymous User default account, the account the IIS service is running as or the IIS Security tab on the website settings. You can set your web application to impersonate (run as) the user that IIS authenticates them as (See Impersonation in the ASP.NET doco). </p> <p>Rob</p>
<p>It will use the credential of the currently logged in user. The reason you see NETWORK Service is because IIS app pools (by default) runs as that account.</p>
36,246
<p>input: phrase 1, phrase 2</p> <p>output: semantic similarity value (between 0 and 1), or the probability these two phrases are talking about the same thing</p>
<hr> <p>You might want to check out this paper:</p> <p><a href="http://ants.iis.sinica.edu.tw/3BkMJ9lTeWXTSrrvNoKNFDxRm3zFwRR/55/Sentence%20Similarity%20Based%20on%20Semantic%20Nets%20and%20corpus%20statistics.pdf" rel="noreferrer">Sentence similarity based on semantic nets and corpus statistics (PDF)</a></p> <p>I've implemented the algorithm described. Our context was very general (effectively any two English sentences) and we found the approach taken was too slow and the results, while promising, not good enough (or likely to be so without considerable, extra, effort).</p> <p>You don't give a lot of context so I can't necessarily recommend this but reading the paper could be useful for you in understanding how to tackle the problem.</p> <p>Regards,</p> <p>Matt.</p>
<p>Take a look at <a href="http://mkusner.github.io/publications/WMD.pdf" rel="nofollow noreferrer">http://mkusner.github.io/publications/WMD.pdf</a> This paper describes an algorithm called Word Mover distance that tries to uncover semantic similarity. It relies on the similarity scores as dictated by word2vec. Integrating this with GoogleNews-vectors-negative300 yields desirable results. </p>
8,771
<p>I would like to make custom cake molds. </p> <p>I've asked about this in a few stores that specialize in cooking equipment, they said this wasn't possible. </p> <p>I wonder if 3D printing makes it possible. It would require a material that is food-safe, as per <a href="https://3dprinting.stackexchange.com/questions/147/which-are-the-food-safe-materials-and-how-do-i-recognize-them">Which are the food-safe materials and how do I recognize them?</a></p> <p>However, there are two extra conditions:</p> <ul> <li>The material must be able to withstand the heat of an oven or microwave, and not mix with the dough.</li> <li>It should not be too difficult to remove the cake from the mold after it is ready.</li> </ul> <p>The first condition is where this question is a little different from <a href="https://3dprinting.stackexchange.com/questions/181/can-you-use-pla-material-with-food-and-drinks">Can you use PLA material with food and drinks?</a> - that question is about cutlery and glasses, not about things that go into the oven or microwave.</p> <p>Is there a material that can be used for this purpose?</p>
<p>For <a href="http://3dprintingfromscratch.com/common/types-of-3d-printers-or-3d-printing-technologies-overview/#fdm" rel="nofollow noreferrer">FDM</a> printing: </p> <p>Both Cura and Makerbot Desktop (and perhaps others I'm not as familiar with) will give you a preview of both the length and weight of your print, including supports/rafts. Once the print is done you can weigh it on a kitchen scale.</p> <p>PLA Filament currently runs about \$23/kg on Amazon, which works out to \$0.023/g. Multiplication can then give you a good estimate of materials costs for a print.</p> <p>Only experience with your specific printer will give you an idea of how often you're going to hit a failed print, and how often you're going to need to replace parts. For wear and tear you could try using a depreciation model of 2-3 years, but that's only an estimate.</p>
<p>I recently faced the problem of calculating the cost of my printed 3D models. I wanted to know what their real value had to be counted in Excel. It was really inconvenient. Then I found a program for counting, it turned out really great, even takes into account the electricity. This is not an advertisement just throwing, maybe someone also encountered such a problem. <a href="https://codecanyon.net/item/mcc-3d-model-cost-calculation-for-3d-printer/24033425" rel="nofollow noreferrer">https://codecanyon.net/item/mcc-3d-model-cost-calculation-for-3d-printer/24033425</a> I was interested in the question who solved the given problem in what ways?</p>
130
<p><em>By Logic Programming I mean the a sub-paradigm of declarative programming languages. Don't confuse this question with "What problems can you solve with if-then-else?"</em></p> <p>A language like Prolog is very fascinating, and it's worth learning for the sake of learning, but I have to wonder what class of real-world problems is best expressed and solved by such a language. Are there better languages? Does logic programming exist by another name in more trendy programming languages? Is the cynical version of the answer a variant of the <a href="http://www.paulgraham.com/pypar.html" rel="noreferrer">Python Paradox</a>?</p>
<p><em>Prototyping</em>. </p> <p>Prolog is dynamic and has been for 50 years. The compiler is liberal, the syntax minimalist, and "doing stuff" is easy, fun and efficient. SWI-Prolog has a built-in <a href="https://www.swi-prolog.org/pldoc/man?section=debugoverview" rel="nofollow noreferrer">tracer (debugger!)</a>, and even a <a href="https://www.swi-prolog.org/pldoc/doc_for?object=section(2,%273.5%27,swi(%27/doc/Manual/guitracer.html%27))" rel="nofollow noreferrer">graphical tracer</a>. You can change the code on the fly, using <code>make/0</code>, you can dynamically load modules, add a few lines of code without leaving the interpreter, or edit the file you're currently running on the fly with <code>edit(1)</code>. Do you think you've found a problem with the <code>foobar/2</code> predicate?</p> <pre><code>?- edit(foobar). </code></pre> <p>And as soon as you leave the editor, that thing is going to be re-compiled. Sure, Eclipse does the same thing for Java, but Java isn't exactly a prototyping language.</p> <p>Apart from the pure prototyping stuff, Prolog is incredibly well suited for <em>translating a piece of logic into code</em>. So, automatic provers and that type of stuff can easily be written in Prolog.</p> <p>The first Erlang interpreter was written in Prolog - and for a reason, since <em>Prolog is very well suited for parsing, and encoding the logic you find in parse trees</em>. In fact, Prolog comes with a built-in parser! No, not a library, it's in the syntax, namely <a href="http://www.amzi.com/manuals/amzi/pro/ref_dcg.htm" rel="nofollow noreferrer">DCG</a>s.</p> <p>Prolog is <em>used a lot in NLP, particularly in syntax and computational semantics</em>.</p> <p>But, Prolog is underused and underappreciated. Unfortunately, it seems to bear an academic or "unusable for any real purpose" stigma. But it can be put to very good use in many real-world applications involving facts and the computation of relations between facts. It is not very well suited for number crunching, but CS is not only about number crunching.</p>
<p>Yes, <a href="https://en.wikipedia.org/wiki/Prolog" rel="nofollow noreferrer">Prolog has been around since 1972</a>. It was invented by Alain Colmerauer with Philippe Roussel, based on Robert Kowalski's procedural interpretation of Horn clauses. Alain was a French computer scientist and professor at Aix-Marseille University from 1970 to 1995.</p> <p>And Alain invented it to <strong>analyse Natural Language</strong>. Several successful prototypes were created by him and his &quot;followers&quot;.</p> <ul> <li>His own system Orbis to understand questions in English and French about the solar system. See his <a href="http://alain.colmerauer.free.fr/" rel="nofollow noreferrer">personal site</a>.</li> <li>Warren and Pereira's system <a href="https://dl.acm.org/doi/10.5555/972942.972944" rel="nofollow noreferrer">Chat80</a> QA on world geography.</li> <li>Today, <a href="https://en.wikipedia.org/wiki/Watson_(computer)" rel="nofollow noreferrer">IBM Watson</a> is a contempory QA based on logic with a huge dose of statistics about real world phrases.</li> </ul> <p>So you can imagine that's where it's strength is.</p> <p>Retired in 2006, he remained active until he died in 2017. He was named Chevalier de la Legion d’Honneur by the French government in 1986.</p>
26,519
<p>If I add 3-400 databases to a single SQL Server instance will I encounter scaling issues introduced by the large number of databases?</p>
<p>This is one of those questions best answered by: Why are you trying to do this in the first place? What is the concurrency against those databases? Are you generating databases when you could have normalized tables to do the same functionality?</p> <p>That said, yes MSSQL 2005 will handle that level of database per installation. It will more or less be what you are doing with the databases which will seriously impede your performance (incoming connections, CPU usage, etc.)</p>
<p>I have never tried this in 2005. But a company I used to work for tried this on 7.0 and it failed miserably. With 2000 things got a lot better but querying across databases was still painfully slow and took too many system resources. I can only imagine things improved again in 2005.</p> <p>Are you querying across the databases or just hosting them on the same server? If you are querying across the databases, I think you need to take another look at your data architecture and find other ways to separate the data. If it's just a hosting issue, you can always try it out and move off databases to other servers as capacity is reached.</p> <p>Sorry, I don't have a definite answer here.</p>
9,334
<p>I want to create parts for a 3D printer using OpenSCAD. Having some STL files from the vendor, but nothing else (no technical drawing, no CAD files).</p> <p>Does anybody knows a free tool, that allows me to</p> <ul> <li>measure distances between 2 selected vertices,</li> <li>measure distances between a selected vertex and a plane defined by 3 vertices,</li> <li>measure the radio of a circle defined by 3 selected vertices?</li> </ul> <p>I very much like the way Blender allows to work with meshes, especially select vertices or planes, but unfortunately haven't found a way to measure with Blender.</p>
<p>I suggest Blender. It's not the simplest of tools but it is free and learning it will improve your 3D printing skills. :-) (I write this answer also for future viewers of this question so I start basic).</p> <p>Another answer can be found here, <a href="https://blender.stackexchange.com/q/19772/14005">How do I measure a distance between two points?</a></p> <ol> <li>Import your STL file.</li> <li>Press the Home key to view everything.</li> <li>Select the model by clicking on it with your left mouse button. (Blender changed to left-click-select as of version 2.80)</li> <li>Hit tab to enter edit-mode.</li> <li>Press N (or use View | Properties) until the Properties panel shows up.</li> <li>Select the &quot;Length&quot; checkbox in the &quot;Edge Info&quot; section of the Properties panel (see image below).</li> <li>Select &quot;Edge Select&quot; mode (see image below)</li> <li>Select the edge to measure by clicking on it with your right mouse button.</li> </ol> <p><a href="https://i.stack.imgur.com/9Oi1c.png" rel="nofollow noreferrer" title="Edge length"><img src="https://i.stack.imgur.com/9Oi1c.png" alt="Edge length" title="Edge length" /></a></p> <p><a href="https://i.stack.imgur.com/Ouw0q.png" rel="nofollow noreferrer" title="Screenshot of toolbar"><img src="https://i.stack.imgur.com/Ouw0q.png" alt="Screenshot of toolbar" title="Screenshot of toolbar" /></a></p> <p>If you need to measure the distance between to vertices with no edge. Create the edge by selecting them and pressing <kbd>F</kbd>. If you need to measure the distance between a vertex and any other point, select it and press <kbd>E</kbd> to extrude.</p>
<p>Use Meshy &quot;...a WebGL-based tool that does measurements and simple transformations on STL and OBJ files.&quot;: <a href="https://0x00019913.github.io/meshy/" rel="nofollow noreferrer">https://0x00019913.github.io/meshy/</a></p>
472
<p>I'm working on a very simple game (essentially an ice sliding puzzle), for now the whole things in one file and the only level is completely blank of any form of obstacle. It throws up a few errors. My current annoyance is an expected primary expression error, can anyone tell me how to fix it (it throws up at line 99)?</p> <p>Here's the whole thing,</p> <pre><code>#include &lt;allegro.h&gt; BITMAP* buffer; int x = 15; int y = 11; int tempX = 15; int tempY = 11; //This will be our background, 1 = clouds, 2 = brick, 3 = floor int map[24][32] = {{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,2,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}}; //This will contain all the objects, 100 = player int objMap[24][32] = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}}; void setupGame(){ buffer = create_bitmap( 640, 480); for (int i = 0; i &lt;= 24; i++){ for( int t = 0; t &lt;= 32; t++){ if( map[i][t] == 1) rectfill( buffer, t * 20, i * 20, (t + 1) * 20, (i + 1) * 20, makecol( 128, 255, 255)); else if( map[i][t] == 2) rectfill( buffer, t * 20, i * 20, (t + 1) * 20, (i + 1) * 20, makecol( 255, 128, 0)); else if( map[i][t] == 3) rectfill( buffer, t * 20, i * 20, (t + 1) * 20, (i + 1) * 20, makecol( 0, 0, 255)); } } for (int i = 0; i &lt;= 24; i++){ for( int t = 0; t &lt;= 32; t++){ if( objMap[i][t] == 100) circlefill( buffer, (t * 20) + 10, (i * 20) + 10, 10, makecol( 255, 255, 0)); } } draw_sprite( screen, buffer, 0, 0); } void movePlayer(){ tempX = x; tempY = y; if ( key[KEY_UP] &amp;&amp; map[y - 1][x] == 3){ for ([y - 1][x] == 3; --y){ // these lines are the ones } } else if( key[KEY_DOWN] &amp;&amp; map[y + 1][x] == 3){ for ([y + 1][x] == 3; ++y){ } } else if( key[KEY_RIGHT] &amp;&amp; map[y][x + 1] == 3){ for ([y][x + 1] == 3; ++x){ } } else if( key[KEY_LEFT] &amp;&amp; map[y][x - 1] == 3){ for ([y][x - 1] == 3; --x){ } } acquire_screen(); rectfill( buffer, tempX * 20, tempY * 20, (tempX + 1) * 20, (tempY + 1) * 20, makecol( 255, 0, 0)); circlefill( buffer, (x * 20) + 10, (y * 20) + 10, 10, makecol( 255, 255, 0)); draw_sprite( screen, buffer, 0, 0); release_screen(); rest(20); } int main(){ allegro_init(); install_keyboard(); set_color_depth(16); set_gfx_mode( GFX_AUTODETECT, 640, 480, 0, 0); setupGame(); while( !key[KEY_ESC]){ modePlayer(); } return 0; } END_OF_MAIN(); </code></pre> <p>and here's the section that breaks;</p> <pre><code>void movePlayer(){ tempX = x; tempY = y; if ( key[KEY_UP] &amp;&amp; map[y - 1][x] == 3){ for ([y - 1][x] == 3; --y){ } } else if( key[KEY_DOWN] &amp;&amp; map[y + 1][x] == 3){ for ([y + 1][x] == 3; ++y){ } } else if( key[KEY_RIGHT] &amp;&amp; map[y][x + 1] == 3){ for ([y][x + 1] == 3; ++x){ } } else if( key[KEY_LEFT] &amp;&amp; map[y][x - 1] == 3){ for ([y][x - 1] == 3; --x){ } } </code></pre> <p>it's the for lines it doesn't like.</p> <p>thanks if you can help.</p>
<p>This might help:</p> <pre><code>void movePlayer(){ tempX = x; tempY = y; if (key[KEY_UP] &amp;&amp; map[y - 1][x] == 3) for ( ; map[y - 1][x] == 3; --y){ } else if(key[KEY_DOWN] &amp;&amp; map[y + 1][x] == 3) for ( ; map[y + 1][x] == 3; ++y){ } else if(key[KEY_RIGHT] &amp;&amp; map[y][x + 1] == 3) for ( ; map[y][x + 1] == 3; ++x){ } else if(key[KEY_LEFT] &amp;&amp; map[y][x - 1] == 3) for ( ; map[y][x - 1] == 3; --x){ } </code></pre>
<p>Your "for" loops are missing a section. Usually there are three parts: an initialization, a condition, and post-iteration operation. From what I can tell, you have the last two, but no initialization. The compiler is currently interpreting your first "for" loop, for example, as:</p> <ol> <li>Check 3 against [y-1][x]</li> <li>While 0 != (result of decrement y)...</li> <li>Do whatever</li> </ol> <p>What I think you mean to happen is:</p> <ol> <li>Assume everything is initialized</li> <li>While 3 == [y-1][x]...</li> <li>Do whatever, and decrement y after each iteration</li> </ol> <p>If so, this should look like:</p> <pre><code>for (; [y-1][x]==3; --y) { // do whatever } </code></pre> <p>This applies to all your "for" loops.</p> <p>Another issue is that you aren't using an array variable, but are just using index offsets. Do you mean to say "map[y-1][x]"?</p>
48,686
<p>I've got some code that will generically get all Controls in a form and put them in a list. Here's some of the code:</p> <pre><code> private List&lt;Control&gt; GetControlList(Form parentForm) { List&lt;Control&gt; controlList = new List&lt;Control&gt;(); AddControlsToList(parentForm.Controls, controlList); return controlList; } private void AddControlsToList(Control.ControlCollection rootControls, List&lt;Control&gt; controlList) { foreach (Control c in rootControls) { controlList.Add(c); if (c.HasChildren) AddControlsToList(c.Controls, controlList); // } } </code></pre> <p>So I'm only able to use c.HasChildren to check and see if there's any more child controls from this root control.</p> <p><strong>What about a menuStrip, toolStrip, and statusStrip? How do I get all of the controls that are in these controls generically? Ex: MenuStripItem</strong></p> <p>I know that I could try testing the c.GetType() == typeof(MenuStrip) but I was hoping to not have to do specific type tests.</p> <p>If I need to give more info, please ask.</p> <p>Thanks a bunch</p>
<p>I believe the VS designer does it by getting an instance of the control's designer (see the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.designerattribute.aspx" rel="nofollow noreferrer"><code>Designer</code> attribute</a>), and, if the designer is a <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.design.componentdesigner.aspx" rel="nofollow noreferrer"><code>ComponentDesigner</code></a>, getting the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.design.componentdesigner.associatedcomponents.aspx" rel="nofollow noreferrer"><code>AssociatedComponents</code></a> property.</p> <p><strong>EDIT</strong>:</p> <p>Okay, I guess that's a little vague. A warning, though: what follows is a little complicated, and might not be worth the effort.</p> <p>A note on nomenclature:<br> Below, I will be referring to both the designer within Visual Studio—which is the name used to refer to the functionality within Visual Studio by which the layout and content of forms and controls are edited visually—and to designer classes—which will be explained below. To prevent confusion as to which I am referring to at any given time, I will always refer to the designer functionality within Visual Studio as "the designer", and I will always refer to a designer class as an "IDesigner", which is the interface each must implement.</p> <p>When the Visual Studio designer loads a component (usually a control, but also things like <code>Timer</code> and such), it looks for a custom attribute on the class of type <code>DesignerAttribute</code>. (Those unfamiliar with attributes might want <a href="http://msdn.microsoft.com/en-us/library/aa288059(VS.71).aspx" rel="nofollow noreferrer">read up on them</a> before continuing.)</p> <p>This attribute, if present, provides the name of a class—an IDesigner—the designer can use to interface with the component. In effect, this class controls certain aspects of the designer and of the design-time behavior of the component. There's indeed quite a lot you can do with an IDesigner, but right now we're only interested in one thing.</p> <p>Most controls that use a custom IDesigner use one that derives from <code>ControlDesigner</code>, which itself derives from <code>ComponentDesigner</code>. The <code>ComponentDesigner</code> class has a public virtual property called <code>AssociatedComponents</code>, which is meant to be overridden in derived classes to return a collection of references to all "child" components of this one.</p> <p>To be more specific, the <code>ToolStrip</code> control (and by inheritance, the <code>MenuStrip</code> control) has a <code>DesignerAttribute</code> that references a class called <code>ToolStripDesigner</code>. It looks sort of like:</p> <pre><code>/* * note that in C#, I can refer to the "DesignerAttribute" class within the [ brackets ] * by simply "Designer". The compiler adds the "Attribute" to the end for us (assuming * there's no attribute class named simply "Designer"). */ [Designer("System.Windows.Forms.Design.ToolStripDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), ...(other attributes)] public class ToolStrip : ScrollableControl, IArrangedElement, ...(other interfaces){ ... } </code></pre> <p>The <code>ToolStripDesigner</code> class is not public. It's internal to System.Design.dll. But since it's specified here by it's fully qualified name, the VS designer can use <code>Activator.CreateInstance</code> to create an instance of it anyway.</p> <p>This <code>ToolStripDesigner</code> class, because it inherits [indirectly] from <code>ComponentDesigner</code> has an <code>AssociatedComponents</code> property. When you call it you get a new <code>ArrayList</code> that contains references to all the items that have been added to the <code>ToolStrip</code>.</p> <p>So what would <em>your</em> code have to look like to do the same thing? Rather convoluted, but I think I have a working example:</p> <pre><code>/* * Some controls will require that we set their "Site" property before * we associate a IDesigner with them. This "site" is used by the * IDesigner to get services from the designer. Because we're not * implementing a real designer, we'll create a dummy site that * provides bare minimum services and which relies on the framework * for as much of its functionality as possible. */ class DummySite : ISite, IDisposable{ DesignSurface designSurface; IComponent component; string name; public IComponent Component {get{return component;}} public IContainer Container {get{return designSurface.ComponentContainer;}} public bool DesignMode{get{return false;}} public string Name {get{return name;}set{name = value;}} public DummySite(IComponent component){ this.component = component; designSurface = new DesignSurface(); } ~DummySite(){Dispose(false);} protected virtual void Dispose(bool isDisposing){ if(isDisposing) designSurface.Dispose(); } public void Dispose(){ Dispose(true); GC.SuppressFinalize(this); } public object GetService(Type serviceType){return designSurface.GetService(serviceType);} } static void GetComponents(IComponent component, int level, Action&lt;IComponent, int&gt; action){ action(component, level); bool visible, enabled; Control control = component as Control; if(control != null){ /* * Attaching the IDesigner sets the Visible and Enabled properties to true. * This is useful when you're designing your form in Visual Studio, but at * runtime, we'd rather the controls maintain their state, so we'll save the * values of these properties and restore them after we detach the IDesigner. */ visible = control.Visible; enabled = control.Enabled; foreach(Control child in control.Controls) GetComponents(child, level + 1, action); }else visible = enabled = false; /* * The TypeDescriptor class has a handy static method that gets * the DesignerAttribute of the type of the component we pass it * and creates an instance of the IDesigner class for us. This * saves us a lot of trouble. */ ComponentDesigner des = TypeDescriptor.CreateDesigner(component, typeof(IDesigner)) as ComponentDesigner; if(des != null) try{ DummySite site; if(component.Site == null) component.Site = site = new DummySite(component); else site = null; try{ des.Initialize(component); foreach(IComponent child in des.AssociatedComponents) GetComponents(child, level + 1, action); }finally{ if(site != null){ component.Site = null; site.Dispose(); } } }finally{des.Dispose();} if(control != null){ control.Visible = visible; control.Enabled = enabled; } } /* We'll use this in the ListComponents call */ [DllImport("user32.dll", CharSet=CharSet.Auto)] static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam); const int WM_SETREDRAW = 11; void ListComponents(){ /* * Invisible controls and disabled controls will be temporarily shown and enabled * during the GetComponents call (see the comment within that call), so to keep * them from showing up and then disappearing again (or appearing to temporarily * change enabled state), we'll disable redrawing of our window and re-enable it * afterwards. */ SendMessage(Handle, WM_SETREDRAW, 0, 0); GetComponents(this, 0, /* You'll want to do something more useful here */ (component, level)=&gt;System.Diagnostics.Debug.WriteLine(new string('\t', level) + component)); SendMessage(Handle, WM_SETREDRAW, 1, 0); } </code></pre>
<p>The items such as ToolStripItem etc aren't actually controls, they are simply components that make up a ToolStrip or MenuStrip.</p> <p>Which means, that if you want to include those components in your flattened list of controls then you will need to do the specific checks.</p>
38,040
<p>I've been working with Vector2's and XNA, and I've come to find that calling the Normalize() member function on a Zero Vector normalizes it to a vector of {NaN, NaN}. This is all well and good, but in my case I'd prefer it instead just leave them as Zero Vectors.</p> <p>Adding this code to my project enabled a cute extension method:</p> <pre><code>using ExtensionMethods; namespace ExtensionMethods { public static class MyExtensions { public static Vector2 NormalizeOrZero(this Vector2 v2) { if (v2 != Vector2.Zero) v2.Normalize(); return v2; } } } </code></pre> <p>Unfortunately, this method <em>returns</em> the normalized vector, rather than simply normalizing the vector which I use to invoke this extension method. I'd like to to instead behave as <em>vector2Instance</em>.Normalize() does.</p> <p>Aside from making this void, how do I adjust this so that the 'v2' is modified? (Essentially, I need access to the 'this' object, or I need 'v2' to be passed by reference.)</p> <p>Edit:</p> <p>And yes, I have tried this:</p> <pre><code> public static void NormalizeOrZero(this Vector2 v2) { if (v2 != Vector2.Zero) v2.Normalize(); } </code></pre> <p>Doesn't work, v2 is just a variable in the scope of NormalizeOrZero.</p>
<p>This doesn't work because Vector 2 <a href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.aspx" rel="nofollow noreferrer">is actually a struct</a>. This means it gets passed by value and you can't modify the caller's copy. I think the best you can do is the workaround specified by lomaxxx.</p> <p>This illustrates why you should generally avoid using structures. See <a href="https://stackoverflow.com/questions/85553/when-should-i-use-a-struct-instead-of-a-class">this question</a> for more information. Vector2 violates the guideline that structs should be immutable, but it probably made sense to do so in the context of XNA.</p>
<p>I'm not sure why your second code sample doesn't work but if the first lot of code does what you want you could simply work around it by going:</p> <pre><code>Vector2 v2 = new Vector2() v2 = v2.NormalizeOrZero(); </code></pre>
39,064
<p>Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:</p> <pre><code>int[] terms; for(int runs = 0; runs &lt; 400; runs++) { terms[] = runs; } </code></pre> <p>For those who have used PHP, here's what I'm trying to do in C#:</p> <pre><code>$arr = array(); for ($i = 0; $i &lt; 10; $i++) { $arr[] = $i; } </code></pre>
<p>You can do this way -</p> <pre><code>int[] terms = new int[400]; for (int runs = 0; runs &lt; 400; runs++) { terms[runs] = value; } </code></pre> <p>Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.</p> <pre><code>List&lt;int&gt; termsList = new List&lt;int&gt;(); for (int runs = 0; runs &lt; 400; runs++) { termsList.Add(value); } // You can convert it back to an array if you would like to int[] terms = termsList.ToArray(); </code></pre> <p><strong>Edit:</strong> <a href="https://stackoverflow.com/a/365658/495455">a) <strong>for</strong> loops on List&lt;T> are a bit more than 2 times cheaper than <strong>foreach</strong> loops on List&lt;T>, b) Looping on array is around 2 times cheaper than looping on List&lt;T>, c) looping on array using <strong>for</strong> is 5 times cheaper than looping on List&lt;T> using <strong>foreach</strong> (which most of us do).</a></p>
<p>Here is one way how to deal with adding new numbers and strings to Array:</p> <pre><code>int[] ids = new int[10]; ids[0] = 1; string[] names = new string[10]; do { for (int i = 0; i &lt; names.Length; i++) { Console.WriteLine(&quot;Enter Name&quot;); names[i] = Convert.ToString(Console.ReadLine()); Console.WriteLine($&quot;The Name is: {names[i]}&quot;); Console.WriteLine($&quot;the index of name is: {i}&quot;); Console.WriteLine(&quot;Enter ID&quot;); ids[i] = Convert.ToInt32(Console.ReadLine()); Console.WriteLine($&quot;The number is: {ids[i]}&quot;); Console.WriteLine($&quot;the index is: {i}&quot;); } } while (names.Length &lt;= 10); </code></pre>
24,807
<p>Through profiling I've discovered that the sprintf here takes a long time. Is there a better performing alternative that still handles the leading zeros in the y/m/d h/m/s fields?</p> <pre><code>SYSTEMTIME sysTime; GetLocalTime( &amp;sysTime ); char buf[80]; for (int i = 0; i &lt; 100000; i++) { sprintf(buf, "%4d-%02d-%02d %02d:%02d:%02d", sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond); } </code></pre> <hr> <p>Note: The OP explains in the comments that this is a stripped-down example. The "real" loop contains additional code that uses varying time values from a database. Profiling has pinpointed <code>sprintf()</code> as the offender.</p>
<p>If you were writing your own function to do the job, a lookup table of the string values of 0 .. 61 would avoid having to do any arithmetic for everything apart from the year.</p> <p>edit: Note that to cope with leap seconds (and to match <a href="http://en.cppreference.com/w/c/chrono/strftime" rel="nofollow noreferrer"><code>strftime()</code></a>) you should be able to print seconds values of 60 and 61.</p> <pre><code>char LeadingZeroIntegerValues[62][] = { "00", "01", "02", ... "59", "60", "61" }; </code></pre> <p>Alternatively, how about <a href="http://en.cppreference.com/w/c/chrono/strftime" rel="nofollow noreferrer"><code>strftime()</code></a>? I've no idea how the performance compares (it could well just be calling sprintf()), but it's worth looking at (and it could be doing the above lookup itself).</p>
<p>StringStream is the suggestion that I got from Google.</p> <p><a href="http://bytes.com/forum/thread132583.html" rel="nofollow noreferrer">http://bytes.com/forum/thread132583.html</a></p>
34,224
<p>I am using Python and the <a href="http://twistedmatrix.com/trac/" rel="nofollow noreferrer">Twisted</a> framework to connect to an FTP site to perform various automated tasks. Our FTP server happens to be Pure-FTPd, if that's relevant.</p> <p>When connecting and calling the <strong>list</strong> method on an <strong>FTPClient</strong>, the resulting <strong>FTPFileListProtocol</strong>'s <strong>files</strong> collection does not contain any directories or file names that contain a space (' ').</p> <p>Has anyone else seen this? Is the only solution to create a sub-class of FTPFileListProtocol and override its <strong>unknownLine</strong> method, parsing the file/directory names manually?</p>
<p>Firstly, if you're performing automated tasks on a retrieived FTP listing then you should probably be looking at <code>NLST</code> rather than <code>LIST</code> as noted in <a href="https://www.rfc-editor.org/rfc/rfc959#page-33" rel="nofollow noreferrer">RFC 959 section 4.1.3</a>:</p> <pre> NAME LIST (NLST) ... This command is intended to return information that can be used by a program to further process the files automatically. </pre> <p>The <a href="http://twistedmatrix.com/documents/current/api/twisted.protocols.ftp.FTPClient.html#list" rel="nofollow noreferrer">Twisted documentation</a> for <code>LIST</code> says:</p> <pre> It can cope with most common file listing formats. </pre> <p>This make me suspicious; I do not like solutions that &quot;cope&quot;. <code>LIST</code> was intended for human consumption not machine processing.</p> <p>If your target server supports them then you should prefer <code>MLST</code> and <code>MLSD</code> as defined in <a href="https://www.rfc-editor.org/rfc/rfc3659#section-7" rel="nofollow noreferrer">RFC 3659 section 7</a>:</p> <pre> 7. Listings for Machine Processing (MLST and MLSD) The MLST and MLSD commands are intended to standardize the file and directory information returned by the server-FTP process. These commands differ from the LIST command in that the format of the replies is strictly defined although extensible. </pre> <p>However, these newer commands may not be available on your target server and I don't see them in Twisted. Therefore <code>NLST</code> is probably your best bet.</p> <p>As to the nub of your problem, there are three likely causes:</p> <ol> <li>The processing of the returned results is incorrect (Twisted may be at fault, as you suggest, or perhaps elsewhere)</li> <li>The server is buggy and not sending a correct (complete) response</li> <li>The wrong command is being sent (unlikely with straight <code>NLST</code>/<code>LIST</code>, but some servers react differently if arguments are supplied to these commands)</li> </ol> <p>You can eliminate (2) and (3) and prove that the cause is (1) by looking at what is sent over the wire. If this option is not available to you as part of the Twisted API or the Pure-FTPD server logging configuration, then you may need to break out a network sniffer such as tcpdump, snoop or WireShark (assuming you're allowed to do this in your environment). Note that you will need to trace not only the control connection (port 21) but also the data connection (since that carries the results of the <code>LIST</code>/<code>NLST</code> command). WireShark is nice since it will perform the protocol-level analysis for you.</p> <p>Good luck.</p>
<p>This is somehow expected. FTPFileListProtocol isn't able to understand every FTP output, because, well, some are wacky. As explained in the docstring:</p> <p>If you need different evil for a wacky FTP server, you can override either C{fileLinePattern} or C{parseDirectoryLine()}.</p> <p>In this case, it may be a bug: maybe you can improve fileLinePattern and makes it understand filename with spaces. If so, you're welcome to open a bug in the Twisted tracker.</p>
39,080
<p>when I apply the tag above my methods I get the error </p> <blockquote> <p>Type System.Runtime.CompilerServices.Extension is not defined.</p> </blockquote> <p>Here is my sample</p> <pre><code>&lt;System.Runtime.CompilerServices.Extension()&gt; _ Public Sub test() End Sub </code></pre> <p>Where am I going wrong?</p> <p>Edit ~ Straight from the MSDN Article <a href="http://msdn.microsoft.com/en-us/library/bb384936.aspx" rel="noreferrer">here</a>, the same error</p> <p><code></p> <pre> Imports System.Runtime.CompilerServices Module StringExtensions _ Public Sub Print(ByVal aString As String) Console.WriteLine(aString) End Sub End Module </pre> <p></code></p> <p>I am using Visual Studio 2008 and 3.5 Framework in my project.</p> <blockquote> <p>Solution ~ The project was on 2.0 Framework. Changed to 3.5 and it works.</p> </blockquote>
<p>What version of .net framework the IDE is pointing towards?</p> <p>Also, at first glance the syntax of extension method looks incorrect.</p> <p>The code is incomplete. Please put the using statements in the example for anyone to use the code and compile it - to reproduce the error.</p>
<p>Use this...</p> <p>System.Runtime.CompilerServices.ExtensionAttribute</p> <p>Couldn't find anything called Extension in the namespace you mentioned.</p>
43,133
<p>Recently I started looking on pressure advance and how it works and I'm a bit confused about where it is usually implemented.</p> <p>My Idea of 3D printer was that its firmware is fairly dumb and only replays GCode, not knowing anything about the object being printed, material used, or even the printer itself.</p> <p>But with pressure advance this whole thing changes and now the firmware needs to know the linear advance factor which combines information about the filament and filament path used. In addition the E axis is no longer controlled directly by the GCode, but it's motion is almost independently determined by the firmware.</p> <p>Why is this? Is there a reason that slicer (or a post-processor) can't compute all this and directly store the needed extruder axis movements in the GCode? Does the printer have some additional information that the slicer is missing?</p>
<blockquote> <p>In addition the E axis is no longer controlled directly by the GCode, but it's motion is almost independently determined by the firmware.</p> </blockquote> <p>This is the case even without linear advance. G-code does not directly control the movement of any of the axes. G-code only specifies the path the axes should travel, but not the acceleration and deceleration associated with following that path. If you are printing a cube, then the G-code might specify that the extruder has to extrude a square. It will specify that the 4 sides of the square should be printed, but it does not specify how the transition from one side to the next should be handled.</p> <p>The printer cannot instantly transition from extruding one side of the square to extruding the next side, because the direction of the extruder cannot change instantaneously. It needs to smoothly decelerate and accelerate. This is handled by the firmware, which translates the straight line commands from G-code to smooth acceleration and deceleration of the extruder.</p> <p>This is exactly where linear advance comes in. It is coupled to the acceleration and deceleration. There is no way to &quot;implement&quot; linear advance in G-code, because G-code does not even have any notion of acceleration and deceleration. The G-code (and slicer) has no idea how the firmware is handling the acceleration and deceleration, so therefore it is impossible for the slicer to know what linear advance is required to match.</p> <p>Then you might ask: &quot;why is acceleration and deceleration not implemented in G-code (rather than in firmware)?&quot; This is simply a design choice. G-code is meant to be a very simple file format, and it simply allows you to specify straight line move commands. Representing smooth acceleration curves would either require breaking them down into many discrete, small steps, but this would greatly increase the file size. You could suggest a more complex G-code specification that would allow a more &quot;compact&quot; representation of acceleration and deceleration curves but then you're just shifting the computation back to the firmware (albeit with a more explicit specification in the G-code).</p>
<p>This is a really good question that sheds a lot of light on 3D printer software/firmware architecture, and Tom already said a lot of the things I wanted to say before getting a chance to write an answer. The basic problem is that, to do pressure advance accurately (and in a way that doesn't get it horribly wrong when inaccurate), you need to know the actual feedrate of the extruder at all times, and that's not available until applying the acceleration profile, which by convention happens in the printer firmware.</p> <p>With that said, there were primitive and even somewhat advanced attempts to do pressure advance in the slicer. The first seems to have been &quot;coasting&quot;, which, along with extra-priming after coast, is pretty much just &quot;pressure advance, assuming a constant feedrate&quot;. It gets things horribly wrong if you mix different extruder feedrates (different print speeds or line widths, etc.) or if you have slow acceleration, but if your acceleration is so fast (relative to max speed) that it's approximately instantaneous, it might work okay.</p> <p>Modern Cura also has Flow Rate Compensation, which is something like pressure advance. It's rate-sensitive, so in theory it can give accurate results with varying line width and print speed as long as acceleration is close enough to instantaneous. Since it appeared after Marlin added linear advance, I never bothered trying to play with it, so I can't speak to whether it actually works decently. There are still a lot of subtleties to when the advance is performed that it could get wrong, and I think you'd want to do some test cases just to read the gcode output and evaluate whether what it's doing is sufficiently close to reasonable.</p> <p>If you wanted to do full pressure advance in the slicer, you'd need to let the slicer handle acceleration profile, breaking lines up into small segments each with nominal feedrate matching the rate they should end at, and sufficiently close to the rate they should start at, with the firmware acceleration limits set to accommodate the change. Then, knowing a very good approximation of the actual toolhead and thus extruder feedrate for each segment, you'd know the advance to apply, and could apply it as an additional subdivision at the end of the previous print move. And then in theory, it all works out. But this would make the gcode <strong>a lot</strong> larger/bulkier, and more demanding on the serial link speed and microcontroller's ability to keep up with parsing/planning. So it's almost surely a bad idea.</p> <p>The Klipper firmware does this differently. It does the gcode parsing and planning (including pressure advance) in Python software (with some C for critical paths) running on a much more capable computer, and sends the precise generated stepper motor timings over the serial link to the microcontroller operating the printer hardware.</p>
1,796
<p>I'm having a problem with a Klondike Solitaire I'm programming. It's almost finished but now when I try to compile (I'm using Dr. Java, yeah I know), it keeps popping up with 2 errors.</p> <ol> <li>Cannot find symbol: Variable event</li> <li>Cannot find symbol: Method "findbunki" (java.awt.Point)</li> </ol> <p>I've already imported java.awt, so that can't be it.</p>
<p>Without code this would be my guess:</p> <p>1) you use a variable named 'event' but it is not one of the arguments in you method. (Alternatively: you forgot to declare it, but from the name I'd guess it's belongs in a method call)</p> <p>2) You call the method 'findbunki' on an object of type java.awt.Point - Point does not have that method. Find the class that has the fundbunki method (probably one of your own classes) and call the method on an object of that type.</p>
<p>You should be import java.awt.event.*;</p>
47,831
<p>Ok, bear with me guys and girls as I'm learning. Here's my question.</p> <p>I can't figure out why I can't override a method from a parent class. Here's the code from the base class (yes, I pilfered the java code from an OOP book and am trying to rewrite it in C#).</p> <pre><code>using System; public class MoodyObject { protected String getMood() { return "moody"; } public void queryMood() { Console.WriteLine("I feel " + getMood() + " today!"); } } </code></pre> <p>and here are my other 2 objects that inherit the base class (MoodyObject):</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { public class SadObject: MoodyObject { protected String getMood() { return "sad"; } //specialization public void cry() { Console.WriteLine("wah...boohoo"); } } } </code></pre> <p>And:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { public class HappyObject: MoodyObject { protected String getMood() { return "happy"; } public void laugh() { Console.WriteLine("hehehehehehe."); } } } </code></pre> <p>and here is my main:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { MoodyObject moodyObject = new MoodyObject(); SadObject sadObject = new SadObject(); HappyObject happyObject = new HappyObject(); Console.WriteLine("How does the moody object feel today?"); moodyObject.queryMood(); Console.WriteLine(""); Console.WriteLine("How does the sad object feel today?"); sadObject.queryMood(); sadObject.cry(); Console.WriteLine(""); Console.WriteLine("How does the happy object feel today?"); happyObject.queryMood(); happyObject.laugh(); } } } </code></pre> <p>As you can see, pretty basic stuff, but here's the output:</p> <blockquote> <p>How does the moody object feel today? I feel moody today!</p> <p>How does the sad object feel today? I feel moody today! wah...boohoo</p> <p>How does the happy object feel today? I feel moody today! hehehehehehe. Press any key to continue . . .</p> </blockquote> <p>Not as I expected. I've tried to make the base method virtual and calling override when trying to override it and that just gets me this error "cannot override inherited member 'MoodyObject.getMood()' because it is not marked virtual, abstract, or override". I also tried it without the virtual and override and it thinks I'm trying to hide the base method. Again, I'm new to OOP and would appreciate any guidance.</p> <p><strong>EDITED TO ADD: I found it! The MoodyObject.cs was only a "solution item" in the solution explorer as opposed to a "ConsoleApplication1" item. I dragged it down to where it belonged in the solution explorer and voila! It works now. I marked Luc's answer below as the answer because he offered the help I needed to get to where I have it resolved... I'm learning so much here. It's amazing and you guys and girls are crazy smart!</strong></p>
<p>In C# methods are not virtual by default, so if you design some method as overridable, you should specify it as virtual:</p> <pre><code>class Base { protected virtual string GetMood() {...} } </code></pre> <p>Second, you have to specify that you are going to override method from base class in derived class. </p> <pre><code>class Derived : Base { protected override string GetMood() {...} } </code></pre> <p>If you don't specify "override" keyword, you will get method that hides base type (and warning from compiler to put "new" keyword for the method to explicitly state so).</p> <p>If you want to stop inheritance chain and disallow further overrides of the method, you should mark method as sealed, like this:</p> <pre><code> protected sealed override string GetMood() {...} </code></pre>
<p>You need to mark the overrides of getMood with the "override" keyword. You'll also need to mark the base getMood method with the "virtual" keyword.</p>
43,805
<p>What are some of the new features that can be used in .NET 2.0 that are specific to C# 3.0/3.5 after upgrading to Visual Studio 2008? Also, what are some of the features that aren't available?</p> <p><strong>Available</strong></p> <ul> <li>Lambdas</li> <li>Extension methods (by declaring an empty System.Runtime.CompilerServices.ExtensionAttribute)</li> <li>Automatic properties</li> <li>Object initializers</li> <li>Collection Initializers</li> <li>LINQ to Objects (by implementing IEnumerable extension methods, see <a href="http://www.albahari.com/nutshell/linqbridge.aspx" rel="nofollow noreferrer">LinqBridge</a>)</li> </ul> <p><strong>Not Available</strong></p> <ul> <li>Expression trees</li> <li>WPF/Silverlight Libraries</li> </ul>
<p>You can use any new C# 3.0 feature that is handled by the compiler by emitting 2.0-compatible IL and doesn't reference any of the new 3.5 assemblies:</p> <ul> <li>Lambdas (used as <code>Func&lt;..&gt;</code>, not <code>Expression&lt;Func&lt;..&gt;&gt;</code> )</li> <li>Extension methods (by declaring an empty <code>System.Runtime.CompilerServices.ExtensionAttribute</code>)</li> <li>Automatic properties</li> <li>Object Initializers</li> <li>Collection Initializers</li> <li>LINQ to Objects (by implementing <code>IEnumerable&lt;T&gt;</code> extension methods, see <a href="http://www.albahari.com/nutshell/linqbridge.aspx" rel="nofollow noreferrer">LinqBridge</a>)</li> </ul>
<p>Lambdas &amp; Extension methods are handled purely by the compiler and can be used with the .Net 2.0 framework.</p>
20,854
<p>I distribute software online, and always wonder if there is a proper way to better define version numbers.</p> <p>Let's assume A.B.C.D in the answers. When do you increase each of the components?</p> <p>Do you use any other version number tricks such as D mod 2 == 1 means it is an in house release only?</p> <p>Do you have beta releases with their own version numbers, or do you have beta releases per version number?</p>
<p>I'm starting to like the Year.Release[.Build] convention that some apps (e.g. Perforce) use. Basically it just says the year in which you release, and the sequence within that year. So 2008.1 would be the first version, and if you released another a months or three later, it would go to 2008.2.</p> <p>The advantage of this scheme is there is no implied "magnitude" of release, where you get into arguments about whether a feature is major enough to warrant a major version increment or not.</p> <p>An optional extra is to tag on the build number, but that tends to be for internal purposes only (e.g. added to the EXE/DLL so you can inspect the file and ensure the right build is there).</p>
<p>For in-house development, we use the following format.</p> <pre><code>[Program #] . [Year] . [Month] . [Release # of this app within the month] </code></pre> <p>For example, if I'm releasing application # 15 today, and it's the third update this month, then my version # will be</p> <pre><code>15.2008.9.3 </code></pre> <p>It's totally non-standard, but it is useful for us.</p>
16,283
<p>I'm now trying to create a xml-rpc server with the CodeIgniter Framework. </p> <pre><code>&lt;?php $this-&gt;load-&gt;library('xmlrpc'); $this-&gt;load-&gt;library('xmlrpcs'); $config['functions']['weblogUpdates.ping'] = array('function' =&gt; 'weblogUpdates.ping'); $config['functions']['ping'] = array('function' =&gt; 'weblogUpdates.ping'); $config['functions']['weblogUpdates'] = array('function' =&gt; 'weblogUpdates.ping'); $config['object'] = $this; $this-&gt;xmlrpcs-&gt;serve(); ?&gt; </code></pre> <p>But the problem I have is when Wordpress is trying to ping my file. I can't figure out what I should have as function in the $config['functions'][HERE];</p> <p>Anyone have a solution to this?</p>
<p>Have you looked at <a href="http://codeigniter.com/user_guide/libraries/xmlrpc.html" rel="nofollow noreferrer">the codeigniter user guide</a>?</p>
<p>Thanks, found the problem, I'm so dumb. Had a beta-server up running which I had set Wordpress to ping, and forgot to change the address when I got the new server :$</p>
37,808
<p>I am working with ASP.net.<br><br> I am trying to call a method that exists on the base class for the page I am using. I want to call this method via Javascript and do not require any rendering to be handled by ASP.net.<br><br> What would be the easiest way to accomplish this. <br><br> I have looked at PageMethods which for some reason are not working and found that a lot of other people have had trouble with them.</p>
<p>It depends on what the method relies on, but assuming it is a static method or that it does not rely on the Page Lifecycle to work, you could expose a webservice endpoint and hit that with whichever Javascript calling mechanism you would like to use.</p>
<p>As Thunder3 suggests, expose a Web Service. Once you have done this, you can register the webservice with the ScriptManager (or ScriptManagerProxy), which will cause a JavaScript wrapper to be generated. This wrapper gives you a good interface to the call.</p>
9,315
<p>Every time I see Ruby or Python discussed in the context of web development, it's always with a framework (Rails for Ruby, Django for Python). Are these frameworks necessary? If not, is there a reason why these languages are often used within a framework, while Perl and PHP are not?</p>
<p><strong>The short answer is no, they are not necessary</strong>. In ruby you have .erb templates that can be used in a similar way as you use PHP pages. You can write a site in ruby or Python using several technologies (Rails-like frameworks, Templates or even talking directly with the HTTP library and building the page CGI-style). </p> <p>Web frameworks like Python's Django or Ruby's Rails (there are many) just raise the level of abstraction from the PHP's or ASP's, and automate several process (like login, database interaction, REST API's) which is always a good thing.</p>
<p>By no means are those development frameworks required. But as with most development environments, your productivity will increase exponentially if you have a supported framework to reference and build your applications on. It also decreases the training needed to bring others up to speed on your applications if they already have a core understanding of the framework that you use.</p>
21,097
<p>I'm <em>extremely new</em> to Java, and have mostly just been teaching myself as I go, so I've started building an applet. I'd like to make one that can select a file from the local disk and upload it as a multipart/form-data POST request but <strong>with a progress bar</strong>. Obviously the user has to grant permission to the Java applet to access the hard drive. Now I've already got the first part working: the user can select a file using a <code>JFileChooser</code> object, which conveniently returns a <code>File</code> object. But I'm wondering what comes next. I know that <code>File.length()</code> will give me the total size in bytes of the file, but how do I send the selected <code>File</code> to the web, and how do I monitor how many bytes have been sent? Thanks in advance.</p>
<p>To check progress using HttpClient, wrap the MultipartRequestEntity around one that counts the bytes being sent. Wrapper is below:</p> <pre><code>import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.httpclient.methods.RequestEntity; public class CountingMultipartRequestEntity implements RequestEntity { private final RequestEntity delegate; private final ProgressListener listener; public CountingMultipartRequestEntity(final RequestEntity entity, final ProgressListener listener) { super(); this.delegate = entity; this.listener = listener; } public long getContentLength() { return this.delegate.getContentLength(); } public String getContentType() { return this.delegate.getContentType(); } public boolean isRepeatable() { return this.delegate.isRepeatable(); } public void writeRequest(final OutputStream out) throws IOException { this.delegate.writeRequest(new CountingOutputStream(out, this.listener)); } public static interface ProgressListener { void transferred(long num); } public static class CountingOutputStream extends FilterOutputStream { private final ProgressListener listener; private long transferred; public CountingOutputStream(final OutputStream out, final ProgressListener listener) { super(out); this.listener = listener; this.transferred = 0; } public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); this.transferred += len; this.listener.transferred(this.transferred); } public void write(int b) throws IOException { out.write(b); this.transferred++; this.listener.transferred(this.transferred); } } } </code></pre> <p>Then implements a ProgressListener which updates a progress bar.<br> Remember that the progress bar update must not run on the Event Dispatch Thread.</p>
<p>Look into <a href="http://hc.apache.org/httpclient-3.x/" rel="nofollow noreferrer">HTTP Client</a> for uploadign the file to the web. It should be able to to do that. I am unsure how to get the progress bar, but it would involve querying that API somehow.</p>
31,776
<p>With WSSv2 (SharePoint 2003) you could get the version of SharePoint you were working with</p> <p>e.g. <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spglobaladmin.version.aspx" rel="nofollow noreferrer">SPGloablAdmin.Version</a> gives you "12.0.0.6219" for <a href="http://www.mindsharpblogs.com/penny/articles/481.aspx" rel="nofollow noreferrer">WSSv3 SP1</a></p> <p>However its now obsolete (although still works). </p> <p>Does anyone know the WSSv3 (SharePoint 2007) equivalent?</p> <p>You have things like <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spwebservice_properties.aspx" rel="nofollow noreferrer">SPWebService.ContentService.Version</a> but that version number is just a timestamp and doesn't seem to relate back to build versions.</p>
<p>SPFarm.Local.BuildVersion would probably give you the same result without having to refer to a SPWebService.</p> <p>Cheers :)</p>
<p>As maxim said, but i included it in a Powershell script <a href="http://snipt.org/nLS/" rel="nofollow">http://snipt.org/nLS/</a></p>
35,656
<p>I'm interested in seeing what <strong>custom extensions other developers have created for the ASP.NET MVC HtmlHelper class</strong>. </p> <p>I think Microsoft got off to a <strong>great a start</strong>, but as usual, left a lot of <strong>open</strong> holes to fill! </p> <p>Looks like I am going to have to create some for rendering images, rendering action links as images, and so on. </p> <p>Thought it might be beneficial to actually <strong>put a list together and save some other developers some time and effort</strong>, and I'll be honest, save me some time as well. =) </p> <p>If you have any website links to other extension methods for the HtmlHelper class please provide them!</p>
<p>You should check the <a href="http://www.codeplex.com/MVCContrib" rel="nofollow noreferrer">MVC-Contrib</a> project on Codeplex...</p> <p>Also, I just found <a href="http://blogs.taiga.nl/martijn/archive/2008/08/27/paging-with-asp.net-mvc.aspx" rel="nofollow noreferrer">this</a> paging extension to the HtmlHelper which looks pretty cool, although I've not used it yet.</p>
<p>I made quite a few for a project I did at work. The ones that I can think off the top of my head were:</p> <p>ActionImage, which was the unholy love child of ActionLink and Image. ScriptBlock, which could write out a JavaScript script block based on some parameters from the ASP.NET. Textile, which would take a string marked up in <a href="http://en.wikipedia.org/wiki/Textile_%28markup_language%29" rel="nofollow" title="Textile markup language">Textile</a> markup and write out that markup as XHTML produced by a <a href="http://textilenet.codeplex.com/" rel="nofollow" title="Textile library">Textile library</a>.</p> <p>There were a few other more specific ones as well, but I think it's a really neat way of encapsulating blocks of tags.</p>
36,900
<p>Our current application is a single OpenGL EXE containing multiple pages. The EXE is responsible for accessing data sent across the network via UDP. It accumulates the data and stores it in a host of singleton structures. The individual pages within the EXE access the singleton structures to process the data as they see fit.</p> <p>In an attempt to lighten our EXE footprint and to support our attempts at configuration management, we have decided to split the pages out into a single DLL that the EXE will load. It is our intention to have the EXE be the shell into which the pages from the DLL will be loaded. The EXE will still have all communication responsibilities (UDP, Corba, User, etc). The pages will still be responsible for displaying whatever it is they do.</p> <p>The question (finally) becomes: How do I pass this myriad of data collected from the EXE down to the consuming DLL based pages. The Singleton concept no longer holds water as the singletons we use (ACE_Singleton) do not allow this level of direction. We can export singletons from the DLL to the consuming EXE all day long, but I have yet to figure out the reverse. I have come up with the following options - none of which I like, so I was hoping someone out there would have a better one :)</p> <ol> <li>Wrap up all the data that is currently stored in separate singletons into another DLL that would export a "true" singleton. Eg. The singleton exported from the DLL would be the same - no matter what EXE loaded it - sort of like shared memory. This is an intriguing choice but would cause problems down the line with our deployment scenarios. I could go into detail about those issues if folks are really smitten with this idea.</li> <li>Create a static DLL level structure that contains all the pertinent data. The EXE would push this data down to the DLL upon DLL load so that the pages contained within the DLL would have access to the data. This seems like the simplest solution - even if it entails editing every single page in our application - over 100. It also seems a bit sloppy. All the data is just in a global. Not very sexy or C++y either.</li> </ol> <p>So, anyone else out there have a solution for this problem?</p> <p>The application is written using Visual C++ 9.0 (VisualStudio 2008) for use on Windows XP. For some reason Vista is not supported in our lab yet - even though our customers are using it. </p>
<p>Give all the DLLs a function SetGlobalDataPointer(Singleton*). Your EXE calls this function before it calls any other DLL function. In the DLL code, replace all occurances of theSingleton. by theSingletonPtr-></p>
<p>You could either:</p> <ul> <li>put everything bar the very outermost shell into a 'common' DLL;</li> <li>use a DEF file to generate export functions from your EXE.</li> </ul> <p>The second is very uncommon but it is possible to generate an import library just from the DEF file. Use LIB /DEF to generate the import library. See <a href="http://msdn.microsoft.com/en-us/library/f0z8kac4(VS.85).aspx" rel="nofollow noreferrer">Working with Import Libraries and Export Files</a>.</p>
11,014
<p>I appreciate that there are now many mechanisms in dotnet to deal with XML in a myriad of ways... </p> <p>Suppose I have a string containing the XML....</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;root&gt; &lt;Element1&gt; &lt;Element1_1&gt; SomeData &lt;/Element1_1&gt; &lt;/Element1&gt; &lt;Element2&gt; Some More Data &lt;/Element2&gt; &lt;/root&gt; </code></pre> <p><strong>What is the simplest (most readable) way of removing Element1_1?</strong></p> <p>Update... I can use any .Net API available in .Net 3.5 :D </p>
<p>Which APIs are you able to use? Can you use .NET 3.5 and LINQ to XML, for instance? If so, <a href="http://msdn.microsoft.com/en-us/library/system.xml.linq.xnode.remove.aspx" rel="noreferrer">XNode.Remove</a> is your friend - just select Element1_1 (in any of the many ways which are easy with LINQ to XML) and call Remove() on it.</p> <p>Examples of how to select the element:</p> <pre><code>XElement element = doc.XPathSelectElement("/root/Element1/Element1_1"); element.Remove(); </code></pre> <p>Or:</p> <pre><code>XElement element = doc.Descendants("Element1_1").Single().Remove(); </code></pre>
<p>I'd use either this:</p> <pre><code>XmlDocument x = new XmlDocument(); x.LoadXml(SomeXmlString); foreach (XmlNode xn in x.SelectNodes("//Element1_1")) xn.ParentNode.RemoveChild(xn); </code></pre> <p>or the same with an explicit XPath:</p> <pre><code>foreach (XmlNode xn in x.SelectNodes("/root/Element1/Element1_1")) xn.ParentNode.RemoveChild(xn); </code></pre> <p>or, even more specific:</p> <pre><code>XmlNode xn = x.SelectSingleNode("/root/Element1/Element1_1"); xn.ParentNode.RemoveChild(xn); </code></pre>
27,281
<p>When we talk about the .NET world the CLR is what everything we do depends on. What is the minimum knowledge of CLR a .NET programmer must have to be a good programmer? Can you give me one/many you think is/are the most important subjects: GC?, AppDomain?, Threads?, Processes?, Assemblies/Fusion? </p> <p>I will very much appreciate if you post a links to articles, blogs, books or other on the topic where more information could be found.</p> <p>Update: I noticed from some of comments that my question was not clear to some. When I say CLR I don't mean .Net Framework. It is NOT about memorizing .NET libraries, it is rather to understand how does the execution environment (in which those libraries live on runtime) work. </p> <p>My question was directly inspired by John Robbins the author of "Debugging Applications for Microsoft® .NET" book (which I recommend) and colleague of here cited Jeffrey Richter at Wintellect. In one of introductory chapters he is saying that "...any .NET programmer should know what is probing and how assemblies are loaded into runtime". Do you think there are other such things? </p> <p>Last Update: After having read first 5 chapters of "CLR via C#" I must say to anyone reading this. If you haven't allready, read this book!</p>
<p>Most of those are way deeper than the kind of thing many developers fall down on in my experience. Most misunderstood (and important) aspects in my experience:</p> <ul> <li>Value types vs reference types</li> <li>Variables vs objects</li> <li>Pass by ref vs pass by value</li> <li>Delegates and events</li> <li>Distinguishing between language, runtime and framework</li> <li>Boxing</li> <li>Garbage collection</li> </ul> <p>On the "variables vs objects" front, here are three statements about the code</p> <pre><code>string x = "hello"; </code></pre> <ul> <li>(Very bad) <code>x</code> is a string with 5 letters</li> <li>(Slightly better) <code>x</code> is a reference to a string with 5 letters</li> <li>(Correct) The value of <code>x</code> is a reference to a string with 5 letters</li> </ul> <p>Obviously the first two are okay in "casual" conversation, but only if everyone involved understands the real situation.</p>
<p>Jon's answer is good. Those are all fairly basic but important areas that a lot of developers do not have a good understanding of. I think knowing the difference between value and reference types ties in to a basic understanding of how the GC in .NET behaves, but, more importantly, a good understanding of the Dispose pattern is important.</p> <p>The rest of the areas you mention are either very deep knowledge about the CLR itself or more advanced concepts that aren't widely used (yet). [.NET 4.0 will start to change some of that with the introduction of the parallel extensions and MEF.]</p>
38,522
<p>During the course of our application login there are several queries ran, all around validating the login. In evaluating them I noticed that one of the queries is run without the NOLOCK hint.</p> <p>There does not seem to be any particular danger of dirty read because the data would hardly ever change.</p> <p>Thinking about it from an attempted DOS type attack by somebody attempting failed logins over and over again I am suggesting that the lack of NOLOCK lowers our threshold for failure.</p> <p>I believe it is an extremely unlikely result of a DOS attack (I think the web server would go first) but adding NOLOCK should make it go from unlikely to impossible.</p> <p>So, am I being excessive or trivial?</p>
<p>Having NOLOCKs or not is the least of your worries with a DoS attempt against your server.</p> <p>I wouldn't sweat it.</p> <p>If, as you say, the data rarely changes, having the NOLOCKs there probably don't hurt.</p>
<p>Also a very rare case, but still: Just at the moment somebody deactivates the user to prevent them from logging in, NOLOCK lets them in. Could be a rogue user/hacker/employee who needs to be locked out immediately?</p> <p>You would have to be concerned about this particular scenario to forgo the performance advantage of NOLOCK.</p>
36,048
<p>When I use (in MS Access 2003 SP3): </p> <pre><code>SELECT * INTO NewTable FROM SomeQuery; </code></pre> <p>MEMO fields are converted to TEXT fields (which are limited to 255 characters), so longer texts are cut.</p> <p>The output of the query itself is fine and not truncated; the text is cut only in the new table that is created.</p> <p>An update: I managed to focus the problem on the IIF statement in my query. When I remove the IIF, the new table contains the MEMO field, but with the IIF the same field appears as TEXT. The weird thing is that the query output shows the long strings in full, even when the IIF is being used. Only when it is 'copied' to the new table (by the INTO statement), the text is cut.</p> <p>Do you know of any problems that IIF may cause to MEMO fields?</p> <p>Thank you for your answers.</p>
<p>You have here the <a href="http://allenbrowne.com/ser-63.html" rel="nofollow noreferrer">current workarounds</a> for avoiding any Truncation of Memo fields.</p> <p>In your case, that may be the result of the query's Properties Sheet including a "<code>set Unique</code>" Values to Yes (which forces comparison of Memo fields, triggering the truncation), or the Format property of the field, e.g. forcing display in upper case (<code>&gt;</code>) or lower case (<code>&lt;</code>).</p> <hr> <p>What Access are you using, and what format are you saving your document into ?</p> <p>In a Access 2000 compatible format, the cell are in <a href="http://support.microsoft.com/kb/208801" rel="nofollow noreferrer">Excel5.0/95 format</a>: 255 characters max.</p> <p>Do you have any other (non-Memo) field with lengthy value you could try to select, just to see if it also gets truncated ?</p> <hr> <p>If the output is fine, but the export in a new table does truncate the Memo fields, could you check the following:</p> <p><a href="http://www.access-programmers.co.uk/forums/archive/index.php/t-108089.html" rel="nofollow noreferrer">In the export dialog under advanced</a>, even though it looks like you can only inlude the name, if you click very carefully to expand column that don't appear, you can change the data type to memo.</p>
<p>SP3 of 2003 is notorious, it may be related to that. There is a hotfix:</p> <p><a href="http://support.microsoft.com/default.aspx/kb/945674" rel="nofollow noreferrer">http://support.microsoft.com/default.aspx/kb/945674</a></p>
48,893
<ol> <li><p>In a simple winform application, I call a function that endlessy create files on a button click event. I add Application.DoEvents() to the loop.</p></li> <li><p>I press the red X to close the form.</p></li> <li><p>the form closes, but files continue to be created ... </p></li> </ol> <p>I think its on the buttons thread, but shouldnt it be a background one ? trying changing Thread.CurrentThread.IsBackGround to True on the loop function does not help.</p> <p>Ideas ?</p>
<p>The fact that you're using <code>Application.DoEvents</code> is the first sign of a problem: it shows that you're doing too much in the UI thread. It's almost never appropriate in a well-structured program. The UI thread is not meant to have any long-running tasks. (Admittedly if it takes a long time to draw your UI you have little choice - but that suggests you should simplify your UI... and it's not applicable in this case, I suspect.)</p> <p>Instead, you should be performing the long-running task (creating the files) in a separate thread. <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="nofollow noreferrer">BackgroundWorker</a> is a perfect fit for this - you can use it to report progress back to the UI, and the UI can call <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancelasync.aspx" rel="nofollow noreferrer"><code>CancelAsync</code></a> method to request that it stops. You need to check the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancellationpending.aspx" rel="nofollow noreferrer"><code>CancellationPending</code></a> property from within the worker thread, to see whether cancellation has been requested, and stop appropriately.</p> <p>EDIT: Just to clarify what I believe is happening - I suspect your form is closing, but the program won't terminate until the event loop has finished. You're keeping the event loop going with your file-creation loop, hence the problem.</p> <p>Note that there isn't a thread for the button - there's just one for your whole UI. (In certain cases you may need more than one UI thread, but that's rare - and you'd know it if you'd done it.)</p>
<p>Did you specifially create a new thread for that ButtonClick code? If not, then it's on the same thread as the Form, so the "X" button <em>should</em> stop it.</p> <p>In either case, you could set a flag (isClosing), and check for that flag in your "while true" loop.</p>
32,449
<p>This is probably too much to ask, but is there any language that does a really terrific job of representing time and date operations? I'll grant straight away that it's <b>really hard</b> to write a truly great time library. That said, are there any widespread languages that have one? Basically, I want something that handles time and date as comprehensively as modern regular expression libraries do their jobs. Everything I've seen so far in Python and Java omits one or more pretty important pieces, or makes too many things hard.</p> <p>At least this should be intuitive to do:</p> <ul> <li>find the number of days between two given dates, number of minutes between two given minute periods, etc. </li> <li>add and subtract intervals from timestamps </li> <li>allow simple conversion between timezones, with Daylight Saving Time changes by region automatically accounted for (given that there's an accurate supporting database of regional settings available) </li> <li>get the period that a given timestamp falls into, given period granularity ("what calendar day is this date in?") </li> <li>support very general string-to-date conversions (given a pattern)</li> </ul> <p>Further, if there's a Java-style Calendar/GregorianCalendar setup, the general Calendar class should be accommodating toward subclasses if I need to roll my own Hebrew, Babylonian, Tolkien, or MartianCalendar. (Java Calendars make this pointlessly hard, for example.)</p> <p>I am completely language-agnostic here. It's fine if the thing chokes on computing ambiguous stuff like "how many minutes are there between 2002 and next Valentine's Day?"</p>
<p>How about <a href="http://msdn.microsoft.com/en-us/library/system.datetime_methods.aspx" rel="nofollow noreferrer">.NET's DateTime</a>? (You can pick your language within the framework)</p>
<p>Ruby has excellent support, actually. Check out <a href="http://www.developer.com/open/article.php/3729206" rel="nofollow noreferrer">this page</a>. Really great support for turning strings into dates, dates into strings, doing math on dates, parsing "natural language" strings like "3 months ago this friday at 3:45pm" into an actual date, turning dates into strings so you can do stuff like "Sam last logged in 4 days ago" or whatever...</p> <p>Very nifty.</p>
11,568
<p>I want to allow an Excel report to be viewed embedded in a WebPage... is there a way?</p> <ul> <li><p>I don't want to use an ActiveX, or OWC (Office Web Components), I just want to open an existing file from the internet explorer application.</p></li> <li><p>I don't want users to download and then open it.</p></li> </ul> <p>Using an iframe wouldn't be a problem, but my preliminary tests weren't successful</p> <p>Any ideas? Is it at all possible?</p>
<p>This has to do with the local person's browser set up and not really anything you can do on your end. If they click a link with the .xls(x) extension, the browser determines if it wants to open it itself or in a new window.</p> <p>Here 2 microsoft pages on how to change these settings:</p> <p><a href="https://support.microsoft.com/en-us/help/162059/how-to-configure-internet-explorer-to-open-office-documents-in-the-app" rel="nofollow noreferrer">http://support.microsoft.com/.../how-to-configure-internet-explorer-to-open-office-documents-in-the-app</a></p> <p><a href="https://support.microsoft.com/en-us/office/embed-your-excel-workbook-on-your-web-page-or-blog-from-sharepoint-or-onedrive-for-business-7af74ce6-e8a0-48ac-ba3b-a1dd627b7773" rel="nofollow noreferrer">http://support.microsoft.com/.../embed-your-excel-workbook-on-your-web-page-or-blog-from-sharepoint-or-onedrive-for-business</a></p>
<pre><code>&lt;iframe src="file:\\yourpath\yourfile.xls" width="100%" height="500"&gt;&lt;/iframe&gt; </code></pre>
20,320
<p>When executing the following (complete) SQL query on Microsoft SQL Server 2000:</p> <pre><code>SELECT B.ARTIFACTTNS, B.ARTIFACTNAME, B.ARTIFACTTYPE, B.INITIALBYTES, B.TIMESTAMP1, B.FILENAME, B.BACKINGCLASS, B.CHARENCODING, B.APPNAME, B.COMPONENTTNS, B.COMPONENTNAME, B.SCAMODULENAME, B.SCACOMPONENTNAME FROM (SELECT DISTINCT A.ARTIFACTTYPE, A.ARTIFACTTNS, A.ARTIFACTNAME FROM (SELECT DISTINCT ARTIFACTTYPE, ARTIFACTTNS, ARTIFACTNAME FROM CUSTPROPERTIES WHERE PNAME = 'AcmeSystemName' AND PVALUE = 'MyRuleGroup' UNION SELECT DISTINCT ARTIFACTTYPE, ARTIFACTTNS, ARTIFACTNAME FROM CUSTPROPERTIES WHERE PNAME = 'AcmeSystemDisplayName' AND PVALUE = 'MyRuleGroup') A, (SELECT DISTINCT ARTIFACTTYPE, ARTIFACTTNS, ARTIFACTNAME FROM CUSTPROPERTIES WHERE PNAME = 'AcmeSystemTargetNameSpace' AND PVALUE = 'http://MyModule') B WHERE A.ARTIFACTTYPE = B.ARTIFACTTYPE AND A.ARTIFACTTNS = B.ARTIFACTTNS AND A.ARTIFACTNAME = B.ARTIFACTNAME) A, BYTESTORE B WHERE (A.ARTIFACTTYPE = 'BRG') AND A.ARTIFACTTYPE = B.ARTIFACTTYPE AND A.ARTIFACTTNS = B.ARTIFACTTNS AND A.ARTIFACTNAME = B.ARTIFACTNAME ORDER BY ARTIFACTTYPE, ARTIFACTTNS, ARTIFACTNAME </code></pre> <p>I get the following exception:</p> <pre><code>java.sql.SQLException: [Acme][SQLServer JDBC Driver][SQLServer] Ambiguous column name 'ARTIFACTTYPE'. </code></pre> <p>What am I doing wrong here and how can I correct it?</p>
<p>Because <code>ARTIFACTTYPE</code> can refer to either <code>A.ARTIFACTTYPE</code> or <code>B.ARTIFACTTYPE</code> and the server needs to know which one you want, just change it to <code>A.ARTIFACTTYPE</code> and you should be okay in this case.</p> <p>To clarify, you need to specify the alias prefix any time the column name is ambiguous. It isn't bad practice to always use alias prefixes as it makes it clear which columns are coming from which tables when you read the query, and eliminates issues like this one.</p> <p>One might wonder why you need to distinguish between which of two columns you want when they both refer to the same column in the same table. The answer is that when you join a table to itself, the values from A.column and B.column may be different depending on the join criteria (such as may be the case with an outer join where values in one of the columns may be null).</p>
<p>To be clear, it is lines 13, 14 and 15 that have the ambiguous columns.</p>
41,091
<p>I'm trying to implement a unit test for a function in a project that doesn't have unit tests and this function requires a System.Web.Caching.Cache object as a parameter. I've been trying to create this object by using code such as...</p> <pre><code>System.Web.Caching.Cache cache = new System.Web.Caching.Cache(); cache.Add(...); </code></pre> <p>...and then passing the 'cache' in as a parameter but the Add() function is causing a NullReferenceException. My best guess so far is that I can't create this cache object in a unit test and need to retrieve it from the HttpContext.Current.Cache which I obviously don't have access to in a unit test.</p> <p>How do you unit test a function that requires a System.Web.Caching.Cache object as a parameter?</p>
<p>When I've been faced with this sort of problem (where the class in question doesn't implement an interface), I often end up writing a wrapper with associated interface around the class in question. Then I use my wrapper in my code. For unit tests, I hand mock the wrapper and insert my own mock object into it.</p> <p>Of course, if a mocking framework works, then use it instead. My experience is that all mocking frameworks have some issues with various .NET classes.</p> <pre><code>public interface ICacheWrapper { ...methods to support } public class CacheWrapper : ICacheWrapper { private System.Web.Caching.Cache cache; public CacheWrapper( System.Web.Caching.Cache cache ) { this.cache = cache; } ... implement methods using cache ... } public class MockCacheWrapper : ICacheWrapper { private MockCache cache; public MockCacheWrapper( MockCache cache ) { this.cache = cache; } ... implement methods using mock cache... } public class MockCache { ... implement ways to set mock values and retrieve them... } [Test] public void CachingTest() { ... set up omitted... ICacheWrapper wrapper = new MockCacheWrapper( new MockCache() ); CacheManager manager = new CacheManager( wrapper ); manager.Insert(item,value); Assert.AreEqual( value, manager[item] ); } </code></pre> <p>Real code</p> <pre><code>... CacheManager manager = new CacheManager( new CacheWrapper( HttpContext.Current.Cache )); manager.Add(item,value); ... </code></pre>
<pre><code>var httpResponse = MockRepository.GenerateMock&lt;HttpResponseBase&gt;(); var cache = MockRepository.GenerateMock&lt;HttpCachePolicyBase&gt;(); cache.Stub(x =&gt; x.SetOmitVaryStar(true)); httpResponse.Stub(x =&gt; x.Cache).Return(cache); httpContext.Stub(x =&gt; x.Response).Return(httpResponse); httpContext.Response.Stub(x =&gt; x.Cache).Return(cache); </code></pre>
30,289
<p>The link over here lists ([http://www.yoda.arachsys.com/csharp/singleton.html][1]) some singleton patterns in C#. The article also describes the obvious that a singleton is not meant to accept parameters which “as otherwise a second request for an instance but with a different parameter could be problematic”. This means that any parameters you need to get the class working should be induced as a property. </p> <p> I am curious to know if there are any parameterized singleton design patterns out there. Accepting values as a property does not enforce anything to the consumer. </p>
<p>Based on your question, it seems you may be looking at an Abstract Factory pattern (creates an instance of several families of classes) that keeps an internal list/dictionary of classes that have already been instantiated, thus mimicking the singleton pattern functionality.</p> <p>You would then use this factory class to request an object based on parameters you've passed in, and if it exists in its internal list it gets returned, and if not, a new instance is created and then added to the list and returned.</p>
<blockquote> <p>his means that any parameters you need to get the class working should be induced as a property.</p> </blockquote> <p>Ideally singleton class should not depend on external code. </p> <p>In case when you need to provide additional information to singleton constructor, you can just create a pool of objects.</p> <p>It can be a simple list or any other suitable data structure. You will need to make it thread-safe (if it matters) and guarantee that there will not be multiple objects instantiated with the same parameters.</p> <p>Basically you will have a class factory. It will return the same object for the same parameters.</p> <p>In this case you will have N singleton objects - i.e. objects with different state will be treated as completely different instances.</p> <p>You can find examples of such singletons in Inversion of Controls containers. </p> <p>For example you can have some service that depends on other services. When you call container.Get(type of service). DI container will automatically initialize service instance with required parameters and return it to caller. But this service instance becomes singleton - you will not be able to create another service with the same parameters.</p>
18,285
<p>Is there any technology out there that will allow you to do side-by-side updates of production schemas?</p> <p>The goal is to have zero down time when applying updates to a schema in production. Weblogic 10 has a similar feature for their Java EE apps where by you deploy the new version of the app and new connections go to the new app, while the existing connections continue to the old app. When all the old connections complete/timeout, the old app is retired and the new app continues on...zero down time. </p> <p>Is there something similar in Oracle?</p>
<p>Yes. There is online redefinition package.</p> <p><a href="http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_redefi.htm#CBBJJAIF" rel="nofollow noreferrer">DBMS_Redefinition</a></p> <p>But I doubt this will give you zero downtime, this doesn't account for every possible change to a schema. This lets you do some table changes. I think you need to define zero and how extensive the changes you want to make. Usually if you change the database, you have to change your client as well. If you changed your database, how would the client switch automatically from the old proc signature to the new proc signature - Instantaneously?</p> <p>Databases don't work like apps. There either is a FK from tableA to tableB or there isn't... it can't not be there for current connection and exist only for new connection in the same manner as your application can. Databases just aren't the same. </p> <p>That being said, there is rumor that Oracle is working on package versioning... so you could connect to a specific version of a package to make such a migration simpler. But again... that would work for packages, DBMS_redef would work for tables... but that's not the sum total of your database.</p>
<p>Depends what you mean, or include, in "schema". If you want to add or drop an index, that can be done "in-flight", although it will require a lock which may halt activity for a time. In the latest Oracle versions, it doesn't need to hold the lock for the entire time it takes to build the index, just for a moment to lock in the change. If you have short-duration transactions it shouldn't be noticeable. In some cases that applies to tables as well (eg adding a nullable or default column).</p> <p>If you use PL/SQL (especially packages), things can be a little more complicated. Enhancements were mooted for 11gR1 to enable the in-flight application upgrade, but it got pushed out and is now expected in 11gR2 (probably out first half next year). In the meantime, a workaround is a multi-schema solution. Say your data sits in one schema ("yellow") and your current application code is running in "blue" schema, you load your new application into "green schema". You switch your connections, one by one, from blue to green. Once your connections are all using "green", you can retire "blue" until your next upgrade (when "blue" becomes the new app and "green" is retired).</p> <p>If you have a genuine 24/7 system, you'll probably always have to stage some upgrades. For example, add a new column as optional, upgrade the application to set it, then make it mandatory (possibly with some data change script for pre-existing rows).</p>
33,798
<p>What is the best way to do cross-platform handling of hidden files? (preferably in Python, but other solutions still appreciated)</p> <p>Simply checking for a leading '.' works for *nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hiding things (.hidden files, etc.). Is there a standard way to deal with this?</p>
<p>Here's a script that runs on Python 2.5+ and should do what you're looking for:</p> <pre><code>import ctypes import os def is_hidden(filepath): name = os.path.basename(os.path.abspath(filepath)) return name.startswith('.') or has_hidden_attribute(filepath) def has_hidden_attribute(filepath): try: attrs = ctypes.windll.kernel32.GetFileAttributesW(unicode(filepath)) assert attrs != -1 result = bool(attrs &amp; 2) except (AttributeError, AssertionError): result = False return result </code></pre> <p>I added something similar to has_hidden_attribute to <a href="https://bitbucket.org/jaraco/jaraco.windows" rel="noreferrer">jaraco.windows</a>. If you have jaraco.windows >= 2.3:</p> <pre><code>from jaraco.windows import filesystem def has_hidden_attribute(filepath): return filesystem.GetFileAttributes(filepath).hidden </code></pre> <p>As Ben has pointed out, on Python 3.5, you can use the stdlib:</p> <pre><code>import os, stat def has_hidden_attribute(filepath): return bool(os.stat(filepath).st_file_attributes &amp; stat.FILE_ATTRIBUTE_HIDDEN) </code></pre> <p>Though you may still want to use jaraco.windows for the more Pythonic API.</p>
<p>"Is there a standard way to deal with this?" Yes. Use a standard (i.e., POSIX-compliant) OS.</p> <p>Since Windows is non-standard -- well -- there's no applicable standard. Wouldn't it be great if there was? I feel your pain.</p> <p>Anything you try to do that's cross-platform like that will have Win32 oddities.</p> <p>Your solution is -- for the present state of affairs -- excellent. At some point in the future, Microsoft may elect to write a POSIX-compliant OS. Until then, you're coping well with the situation.</p>
36,046
<p>I have a COM <code>.dll</code> registered successfully with <code>regsvr32</code> but somehow <code>CoCreateInstance()</code> fails to create one of its interfaces. Is there a freeware tool which can determine the reason for the failure?</p>
<p>First of all, check the return value of the CoCreateInstance() call. Second, you can use a tool like Regmon or Process Monitor to see what registry lookup fails. This way, you can quickly determine what exactly wasn't registered the way you'd expect it to be. </p>
<p>If your com dll is implemented in C++ &amp; has debug info, you could also try debugging with MSVC to step into CoCreateInstance.</p> <p>My guess is that you missed associating your class with one of the interfaces properly. I've done that a number of times by mistake. If you're using ATL you need to make sure your implementing class derives from the interface &amp; also you have added <code>COM_INTERFACE_ENTRY(I____)</code> for your interface in the COM_MAP:</p> <pre><code>BEGIN_COM_MAP(CFileHelper) COM_INTERFACE_ENTRY(IFileHelper) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IStream) COM_INTERFACE_ENTRY(ISupportErrorInfo) END_COM_MAP() </code></pre> <p>Or maybe the GUID differs between the IDL file and what's in the implementing C++ file. MSVC6 has an annoying bug where if the wizard fails to create a new class because of file permissions (e.g. some of the files it wants to change are read-only) but it has already added a GUID to the IDL file, and you fix the file permissions and go to do it again, there will be an inconsistency in the GUIDs and it's a pain to catch this. In an ideal world, the GUID definitions would reside ONLY in one file and then you wouldn't have to worry about this.</p> <p>If not that, sometimes there are weird errors regarding marshaling &amp; apartments but that only pops up if you've got multiple threads and are sending interface pointers across thread or interface boundaries.</p>
42,848
<p>I'm stuck in .NET 2.0 Windows Forms.</p> <p>It doesn't look like the ability to select multiple nodes exists in the standard <code>TreeView</code> control.</p> <p>I'm trying to do this for a context menu selection. So check boxes aren't an acceptable UI paradigm here.</p> <p>What's the best way to provide that very necessary functionality?</p>
<p>We did this in a WTL project once, but the basic work needed is the same for .NET. To achieve a multiple selection tree control, you will need to draw the tree items yourself and override the keyboard and mouse handling. You will also need to maintain your own list of items that are selected.</p> <p>Don't forget to consider selection rules (are parents and children allowed, for example), and don't forget to implement the keyboard shortcuts including selection using Ctrl, Shift, and Ctrl+Shift, as well as the Spacebar for selecting/deselecting.</p>
<p>You might look at a 3rd party solution. The <a href="http://www.infragistics.com" rel="nofollow noreferrer">Infragistics</a> tree does this. Not free, but the time spent trying to find a solution isn't really free, either.</p>
25,248
<p>I want to be able to run unstrusted ruby code. I want to be able to pass variables to said untrusted code that it may use. I also want said code to return a result to me. Here is a conceptual example of what I am thinking</p> <pre><code>input = "sweet" output = nil Thread.start { $SAFE = 4 #... untrusted code goes here, it uses the input variable(s) #to calculate some result that it places in the output variable } #parse the output variable as a string. </code></pre> <p>Just to clarify, I am basically using the untrusted code as a function. I want to provide its some inputs, and then allow it to write to the output. That is all I really want, I don't care how it is done, I just want the ability to use untrusted Ruby code as a sort of function. The solution does not have to look anything like the code I wrote above, I am just using it to illustrate what I want.</p> <p>Now, I can currently think of 3 ways to do this:</p> <ol> <li>Use the $SAFE level construct above.</li> <li>whytheluckystiff has a Sandbox plugin for ruby</li> <li>I could run each function in its own virtual machine, using some sort of os virtualization software like vmware or Xen or something.</li> </ol> <p>I am wondering if anyone has any recommendations for running untrusted ruby code in a functional way? What option would you recomend? How would you go about it? Thanks.</p>
<p>$SAFE is not enough; you need to be at least at the level of Why's freaky sandbox. However, I don't know if that sandbox code is actively maintained or if he/they ever solved the holes such as infinite loops, etc.</p> <p>Unsafe generally means hostile. If you can relax from hostile to, say, 'naive', and depending upon the requirements of your app, you might get away with sandboxing in Ruby. It's not really a first-class scenario in the language design.</p> <p>Even with that, though, you probably don't need to go to the machine level of separation. I'd feel pretty safe using a sandbox in a separately spawned process, with your app functioning as a process manager to kill off any that manage to hang/flame. Now, that is a few orders of magnitude more work than your simple block above.</p> <p>But remember and keep repeating, "SAFE can't deal with hostile".</p>
<p>I'd strongly recommend just using JRuby.</p> <p>The JVM has had a very strong security model built in from the beginning, and JRuby piggy-backs off that. You can restrict access to files, restrict loading of code, and much more. It's <em>far</em> better than anything that exists in native Ruby impls, and there are a number of sites that run sandboxed, user-accessible sites atop JRuby for exactly this purpose.</p>
20,438
<p>I have a CC.NET project configured to call a common NAnt build file, which does some stuff, and then calls a child NAnt build file. The child build file name is specified by CC.NET to the command build file using a property.</p> <p>The hurdle that I am trying to get over is that the common build file log gets overwritten by the child build file log, so I don't get the common build log in the CC.NET build log.</p> <p>Anyone have any ideas on how to fix this?</p> <p>I thought about changing the child build's log, but reading up on the NAnt <code>&lt;nant&gt;</code> task doesn't allow me to change the child's output log.</p>
<p>Use the <a href="http://nant.sourceforge.net/release/0.85-rc1/help/tasks/nant.html" rel="nofollow noreferrer">nant task</a>, so you get one single build file.</p>
<p>Is there any way that you could <em>include</em> the child nant file as opposed to executing it as a full-fledged child nant project? This would prevent the overwrite, but not sure if it's possible in your situation.</p>
4,345
<p>I made an array in PHP which holds a bucnh of unix timestamps.</p> <p>I'm trying to make a function that will return an array containing the indexes of the 3 largest numbers in that array.</p> <p>For instance, if the largest numbers are located at indexes 3,5 and 8</p> <p>And if the largest is 5, second largest is 8 and smallest of the three is number 3, I want an array that holds the values (5,8,3) in that order.</p> <p>And frankly, I don't have a clue how to pull this off. Does anybody know how to do this?</p>
<p>You could use <a href="http://uk3.php.net/manual/en/function.asort.php" rel="nofollow noreferrer">asort</a> to sort the array and maintain index and then use <a href="http://uk3.php.net/manual/en/function.array-slice.php" rel="nofollow noreferrer">slice</a> along with the 4th parameter, again to maintain the index, to grap the top x number of elements you are after, and finally use <a href="http://uk3.php.net/manual/en/function.array-keys.php" rel="nofollow noreferrer">array_keys</a>.</p> <p>There may well be a quicker way, but it's just to show there are plenty of PHP array functions to help you achieve the effect you're looking for.</p>
<p>In PHP code:</p> <pre><code>function threeLargest($array){ krsort($array, "SORT_NUMERIC"); $return[0] = $array[0]; $return[1] = $array[1]; $return[2] = $array[2]; return $return; } </code></pre>
45,252
<p>I just installed Ganymede and am exploring an old project in it. All of my JSPs are giving me weird validation errors. I'm seeing stuff like - </p> <pre><code>Syntax error on token "}", delete this token Syntax error on token "catch", Identifier expected Syntax error, insert "Finally" to complete TryStatement </code></pre> <p>I'm doing best practice stuff here, no scriplets or anything, so I think that Eclipse is incorrectly applying a Java class validator to my JSPs. Any idea on how to stop that from happening?</p> <p>Under Options/Editors/File Associations I have the following for JSPs:</p> <pre><code>JSP Editor (default) Web Page Editor Text Editor CSS JSP Editor </code></pre> <p>Am I missing something?</p> <p>Also I think this is correct, but just in case it's not, here is my page directive - </p> <pre><code>&lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt; </code></pre>
<p>I actually found out what my problem was through the <a href="http://www.eclipse.org/newsportal/article.php?id=17447&amp;group=eclipse.webtools#17447" rel="noreferrer">eclipse webtools usergroup</a>. The issue for me was the use of the Spring form custom tag library. If you self-close the tag... </p> <pre><code>&lt;form:errors path="*" /&gt; </code></pre> <p>...then you get the goofy JSP validation error. If you close the tag as if there was body content...</p> <pre><code>&lt;form:errors path="*"&gt;&lt;/form:errors&gt; </code></pre> <p>Then the error goes away. I need to follow-up with a bug for the Ganymede team.</p>
<p>I have the same issue. Whatever JSP editor is in Ganymede does not like my if/else scriptlets:</p> <pre><code>&lt;% if(message != null) { %&gt; &lt;p id="message"&gt;&lt;%=message %&gt;&lt;/p&gt; &lt;% } else { %&gt; &lt;p&gt;Please login to view your account information.&lt;/p&gt; &lt;% } %&gt; </code></pre> <p>It tells me:</p> <pre><code>Syntax error on token "}", delete this token Syntax error on token "catch", Identifier expected Syntax error, insert "Finally" to complete TryStatement </code></pre> <p>...on the final closing brace. I have the same file associations as the original poster. I suppose I will try to find another JSP editor in the WTP toolkit, but I was under the impression that came with my build.</p>
17,375
<p>How would one go about capturing users keystrokes in the SMS composer on the Symbian OS, specifically for a Nokia N73 (or any of the symbian supported devices <a href="http://en.wikipedia.org/wiki/Symbian_OS#Devices_that_have_used_the_Symbian_OS" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Symbian_OS#Devices_that_have_used_the_Symbian_OS</a>)? I'm new to symbian development and I'm trying to write an application to analyse writing styles of those who send SMSs. Any information (or push in the right direction) would be great.</p> <p>Many Thanks,</p> <p>A</p>
<p>Actually, you can capture keystrokes destined for any application in Symbian OS. <code>RWindowGroup::CaptureKey()</code> and <code>RWindowGroup::CaptureLongKey()</code> allow your executable to capture keys from any applicaton, whether yours is in the foreground or not. However, in this case this may prove to be tedious - these two functions work by capturing specific key codes and modifier combinations, so you would have to set up a lot of captures to deal with all the key combinations in the SMS composer.</p> <p>You would also have to pass the event on to the SMS composer once your exectuable had captured it. Whilst nominally possible using <code>RWsSession::SendEventToWindowGroup()</code> or <code>TApaTask::SendKey()</code>, there are complexities involved the events arrive in right order (i.e. key down, key event, key up) and behaviour of different FEPs (Front End Processors) for user input.</p> <p>So whilst it is nominally feasible to do what you require as above, it would prove to be tedious to implement and test, bordering on the risky. If all you want to do is analyse writing style to collect data (rather than in a product app), you might be better off writing your own SMS composer - there are plenty of examples on the Forum Nokia web site of editors and SMS sending.</p>
<p>Well, there are several levels to answering to your question.</p> <ul> <li><p>The keystrokes are actually captured by the message editor application. So, either it provides an API to feed you all its keystrokes (you can look for one on <a href="http://forum.nokia.com" rel="nofollow noreferrer">http://forum.nokia.com</a>. You'll find the message editor API but it will be mostly about re-using GUI controls and not what you're looking for) or you would need a transparent application of your own that stays in the foreground and captures keystrokes before feeding them back to whatever application happens to be right behind. Fortunately (for obvious security reasons), Symbian OS will not allow you to do the later.</p></li> <li><p>You can, however, have your own application read messages when they are saved in the phone memory: when they are saved in the Draft folder or in the SMS Outbox.</p></li> </ul> <p>The obligatory shameless plug: I would advise reading the messaging chapter of <a href="http://www.quickrecipesonsymbianos.com" rel="nofollow noreferrer">http://www.quickrecipesonsymbianos.com</a> in order to understand how to use the Symbian Message Store</p> <p>The classes of interest in your case are : CmsvEntry, CMsvSession, MMsvSessionObserver, CMsvOperation and CSmsClientMtm.</p>
30,167
<p>Is there a simple way in .NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL:</p> <p><code>http://www.mywebsite.com:80/pages/page1.aspx</code></p> <p>I need to return:</p> <p><code>http://www.mywebsite.com:80</code></p> <p>I know I can use <code>Request.Url.AbsoluteUri</code> to get the complete URL, and I know I can use <code>Request.Url.Authority</code> to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string.</p> <p>Any suggestions?</p>
<p>The following (C#) code should do the trick</p> <pre><code>Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx"); string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port; </code></pre>
<p>In my case</p> <pre><code>Uri uri = new Uri(&quot;http://www.mywebsite.com:80/pages/page1.aspx&quot;); string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Authority; </code></pre> <p>works to get</p> <p><a href="https://www.mywebsite.com:80" rel="nofollow noreferrer">https://www.mywebsite.com:80</a></p>
4,176
<p>I have a file with data listed as follows:</p> <pre><code>0, 2, 10 10, 8, 10 10, 10, 10 10, 16, 10 15, 10, 16 17, 10, 16 </code></pre> <p>I want to be able to input the file and split it into three arrays, in the process trimming all excess spaces and converting each element to integers.</p> <p>For some reason I can't find an easy way to do this in c++. The only success I've had is by inputting each line into an array, and then regexing out all the spaces and then splitting it up. This entire process took me a good 20-30 lines of code and its a pain to modify for say another separator(eg. space), etc.</p> <p>This is the python equivalent of what I would like to have in C++:</p> <pre><code>f = open('input_hard.dat') lines = f.readlines() f.close() #declarations inint, inbase, outbase = [], [], [] #input parsing for line in lines: bits = string.split(line, ',') inint.append(int(bits[0].strip())) inbase.append(int(bits[1].strip())) outbase.append(int(bits[2].strip())) </code></pre> <p>The ease of use of doing this in python is one of the reasons why I moved to it in the first place. However, I require to do this in C++ now and I would hate to have to use my ugly 20-30 line code.</p> <p>Any help would be appreciated, thanks!</p>
<p>There is really nothing wrong with fscanf, which is probably the fastest solution in this case. And it's as short and readable as the python code:</p> <pre><code>FILE *fp = fopen("file.dat", "r"); int x, y, z; std::vector&lt;int&gt; vx, vy, vz; while (fscanf(fp, "%d, %d, %d", &amp;x, &amp;y, &amp;z) == 3) { vx.push_back(x); vy.push_back(y); vz.push_back(z); } fclose(fp); </code></pre>
<p>If you want to be able to scale to harder input formats, you should consider spirit, boost parser combinator library.</p> <p><a href="http://www.boost.org/doc/libs/1_37_0/libs/spirit/classic/doc/quick_start.html" rel="nofollow noreferrer">This page</a> has an example which almost do what you need (with reals and one vector though)</p>
33,542
<p>I've got a list of links which have a click event attached to them, I need to get the ID from the child A link. So in the example below if I clicked the first list element I'd need google retuned. </p> <p>I've tried <code>'$this a'</code> but can't quite work out the syntax.</p> <pre><code>$("ul li").click(function(event){ $("input").val($(this).html()); }); </code></pre> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;a href="http://www.google.com" id="google"&gt;Google&lt;/a&gt; &lt;/ul&gt; </code></pre>
<p>I don't see the sample HTML but </p> <pre><code>$(this).find('a:first').attr('id') </code></pre> <p>would do it (fix <em>a:first</em> selector if it's not what you meant)</p> <p><strong>this</strong> refer to the element that fired your event</p>
<p>You could use the <a href="http://docs.jquery.com/Traversing/children" rel="nofollow noreferrer"><code>children</code></a> method:</p> <pre><code>$(this).children('a').eq(0).attr('id'); </code></pre> <p>I'm not sure about the syntax, but something like this should work.</p>
46,879
<p>Is there anyway how to check which website is being used with that pool without browsing each website and checks its assigned pool?</p> <p>I have approximately 35 websites and I can't afford browsing the websites one by one....</p> <p>Thanks</p>
<p>I won't create one class to handle in- and output - one class, one responsibility. I would like two filter streams, one for input/decryption and one for output/encryption:</p> <pre><code>InputStream decrypted = new DecryptingStream(inputStream, decryptionParameters); ... OutputStream encrypted = new EncryptingStream(outputSream, encryptionOptions); </code></pre> <p>They may have something like a lazy init mechanism reading the envelope before first <code>read()</code> call / writing the envelope before first <code>write()</code> call. You also use classes like Message or MessageEnvelope in the filter implementations, but they may stay package protected non API classes.</p> <p>The processing will know nothing about de-/encryption just working on a stream. You may also use both streams for input and output at the same time during processing streaming the processing input and output.</p>
<p>Can you split the body at arbitrary locations? </p> <p>If so, I would have two threads, input thread and output thread and have a concurrent queue of strings that the output thread monitors. Something like:</p> <pre><code>ConcurrentLinkedQueue&lt;String&gt; outputQueue = new ConcurrentLinkedQueue&lt;String&gt;(); ... private void readInput(Stream stream) { String str; while ((str = stream.readLine()) != null) { outputQueue.put(processStream(str)); } } private String processStream(String input) { // do something return output; } private void writeOutput(Stream out) { while (true) { while (outputQueue.peek() == null) { sleep(100); } String msg = outputQueue.poll(); out.write(msg); } } </code></pre> <p>Note: This will definitely not work as-is. Just a suggestion of a design. Someone is welcome to edit this. </p>
47,344
<p>I have been programming in Perl, off and on, for years now, although only sporadically is it my primary language. Because I often go months without writing any perl, I rely heavily on my dog-eared Camel Book to remind me how to do things. However, when I copy recipes verbatim with no understanding, this bothers me. This is one of the most vexing: On page 154 of the 3rd edition Camel, there is an example for "modifying strings <em>en passant</em>, which reads like this:</p> <pre><code>($lotr = $hobbit) =~ s/Bilbo/Frodo/g; </code></pre> <p>Q1) what is going on here? On what, exactly, is the regex operating?</p> <p>Q2) Is this near-magical syntax necessary for such a basic operation as "take a string from $a, modify it with a regex, place result in $b"?</p> <p>Q3) How do I do this operation using the loop default variable as the initial string?</p> <p>Apologies in advance to Perl dreamers for whom the above looks perfectly natural.</p>
<p>Hmmm... <code>($lotr=$hobbit) =~ s/Bilbo/Frodo/g</code> is one of the many magicks of Perl. Now for some answers.</p> <p>Q1) <code>$lotr</code> is being assigned the value contained in <code>$hobbit</code>. After the assignment, we can forget about the source variable. Treat <code>($lotr = $hobbit)</code> as it's own statement as-if we had written:</p> <pre><code>$lotr = $hobbit; $lotr =~ s/Bilbo/Frodo/g; </code></pre> <p>instead. The regex is operating on <code>$lotr</code>.</p> <p>Q2) The syntax is simply a one-line version of the snippet given above. Think of it as "copy the string from <code>$a</code>, copy it into <code>$b</code>, and modify <code>$b</code> with the regex" instead of "take a string from <code>$a</code>, modify it with a regex, place result in <code>$b</code>"</p> <p>Q3) I'm assuming that you mean the default pattern searching space by "loop default variable"? In that case, just use <code>$_</code> instead of <code>$hobbit</code>:</p> <pre><code>while (&lt;&gt;) { chomp; ($lotr = $_) =~ s/Bilbo/Frodo/g; print "\$lotr = [$lotr]\n"; print "\$_ = [$_]\n"; } </code></pre> <p>Interestingly enough, the magic var <code>$_</code> is not modified by this operation. This is how you can conclude that the assignment happens <em>before</em> the regex substitution and that the substitution does not interact on the default pattern space in any way.</p> <p>And for the experienced Perl programmers thing... I don't know too many people that are thrown by some piece of Perl syntax regardless of how long they have been staring at it 'cept Mr. Schwartz of course ;)</p>
<p>If in Q2 you mean to take a sub-string from $a, you might find this idiom useful:</p> <pre><code>($b) = $a =~ /(substring-to-match)/; $b =~ s/regex-on-susbtring/result-string/; </code></pre> <p>Also do note that $a and $b are not normal variables in Perl since they have special scope rules related to the sort function. See 'perldoc perlvar' for details.</p>
45,162
<p>According to the help file that comes with the Spring.NET framework, you can inject a dependancy defined in the local file by using an 'idref' tag along with a 'local' attribute. </p> <p>I have been trying to do this with no success and was hoping someone had the experience to help me out. </p> <p>Below I have a snippet from the config where I am passing it as a constructor argument, but I have tried setting it as a property as well. Both methods seem to yield the same error.</p> <pre><code>&lt;object id="theTargetObject" type="TestClassLibrary.TargetObject, TestClassLibrary"/&gt; &lt;object id="theClientObject" type="TestClassLibrary.ClientObject, TestClassLibrary"&gt; &lt;constructor-arg name="myClass"&gt; &lt;idref local="theTargetObject"/&gt; &lt;/constructor-arg&gt; &lt;/object&gt; </code></pre> <p>Error creating context 'spring.root': Error creating object with name 'theClientObject' defined in 'file [C:\Test\TestApp\bin\Debug\my.config.xml]' : Unsatisfied dependency expressed through constructor argument with index 0 of type [TestClassLibrary.TargetObject] : Could not convert constructor argument value [theTargetObject] to required type [TestClassLibrary.TargetObject] : Cannot convert property value of type [System.String] to required type [TestClassLibrary.TargetObject] for property ''.</p>
<p>I guess gef was on the right way but accidentially mixed it up when pasting the snippet.You are looking for the <a href="http://www.springframework.net/docs/1.2.0/reference/html/objects.html#objects-ref-element" rel="nofollow noreferrer">&lt;ref&gt; element</a>:</p> <pre><code>&lt;object id="theTargetObject" type="TestClassLibrary.TargetObject, TestClassLibrary"/&gt; &lt;object id="theClientObject" type="TestClassLibrary.ClientObject, TestClassLibrary"&gt; &lt;property name="myClass"&gt; &lt;ref local="theTargetObject"/&gt; &lt;/property&gt; </code></pre> <p></p> <p>the shorthand notation for this is:</p> <pre><code>&lt;object id="theClientObject" type="TestClassLibrary.ClientObject, TestClassLibrary"&gt; &lt;property name="myClass ref="theTargetObject"/&gt; </code></pre> <p>hth, Erich</p>
<p>Please view the post <a href="http://forum.springsource.org/showthread.php?t=14211" rel="nofollow noreferrer">http://forum.springsource.org/showthread.php?t=14211</a></p>
33,910
<p>How do I use PowerShell to stop and start a "Generic Service" as seen in the Microsoft "Cluster Administrator" software?</p>
<p>You can also use WMI. You can get all the Generic Services with:</p> <pre><code>$services = Get-WmiObject -Computer "Computer" -namespace 'root\mscluster' ` MSCluster_Resource | Where {$_.Type -eq "Generic Service"} </code></pre> <p>To stop and start a service:</p> <pre><code>$timeout = 15 $services[0].TakeOffline($timeout) $services[0].BringOnline($timeout) </code></pre>
<p>It turns out the answer is to simply use the command line tool CLUSTER.EXE to do this:</p> <p>cluster RES MyGenericServiceName /OFF</p> <p>cluster RES MyGenericServiceName /ON</p>
13,887
<p>I have been using Solidworks and AutoCAD to create STL file of a 3D model I want to print. I slice the STL file using Freesteel Z level slicer (<a href="http://www.freesteel.co.uk/wpblog/slicer/" rel="nofollow">http://www.freesteel.co.uk/wpblog/slicer/</a>) and save the slices in a bmp format. </p> <p>My 3d print has an array of circular channels, all of one radius. I expected the bmp slice to contain the circular shapes looking exactly identical to each other. However, I don't obtain the exact same replicas. Looks like the pixel-wise mapping has not been done uniformly. (View <a href="http://s24.postimg.org/p7w09zvkl/snippet.png" rel="nofollow">http://s24.postimg.org/p7w09zvkl/snippet.png</a> for the image). </p> <p>I want each and every circle to be represented by exactly the same set of pixels in the bmp image, so that all of the circular contours are identical. (I do not prefer changing the pixel resolution.)</p> <p>How can I overcome this problem? Are there any better tools which would lead to a perfectly uniform pixel-wise mapping? </p> <p>Thanks! </p> <p>PJ </p>
<p>Your objective has a serious constraint regarding the pixel resolution. Within that limitation, the software (slicer) you are using will generate "best guess" images, particularly dependent on floating point math. There may be a single combination of circular shapes (radius) and spacing for these shapes that provides your objective, but that's likely not a practical exercise.</p> <p>You have not indicated if you've tried other slicers, which would be the primary direction. A list of choices can be found here:</p> <p><a href="https://all3dp.com/best-3d-printing-software-tools/" rel="nofollow">Free Slicing Program List</a></p> <p>Another option that you can consider, not included in this list, is to use OpenSCAD, import the STL file, then use the projection() command to manually slice and export the image file. I use the term "manually" but the program can be coded to perform this task automatically, and there is a command line feature to OpenSCAD that may be useful.</p> <p>Note also that the output of these slicers and/or OpenSCAD may exceed the resolution you desire. Manipulation of the image with a graphics editor could result in the same floating point disarray as you perform the changes.</p>
<p>Your objective has a serious constraint regarding the pixel resolution. Within that limitation, the software (slicer) you are using will generate "best guess" images, particularly dependent on floating point math. There may be a single combination of circular shapes (radius) and spacing for these shapes that provides your objective, but that's likely not a practical exercise.</p> <p>You have not indicated if you've tried other slicers, which would be the primary direction. A list of choices can be found here:</p> <p><a href="https://all3dp.com/best-3d-printing-software-tools/" rel="nofollow">Free Slicing Program List</a></p> <p>Another option that you can consider, not included in this list, is to use OpenSCAD, import the STL file, then use the projection() command to manually slice and export the image file. I use the term "manually" but the program can be coded to perform this task automatically, and there is a command line feature to OpenSCAD that may be useful.</p> <p>Note also that the output of these slicers and/or OpenSCAD may exceed the resolution you desire. Manipulation of the image with a graphics editor could result in the same floating point disarray as you perform the changes.</p>
258
<p>In the build log I'd like to the start and end time of each project's compilation. Is there any way to get VS to do this?</p>
<p>For VC++ builds you can enable build timing. Go to Tools->Options->Projects and Solutions->VC++ Project settings and choose the option for 'Build Timing'</p>
<p>Not without modifying the actual project file (using a text editor) to add calls in to the MSBuild script targets.</p>
6,866
<p>Is it possible, in Windows XP, to copy files to a Network Place from the command line, a batch file or, even better, a PowerShell script?</p> <p>What sent me down this road of research was trying to publish files to a WSS 3.0 document library from a user's machine. I can't map a drive to the library in question because the WSS site is only available to authenticate via NTLM on a port other than 80 or 443. I suppose I could alternately use the WSS web services to push the files out, but I'm really curious about the answer to this question now.</p>
<p>Using a batch file, you can both log on to the resource and copy the file: </p> <p>The Batch File would contain the following: </p> <pre><code>net use \\{dest-machine}\{destfolder} {password} /user:{username} copy {file} \\{dest-machine}\{destfolder} </code></pre> <p>e.g.</p> <pre><code>net use \\Development\myfolder mypassword /user:Administrator copy newfile.c \\development\myfolder </code></pre>
<p>Yes you can. I suggest using a tool like robocopy.</p>
3,154
<p>I am running <code>MOSS 2007</code> on a <code>Windows 2003</code> box. I need to know what configuration must be done to get Alerts to work. <code>SMTP settings</code>, etc.... When I create my alert, it is created but it does not send the email to show me that something changed in my document library or on any particular document. What am I missing?</p> <p>I did install the Email Services under Windows Components and the SMTP under <code>IIS</code>. In my SharePoint Central Admin, I did change my settings for outgoing and incoming email (Under the Topology and Services section).</p> <p>What else am I missing?</p>
<p>Did you setup the Web Application Outgoing E-mail Settings in your Central Administration? Y</p>
<p>I don't think this question is really appropriate for StackOverflow - its not a programming question, see the FAQ.</p> <p>But anyway - could be anti-virus or smtp relay rules stopping sharepoint sending smtp to your mail server. Try this tool to diagnose.</p> <p><a href="http://www.simplecomtools.com/smtptesttool.html" rel="nofollow noreferrer">http://www.simplecomtools.com/smtptesttool.html</a></p> <p>If that doesn't work then its MS support - the newsgroups are littered with the carcasses of people trying to resolve alert email problems!</p>
39,224
<p>I really like the mp3 player on 8tracks.com and was wondering how they manage to keep the mp3 playing even when I change pages?</p> <p>For example, listen to the track here <a href="http://8tracks.com/mixes?q=Aztec+Camera" rel="nofollow noreferrer">http://8tracks.com/mixes?q=Aztec+Camera</a> and click on one of the links to another page. The music cuts out for 1/4 of a second and then comes back in at exactly the right point!</p> <p>I don't think it's using a streaming server, so was wondering if it's a feature of flash?</p>
<p>Keep it simple: have the player store the current track/time in a cookie when onunload fires, then start from there when the next page loads. You'll need to write a couple support functions in JavaScript, as AFAIK Flash doesn't have access to browser cookies or JS events.</p>
<p>Yup, but you would get all the problemas that are involved with frames, you would end adding script code on all pages to take care when the user entered the site directly without the frame defining site</p>
17,372
<p>In Ultimaker Cura, is there a setting to slow down just the first layer (or two layers) covering over the infill? </p> <p>I'm not talking about the top layers, since you may have infill covered over during a lower section of the print. And I'm not talking about bridging, since this isn't a true bridge, and quick testing shows the bridge settings don't seem to control this. I'm also not talking about the whole layer, since you may have just a section of a layer involved with covering the infill.</p> <p>What I want, is, whenever a print transitions from infill back to shell, that first section of shell above the infill (and maybe also the next layer going the opposite direction) should be slower. </p> <p>What I've observed is this layer prints at the same speed as other shell sections, which can be too fast at this point for complete coverage, leaving a stringy section. This won't be visible later, but it does matter for strength and potentially quality; if expected filament isn't deposited it has to end up somewhere. Slowing down should help get a cleaner layer. </p> <p>Can Ultimaker Cura do this? I don't care which version. For completeness, what about other slicers? Even if I normally use Cura, I might be tempted to use a different slicer that can do this if I have a part where it really matters.</p>
<p>Cura can do this. It's a bit convoluted though. Here's what you need to do:</p> <ul> <li>Load your model / scene in the build plate.</li> <li>Load an additional cube and make it as big as the entire build plate so that it overlaps with everything (in the preferences you may need to disable "Ensure that models are kept apart).</li> <li>Select the cube and go to the per-object settings tool.</li> <li>Change the cube's mesh type to "modify settings for infill".</li> <li>For the cube, set Wall Line Count to 0, Top/Bottom Thickness to 0 and Top Layers to 1. This effectively makes the cube add one additional layer on the top side of all infill volumes.</li> <li>For the cube, set the Top/Bottom Speed to your desired speed for the one slower layer.</li> <li>(Optional) In the normal settings panel on the right, set the number of top layers to be one less, so that you get the same number of top layers again.</li> </ul>
<p>As far as I know, Cura has no option to do this. Conceptually Cura treats the model as a solid, so that the material over infill is not "overhang". However, you may be able to hack it by using the "magic mesh surface mode" feature under "special modes", to treat the model as a surface rather than a solid, then enable support and use the same model as a mask for where support material should be printed, and print support as infill-only. Alternatively you might just print a second copy of the model as infill-only (0 walls and 0 layers of top/bottom skin) in the same location.</p>
1,355
<p>I use MyGeneration along with nHibernate to create the basic POCO objects and XML mapping files. I have heard some people say they think code generators are not a good idea. What is the current best thinking? Is it just that code generation is bad when it generates thousands of lines of not understandable code?</p>
<p>Code generated by a code-generator should not (as a generalisation) be used in a situation where it is subsequently edited by human intervention. Some systems such the wizards on various incarnations of Visual C++ generated code that the programmer was then expected to edit by hand. This was not popular as it required developers to pick apart the generated code, understand it and make modifications. It also meant that the generation process was one shot.</p> <p>Generated code should live in separate files from other code in the system and only be generated from the generator. The generated code code should be clearly marked as such to indicate that people shouldn't modify it. I have had occasion to do quite a few code-generation systems of one sort or another and <em>All</em> of the code so generated has something like this in the preamble:</p> <pre><code>-- ============================================================= -- === Foobar Module =========================================== -- ============================================================= -- -- === THIS IS GENERATED CODE. DO NOT EDIT. === -- -- ============================================================= </code></pre> <p><a href="https://rads.stackoverflow.com/amzn/click/com/1930110979" rel="noreferrer" rel="nofollow noreferrer">Code Generation in Action</a> is quite a good book on the subject. </p>
<p>In certain (not many) cases they are useful. Such as if you want to generate classes based on lookup-type data in the database tables.</p>
24,814
<p>Is there a way to copy an entire directory to the output directory in a console application in C#.NET?</p> <p>I know for files you can right click them, properties and mark copy to output directory. But I'm not going to do that for 20.000 files...</p> <p>Thx, Lieven Cardoen aka Johlero</p>
<p>Are you sure you want all 20000 files in the output?</p> <p>Besides manual copy-paste operation I see two options: one is you can have a post-build task to copy all the files and another is to have 20000 files zipped, zip file added as a content item to your project with "copy always" set and either console application unzip 'em, or a post-build step is calling unzip utility to do that.</p>
<p>You could hit ctrl+A to highlight all of them, then hit ctrl+C to copy them, then go to the new directory and hit ctrl+V to paste them all to the new location...</p> <p>Or you could open up the command window and use copy... but the first way is probably easier.</p>
34,634
<p>I know that IntelliJ has an option to select all the code in a JSP file, right click, and select "format". This nicely formats all HTML, CSS, scriptlets and JSTL tags in a JSP file. </p> <p>Can Eclipse do this? </p> <p>If not, what is the best free Eclipse plugin that does the same? </p>
<p>With the Web Tool Plateform plateform (on eclipse.org website), this is very simple : in the JSP editor tab, right click->source->format (or Shift+Ctrl+F)</p>
<p>I found this one on eclipse plugin central.</p> <p>Looks like an all in one kind of formatter. I haven't tried it myself but it might be what you are looking for</p> <p><a href="http://www.eclipseplugincentral.com/Web_Links-index-req-viewlink-cid-926.html" rel="nofollow noreferrer">NXFormat</a></p>
29,670
<p>I am in the process of moving from VSS to SVN and I'm not sure how to share files in SVN.</p> <p>Basically we have the following structure in VSS</p> <pre><code>$MOSS - Components - ComponentA - bin - ComponentB - bin - GAC Mirror </code></pre> <p>GAC Mirror holds a shared copy of all the Dlls from the bin folders of the components to allow for easy copying to the GAC.</p> <p>In VSS all you do is drag the Dll from the bin folder to the GAC Mirror folder and it works it's life out.</p> <p>How would I do this in SVN?</p> <p>Thanks in advance.</p>
<p>Is svn:externals what you're after? <a href="http://svnbook.red-bean.com/en/1.0/ch07s03.html" rel="nofollow noreferrer">http://svnbook.red-bean.com/en/1.0/ch07s03.html</a></p>
<p>Use SVN 1.6+, it supports files also, see: <a href="http://svnbook.red-bean.com/nightly/en/svn-book.html#svn.advanced.externals" rel="nofollow">http://svnbook.red-bean.com/nightly/en/svn-book.html#svn.advanced.externals</a></p>
31,066
<p>I'm experiencing a strange issue where my Visual Studio 2005 C++ program crashes the first time it runs after a new build. I'm having a difficult time debugging this intermittent issue and I suspect it's somehow related to a file somewhere on my hard drive that is being changed. If I can find the file(s), that might provide some more insight into this issue. Are there any good tools for observing which files are being created/deleted/modified when a specific program is run?</p> <p>Thanks in advance!</p>
<p>You can use <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow noreferrer">Process Monitor</a> tool. Set "Show File System Activity" to ON and set a filter on the process name to get only the traces you need.</p>
<p>SysInternals (now Microsoft) FileMon</p> <p><a href="http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx" rel="nofollow noreferrer"><a href="http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx</a></a></p>
31,695
<p>I have a PHP script that runs as a CGI program and the HTTP <code>Authenticate</code> header gets eaten and spit out. So I would like to implement some kind of FORM based authentication. As an added constraint, there is no database so no session data can be stored.</p> <p>I am very open to having a master username and password. I just need to protect the application from an intruder who doesn't know these credentials.</p> <p>So how would you implement this?</p> <p>Cookies?</p> <p>I could present the form and if it validates, I can send back a cookie that is a hash of the IP address come secret code. Then I can prevent pages from rendering unless the thing decrypts correctly. But I have no idea how to implement that in PHP.</p>
<p>A few ways you could do this.</p> <ol> <li><a href="http://fragments.turtlemeat.com/htaccess.php" rel="nofollow noreferrer">htaccess</a> -- have your webserver handle securing the pages in question (not exactly cgi form based though).</li> <li>Use cookies and some sort of hashing algorithm (md5 is good enough) to store the passwords in a flat file where each line in the file is username:passwordhash. Make sure to <a href="http://www.codinghorror.com/blog/archives/000949.html" rel="nofollow noreferrer">salt</a> your hashes for extra security vs rainbow tables. (This method is a bit naive... be <em>very</em> careful with security if you go this route)</li> <li>use something like a <a href="http://www.sqlite.org/" rel="nofollow noreferrer">sqlite</a> database just to handle authentication. Sqlite is compact and simple enough that it may still meet your needs even if you don't want a big db backend.</li> </ol> <p>Theoretically, you could also store session data in a flat file, even if you can't have a database.</p>
<p>... About salt, add the username in your hash salt will prevent someone who knows your salt and have access to your password file to write a rainbow table and crack number of your users's password.</p>
3,805
<p>As a team we are using Visual Studio 2005 with framework 3.0. I am thinking if it will be nice for us to switch to Visual Studio 2008 with framework 3.5 ? Is it worth it ?</p> <p>Thanks.</p>
<p>Yes, it is 100% worth it. Visual Studio 2008 supports 2005 code (.net 2.0) completely. There are also a lot of improvements that you'll enjoy as you use 2008.</p>
<p>yes it is. works faster and more reliable</p>
33,194
<p>I am deciding on a framework to try out for PHP. I have narrowed it down to CakePHP and CodeIgniter. I have a couple of questions for any of you who have used or are familiar with both:</p> <ol> <li><p>I like the fact that CakePHP keeps most of the code outside of the webroot by default. Especially since I may end up using a single framework install for multiple apps. I see CodeIgniter will do that too, but you have to configure it and move some stuff around. Is that workaround secure and reliable, or is it an afterthought hack?</p></li> <li><p>Which (if not both) is easier to upgrade, and maintain over the long term? As new versions of the framework (and PHP itself) come out. I don't want to find my stuff either breaking, or becoming outdated.</p></li> </ol> <p><strong>Edit:</strong></p> <p>This is a very old post, but I thought I would update it with what I finally ended up doing, which was to use Kohana.</p>
<p>You should <strong>try</strong> both frameworks for a week or so, building something trivial (like a blog or wiki) in both, and see which you prefer using. Whatever makes the most sense <em>to you</em> will probably sustain you the longest through upgrades an deprecations.</p> <p>CakePHP is in a bit of a volatile state right now, still unearthing bugs while pushing to release version 1.2 (which is not backward compatible). I wouldn't suggest building a critical application with it if you need something rock solid <em>right now</em>. If you can wait a month or two for things to settle, then it's probably a moot point.</p> <p>To address your concerns:</p> <p>1) Cake and CI do it the same way (iirc). They are equally secure, reliable, and hackish on this front.</p> <p>2) Everything changes. If you need concrete, perpetual assurance of stability and backward compatibility, roll your own framework. There's not that much to it, and you're guaranteed that nothing changes unless you want it to.</p>
<ol> <li><p>This is a non issue. The app has a couple of lines which says where the core and your application code lies. You just need to change those lines.</p></li> <li><p>You can never anticipate this one. </p></li> </ol> <p>The state of PHP is a wildcard here. One app (CI) is built to be compatible with PHP4 the other requires PHP5. If you need to deal with the possibilty of a web host only supporting older versions of PHP then you need to go with CO. </p> <p>Another issue is unit testing. If you require your framework to ship with tests, then CI is not the way to go.</p> <p>Personally, I feel comfortable with CI because of the corporate backing. The company behind CI is making real profit from their efforts. Though CI is free, their paid product (ExpressionEngine) will eventually live on CI. The same could be said of the Zend Framework and even the birth of Rails (originally built for Basecamp.)</p>
31,828
<p>When I run my Visual Studio Windows Forms application by clicking F5 (debug mode), after I click on the close button (which calls <code>Application.Exit()</code>), after a few seconds I get an error that says:</p> <blockquote> <p>cannot acess a disposed object: Object name 'SampleForm'.</p> </blockquote> <p>A bit of background, I have another thread that runs every x seconds.</p> <p>My guess is that when I close the application, and since it is still in debug mode, the other thread is still running and it tries to access something but since I close the application the form is disposed.</p> <p>Is this correct?</p> <p>Do I have to kill the background process thread in before I call <code>Application.Exit()</code>?</p> <p><b>Update</b></p> <p>Now when I call <code>thread.Abort()</code> before the call to <code>Application.Exit()</code> the application closes completely. Before, EVEN after I clicked on the close button, the debugger was still running (i.e. the stop button was not selected) so it must have been because the thread was still active).</p>
<p>Mark your thread as BackgroundThread, and it will stop running as soon as you close the window.</p>
<p>Yes, you need to kill the thread first.</p> <p>This really has nothing to do with debug mode though. This has to do with basic threading.</p> <p>EDIT: Per your update, you should not be aborting the thread. The thread should be getting signaled and exiting on it's own. I am not sure what your thread or code looks like, but something like:</p> <pre><code>do { // Crazy threading stuff here }while(_running); </code></pre>
19,707
<p>I'm using IPAddress.TryParse() to parse IP addresses. However, it's a little too permissive (parsing "1" returns 0.0.0.1). I'd like to limit the input to dotted octet notation. What's the best way to do this?</p> <p>(Note: I'm using .NET 2.0)</p> <hr> <p><strong>Edit</strong></p> <p>Let me clarify:</p> <p>I'm writing an app that will scan a range of IPs looking for certain devices (basically a port scanner). When the user enters "192.168.0.1" for the starting address, I want to automatically fill in "192.168.0.255" as the ending address. The problem is that when they type "1", it parses as "0.0.0.1" and the ending address fills in as "0.0.0.255" - which looks goofy.</p>
<p>If you are interested in parsing the format, then I'd use a regular expression. Here's a good one (<a href="http://www.regular-expressions.info/regexbuddy/ipquick.html" rel="noreferrer">source</a>):</p> <pre><code>bool IsDottedDecimalIP(string possibleIP) { Regex R = New Regex(@"\b(?:\d{1,3}\.){3}\d{1,3}\b"); return R.IsMatch(possibleIP) &amp;&amp; Net.IPAddress.TryParse(possibleIP, null); } </code></pre> <p>That regex doesn't catch invalid IPs but does enforce your pattern. The TryParse checks their validity.</p>
<p>An IP address is actually a 32 bit number - it is not xxx.xxx.xxx.xxx - that's just a human readable format for the same. So IP address 1 is actually 0.0.0.1.</p> <p>EDIT: Given the clarification, you could either go with a regex as has been suggested, or you could format the short cuts to your liking, so if you want "1" to appears as "1.0.0.0". you could append that and still use the parse method. </p>
49,649
<p>I've seen some methods of <a href="http://www.anastasiosyal.com/archive/2007/04/17/3.aspx" rel="noreferrer">checking if a PEFile is a .NET assembly by examining the binary structure</a>.</p> <p>Is that the fastest method to test multiple files? I assume that trying to load each file (e.g. via <a href="http://msdn.microsoft.com/en-us/library/0et80c7k(VS.80).aspx" rel="noreferrer">Assembly.ReflectionOnlyLoad</a>) file might be pretty slow since it'll be loading file type information.</p> <p>Note: I'm looking for a way to check files programmatically.</p>
<p>Maybe this helps</p> <p>from <a href="https://web.archive.org/web/20110930194955/http://www.grimes.demon.co.uk/dotnet/vistaAndDotnet.htm" rel="nofollow noreferrer">https://web.archive.org/web/20110930194955/http://www.grimes.demon.co.uk/dotnet/vistaAndDotnet.htm</a></p> <blockquote> <p>Next, I check to see if it is a .NET assembly. To do this I check to see if the file contains the CLR header. This header contains important information about the location of the .NET code in the file and the version of the framework that was used to write that code. The location of this header is given in the file's Data Directory table. If the data directory item has zero values then the file is unmanaged, if it has non-zero values then the file is a .NET assembly.</p> <p>You can test this yourself using the dumpbin utility with the /headers switch. This utility will print the various headers in a file on the command line. At the end of the Optional Header Values you'll see a list of the Data Directories (there will always be 16 of them) and if the COM Descriptor Directory has a non-zero location it indicates that the file is a .NET assembly. The contents of the CLR header can also be listed using the /clrheader switch (if the file is unmanaged this will show no values). XP tests for the CLR header when it executes a file and if the CLR header is present it will initialize the runtime and pass the entry point of the assembly to the runtime, so that the file runs totally within the runtime.</p> </blockquote>
<p>The first link there is going to be the fastest and simplest method of checking (the PE file header one). You're correct in assuming that calling Assembly.ReflectionOnlyLoad is going to be pretty slow. </p>
42,755
<p>I know <a href="http://www.libtiff.org/libtiff.html" rel="noreferrer">libtiff</a> for C, but haven't found a port for .NET. Does such a port exist?</p>
<p>My company recently released a free and open-source(New BSD license) version of LibTiff written using only managed C# (license permits commercial use and distribution).</p> <p><a href="https://bitmiracle.com/libtiff/" rel="nofollow noreferrer">https://bitmiracle.com/libtiff/</a></p>
<p>What about using the built in .NET class? See <a href="http://msdn.microsoft.com/en-us/library/aa969817.aspx" rel="noreferrer">"How to: Encode and Decode a TIFF Image"</a> on MSDN.</p>
37,580
<p>i need write the code that runs when DllRegisterServer is called. i.e. when someone calls:</p> <pre><code>regsvr32 myActiveX.ocx </code></pre> <p>i'm trying to find the definitive list of required registry entries (rather than just what i can cobble together by spellunking through the registry).</p> <p>So far my expeditions have found:</p> <pre><code>HKEY_CLASSES_ROOT \MyCoolLibrary.MyCoolControl \Clsid (default) = "{myClassId}" \CLSID \{myClassId} \Control \InprocServer32 (default) = "c:\foo\myActiveX.ocx" ThreadingModel = "Apartment" \MiscStatus \1 (default) = 205201 \ProgID (default) = "MyCoolLibrary.MyCoolControl" \ToolboxBitmap32 (default) = "c:\foo\myActiveX.ocx,1" \TypeLib (default) = "{myTypeLibraryGuid}" \Verb \0 (default) = "Properties,0,2" \Version (default) = "1.0" \TypeLib \{myTypeLibraryGuid} \1.0 (default) = "MyCoolLibrary.MyCoolControl" </code></pre> <p>Now, the concerns: - what does the Control folder contain? Is it's presence indicate a control? - what's a MiscStatus of 205201 do? What would 205202 do instead? - What's the verb "Properties,0,2"? Where's "Properties,0,0" and "Properties,0,1"?</p> <p>In other words, i'm looking for the docs.</p>
<p>What i know so far. COM creates an object based on it's <em>clsid</em>. This is a guid that uniquely identifies that class. </p> <pre><code>HKEY_CLASSES_ROOT \Clsid \{AE8530CF-D204-4877-9CAB-F052BF1F661F} </code></pre> <p>That class is then used to create objects. COM now needs to know where the DLL is that holds that COM Object. In my particular case, the "server" that exposes the COM object is a DLL, and will be "in process". We then point COM to that "in-process" dll by adding:</p> <pre><code>HKEY_CLASSES_ROOT \Clsid \{AE8530CF-D204-4877-9CAB-F052BF1F661F} \InprocServer32 (default) = "c:\foo\myActiveX.ocx" </code></pre> <p>COM also needs to know the threading model that the COM server object supports. The simplest, most common, and the one used in this example is the "Apartment" threading model:</p> <pre><code>HKEY_CLASSES_ROOT \Clsid \{AE8530CF-D204-4877-9CAB-F052BF1F661F} \InprocServer32 (default) = "c:\foo\myActiveX.ocx" ThreadingModel = "Apartment" </code></pre> <p>Next is the ProgID. This is similar to how DNS is used to turn a friendly name into an IP. Here we turn a friendly name <code>"MyCoolLibrary.MyCoolControl"</code> into the ugly clsid <code>"{AE8530CF-D204-4877-9CAB-F052BF1F661F}"</code></p> <pre><code>HKEY_CLASSES_ROOT \Clsid \{AE8530CF-D204-4877-9CAB-F052BF1F661F} \InprocServer32 (default) = "c:\foo\myActiveX.ocx" ThreadingModel = "Apartment" HKEY_CLASSES_ROOT \MyCoolLibrary.MyCoolControl \Clsid (default) = "{AE8530CF-D204-4877-9CAB-F052BF1F661F}" </code></pre> <p>Now someone can ask for </p> <pre><code>MyCoolLibrary.MyCoolControl </code></pre> <p>and COM can turn that into the ClassID </p> <pre><code>{AE8530CF-D204-4877-9CAB-F052BF1F661F} </code></pre> <p>Once COM has the clasid, it can then look in the registry under <code>HKCR\Clsid\{AE8530CF-D204-4877-9CAB-F052BF1F661F}</code> to find the real information.</p> <p>For fun, the ProgID is added to the Clsid section, just so people can have some idea what this class is:</p> <pre><code>HKEY_CLASSES_ROOT \Clsid \{AE8530CF-D204-4877-9CAB-F052BF1F661F} \InprocServer32 (default) = "c:\foo\myActiveX.ocx" ThreadingModel = "Apartment" \ProgID (default) = "MyCoolLibrary.MyCoolControl" HKEY_CLASSES_ROOT \MyCoolLibrary.MyCoolControl \Clsid (default) = "{AE8530CF-D204-4877-9CAB-F052BF1F661F}" </code></pre> <p>Next is the type library. This is mostly <em>un</em>important for anything in-process, but if the COM object is in another "apartment", then function parameters need to be marshalled. COM does this automatically for you if it has a type library that defines all the classes methods. </p> <p>The clsid section is pointed to the appropriate type library with the addition of a TypeLib key:</p> <pre><code>HKEY_CLASSES_ROOT \Clsid \{AE8530CF-D204-4877-9CAB-F052BF1F661F} \InprocServer32 (default) = "c:\foo\myActiveX.ocx" ThreadingModel = "Apartment" \ProgID (default) = "MyCoolLibrary.MyCoolControl" \TypeLib (default) = "{17A5A3D4-439C-4C2A-8AB4-749B7771CDE1}" HKEY_CLASSES_ROOT \MyCoolLibrary.MyCoolControl \Clsid (default) = "{AE8530CF-D204-4877-9CAB-F052BF1F661F}" </code></pre> <p>Information about this type library is also stored in the registry, but adding these keys is done for us with a call to <a href="http://msdn.microsoft.com/en-us/library/ms221570.aspx" rel="noreferrer">RegisterTypeLib</a>. But it will add keys for us similar to:</p> <pre><code>HKEY_CLASSES_ROOT \Clsid \{AE8530CF-D204-4877-9CAB-F052BF1F661F} \InprocServer32 (default) = "c:\foo\myActiveX.ocx" ThreadingModel = "Apartment" \ProgID (default) = "MyCoolLibrary.MyCoolControl" \TypeLib (default) = "{17A5A3D4-439C-4C2A-8AB4-749B7771CDE1}" HKEY_CLASSES_ROOT \MyCoolLibrary.MyCoolControl \Clsid (default) = "{AE8530CF-D204-4877-9CAB-F052BF1F661F}" HKEY_CLASSES_ROOT \TypeLib \{AE8530CF-D204-4877-9CAB-F052BF1F661F} \1.0 (default) = "My Cool ActiveX Library" ... </code></pre> <p>Now we get into the tricky stuff, stuff that is needed to <em>hopefully</em> make an ActiveX control work.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms221150.aspx" rel="noreferrer">An MSDN article states</a> that you must add a dummy <strong>Programmable</strong> key to indicate that it is an ActiveX control:</p> <pre><code>HKEY_CLASSES_ROOT \Clsid \{AE8530CF-D204-4877-9CAB-F052BF1F661F} \Programmable </code></pre> <p>But <a href="http://msdn.microsoft.com/en-us/library/ms691424(VS.85).aspx" rel="noreferrer">this MSDN Library page</a> says the keyword is <strong>Control</strong>, and not <strong>Programmable</strong> - and there is no Programmable key.</p> <p>But that doesn't stop some ActiveX's from using Control, some using Programmable, and some using both.</p> <p>i cannot find anything mentioning anything else being required.</p> <p>So, can anyone find some definitive documentation?</p>
<p>Are you working on a 64 bit OS?</p> <p>If so, instead of writing to<br> HKEY_CLASSES_ROOT\CLSID\<br> you should write to<br> HKEY_CLASSES_ROOT\Wow6432Node\CLSID\</p>
36,114
<p>I am trying to build a server control that, depending on a "QuestionTypeId" display either a text box, date picker or Yes-No radio buttons. </p> <p>I have my control displaying how I want it to, but when the submit button is pressed on the form, the text box, date picker or radio buttons that were generated in the RenderContents method are all null.</p> <p>I have attempted to store the generated controls in view state, that stopped them being null, but the user inputs were not being stored.</p> <p>I will post code if it is needed. Just ask.</p>
<p>I think you need to create (and add) the controls in <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.control.createchildcontrols.aspx" rel="nofollow noreferrer" title="MSDN">CreateChildControls</a>. This will mean you'll need to store the value of the QuestionTypeId in either Viewstate or ControlState (I'd argue that ControlState is applicable in this case, as your control can't work without this value).</p>
<p>When you add controls dynamically, you need to make sure they are recreated before the viewstate is restored.</p> <p>I haven't done this in a while, but from memory I think you should recreate your controls in the OnInit method. This happens before postback data has been loaded and before the controls have their values set from viewstate.</p> <p>It may be worth doing some reading on the asp.net page lifecycle:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms178472.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms178472.aspx</a></p>
40,979
<p>Is it possible to setup a JDBC connection to Oracle without providing username/password information in a configuration file (or in any other standard readable location)?</p> <p>Typically applications have a configuration file that contains setup parameters to connect to a database. Some DBAs have problems with the fact that usernames and passwords are in clear text in config files.</p> <p>I don't think this is possible with Oracle and JDBC, but I need some confirmation...</p> <p>A possible compromise is to encrypt the password in the config file and decrypt it before setting up the connection. Of course, the decryption key should not be in the same config file. This will only solve accidental opening of the config file by unauthorized users.</p>
<p>You definitely don't want to be able to connect to the database without credentials because that makes the database vulnerable. </p> <p>This is a general problem, how do I store credentials needed to access external systems? WebLogic has a credential mapper to solve this problem, in which credentials (encrypted) are stored in embedded LDAP. Many Oracle products use a credential store facility that stores credentials in Oracle wallet. </p> <p>In the question, you provided the answer. Store the password encrypted and decrypt when you need it. Obviously you have to use symmetric encryption algorithm such as 3DES so you can decrypt it. Make sure the symmetric key is not something that can be guessed.</p> <p>The trick is where you keep the symmetric key needed for en/de-cryption. You can put it in a file that is secured through the OS or you can keep it in the code, but then you need to keep the code secure. You can also generate the key if you use a technique that will produce the same key and the algorithm is reasonably secure. </p> <p>If you can keep the code secure you can obviously keep the password in the code as well. However, you want the flexibility of being able to change the credentials without changing the code. </p> <p>You can add more layers to this solution as well. You can encrypt the configuration file (with a different key) as well as the password inside it making the hacker discover 2 keys. There are other even more secure methods using PKI, but they get hard to set up.</p>
<p>You can store the credentials anywhere, including as hardwired strings in the program or as entries in the Windows registry. It's up to you to retrieve them if you use something nonstandard, though; I'm not aware of any pre-rolled solutions that aren't plaintext.</p>
15,415
<p>Say I want to get the HTML of</p> <pre>http://www.google.com</pre> <p>as a String using some built-in classes of the Cocoa Touch framework.</p> <p>What is the least amount of code I need to write?</p> <p>I've gotten this far, but can't figure out how to progress. There must be an easier way.</p> <pre><code>CFHTTPMessageRef req; NSURL *url = [NSURL URLWithString:@"http://www.google.com"]; req = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), (CFURLRef)url, kCFHTTPVersion1_1); </code></pre>
<p>The <i>quickest</i> way is to use NSString's <code>+stringWithContentsOfURL:</code> method. However, this is a modal call, and your application will be non-responsive while it runs. You can either move it to a background thread, or use the NSURLConnection class to make a proper, asynchronous request.</p>
<p>One way to do this is as follows, however as <strong>Ben Gottlieb</strong> points out, this is a synchronouseRequest and will cause your program's execution to wait on the return of this function call, possibly making your application non-responsive. </p> <pre><code>NSURL *url = [ NSURL URLWithString: @"http://www.google.com"]; NSURLRequest *req = [ NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0 ]; NSError *err; NSURLResponse *res; NSData *d = [ NSURLConnection sendSynchronousRequest:req returningResponse:&amp;res error:&amp;err ]; </code></pre> <p>You can find information on writing the proper delegate methods to handle a Asynchronous Connection <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-170129" rel="noreferrer">here</a> on the Apple dev-docs.</p>
29,938
<p>I was really looking at the differences between pass by value and how Java allocates objects and what java does to put objects on the stack.</p> <p>Is there anyway to access objects allocated on the heap? What mechanisms does java enforce to guarantee that the right method can access the right data off the heap?</p> <p>It seems like if you were crafty and maybe even manipulate the java bytecode during runtime, that you might be able to manipulate data off the heap when you aren't supposed to?</p>
<p>There is no instruction in the JVM instruction set that gives arbitrary access to the heap. Hence, bytecode manipulation will not help you here.</p> <p>The JVM also has a verifier. It checks the code of every method (as a class is being loaded) to verify that the method does not try to pop more values off the execution stack than what it had pushed onto it. This ensures that a method cannot "see" the objects pointed by its calling method.</p> <p>Finally, local variables are stored in a per-method array (known as the "local variables array"). Again, the verifier makes sure that every read/write instruction from-/to- that array specifies an index that is less than the size of the array. Note that these JVM instructions can only specify a constant index. They cannot take a computed value and use it as an index.</p> <p>So to recap, the answer is No.</p>
<p>Regarding objects on the stack, it is only the new Java 6 VM from SUN (and perhaps some others) that will try to optimize byte code by putting objects on the stack. Typically, all objects will go into the heap. For reference, check out: <a href="http://www.ibm.com/developerworks/java/library/j-jtp09275.html" rel="nofollow noreferrer">http://www.ibm.com/developerworks/java/library/j-jtp09275.html</a></p> <p>Also the JVM spec is at <a href="http://java.sun.com/docs/books/jvms/second_edition/html/Overview.doc.html#6348" rel="nofollow noreferrer">http://java.sun.com/docs/books/jvms/second_edition/html/Overview.doc.html#6348</a>. The JVM protects its heap by simply not giving you instructions needed to corrupt it. Flaws in JVM implementations may cause your mileage to vary.</p>
36,814
<p>I'm relatively new to Mercurial and my team is trying it out right now as a replacement for Subversion. </p> <p>How can I commit and push a single file out to another repository while leaving other modifications in my working directory uncommitted (or at least not pushed to the other repository)?</p> <p>This happens for us with database migrations. We want to commit the migration to source control so a DBA can view and edit it while we're working on the code modifications to go along with that database migration. The changes aren't yet ready to go so we don't want to push all of them out.</p> <p>In subversion, I'd simply do:</p> <pre><code>svn add my_migration.sql # commit only the migration, but not the other files I'm working on svn commit -m "migration notes" my_mygration.sql </code></pre> <p>and continue working locally.</p> <p>This doesn't work with mercurial as when I'm pushing it out to the other repository, if there are changes to it that I haven't pulled down, it wants me to pull them down, merge them, and commit that merge to the repository. Commits after a merge don't allow you to omit files so it forces you to commit everything in your local repository.</p> <p>The easiest thing that I can figure out is to commit the file to my local repository, clone my local repository, fetch any new changes from the actual repository, merge them and commit that merge, and them push my changes out.</p> <pre><code>hg add my_migration.sql hg commit -m "migration notes" my_migration.sql cd .. hg clone project project-clone cd project-clone hg fetch http://hg/project hg push http://hg/project </code></pre> <p>This works, but it feels like I'm missing something easier, some way to tell mercurial to ignore the files already in my working directory, just do the merge and send the files along. I suspect mercurial queues can do this, but I don't fully grok mq yet.</p>
<p>There's a Mercurial feature that implements shelve and unshelve commands, which give you an interactive way to specify changes to store away until a later time: <a href="http://www.selenic.com/mercurial/wiki/index.cgi/ShelveExtension" rel="nofollow noreferrer">Shelve</a>.</p> <p>Then you can <code>hg shelve</code> and <code>hg unshelve</code> to temporarily store changes away. It lets you work at the "patch hunk" level to pick and choose the items to shelve away. It didn't appear to shelve a file had listed for adding, only files already in the repo with modifications.</p> <p>It is included with Mercurial as an "extension" which just means you have to enable it in your hg config file.</p> <hr> <p>Notes for really old versions of Mercurial (before shelve was included -- this is no longer necessary):</p> <p>I didn't see any great install instructions with some googling, so here is the combined stuff I used to get it working:</p> <p>Get it with:</p> <pre><code>hg clone http://freehg.org/u/tksoh/hgshelve/ hgshelve </code></pre> <p>The only file (currently) in the project is the hgshelve.py file.</p> <p>Modify your ~/.hgrc to add the shelve extension, pointing to where you cloned the repo:</p> <pre><code>[extensions] hgshelve=/Users/ted/Documents/workspace/hgshelve/hgshelve.py </code></pre>
<p>Since you said easiest, I often use <code>hg commit -i</code> (--interactive) even when committing whole files. With <code>--interactive</code> you can just select the file(s) you want rather than typing their entire path(s) on the command line. As an added bonus you can even selectively include/exclude chunks within the files.</p> <p>And then just <code>hg push</code> to push that newly created commit.</p> <p>I put more details on using <code>hg commit --interactive</code> in this answer: <a href="https://stackoverflow.com/a/47931672/255961">https://stackoverflow.com/a/47931672/255961</a></p>
15,227
<p>I want to create variables as <code>a1</code>,<code>a2</code>,<code>a3</code>...<code>a10</code>. For that I used a for loop. As the variable in loop increments I need to create a variable as above.</p> <p>Can anyone give me an idea?</p> <p>At the time of creation I also need to be able to assign values to them.</p> <p>That's where I'm getting syntax error.</p>
<p>Usually, we use a list, not a bunch of individual variables.</p> <pre><code>a = 10*[0] a[0], a[1], a[2], a[9] </code></pre>
<p>You can use the exec function:</p> <pre><code>for i in range(0,10): exec("a%d=%d" % (i,i)) </code></pre> <p>Not very pythonic way of doing things.</p>
48,992
<p>I have TurtoiseSVN and ankhSVN installed. I created a repository on my computer.. "C:\Documents and Settings\user1\My Documents\Subversion\Repository\"</p> <p>I am trying to connect to this repository from my co-workers computer. What should this URL be?</p> <p>Any help would be great. Thanks.</p>
<p>You will need to run the svnserve daemon on your computer, or run an apache server with the necessary modules, to allow your colleague to access this locally stored repository. For a simple case like this I would recommend svnserve, it should be simpler to configure and run.</p> <p>The url would then be:</p> <pre><code>svn://&lt;your_ip&gt;/&lt;repository_name&gt; </code></pre> <p>As opposed to an http or file protocol URL for apache and local filesystem based repositories.</p> <p>Read this page for details on how to set up svnserve it on Windows:</p> <p><a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-serversetup-svnserve.html" rel="noreferrer">http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-serversetup-svnserve.html</a></p>
<p>Try svn://xxx.xxx.xxx.xxx/Repository/</p> <p>The default port is 3690 if you have a firewall to configure.</p>
21,068
<p>I'm thinking about making a simple map control in WPF, and am thinking about the design of the basic map interface and am wondering if anyone has some good advice for this. </p> <p>What I'm thinking of is using a ScrollViewer (sans scroll bars) as my "view port" and then stacking everything up on top of a canvas. From Z-Index=0 up, I'm thinking:</p> <ol> <li>Base canvas for lat/long calculations, control positioning, Z-Index stacking.</li> <li>Multiple Grid elements to represent the maps at different zoom levels. Using a grid to make tiling easier.</li> <li>Map objects with positional data.</li> <li>Map controls (zoom slider, overview, etc).</li> <li>Scroll viewer with mouse move events for panning and zooming.</li> </ol> <p>Any comments suggestions on how I should be building this?</p>
<p>If you're looking for a good start, you can use the foundation of code supplied by the <a href="https://github.com/SharpMap/SharpMap" rel="nofollow noreferrer">SharpMap</a> project and build out from there. If I recall there were a few people already working on a WPF renderer for SharpMap, so you may also have some code to begin with.</p> <p>I've personally used SharpMap in a C# 2.0 application that combined GIS data with real time GPS data, and it was very successful. SharpMap provided me the transformation suite to handle GIS data, along with the mathematical foundation to work with altering GIS information. It should be relatively straightforward to use the non-rendering code with a WPF frontend, as they already have presentation separated from the data.</p> <p><em>(EDIT: added more details about how I used SharpMap)</em></p>
<p>The main question is how you store and access the items you are going to put in the map (assuming this isn't just a picture display). Lookup scenegraph for some ideas.</p> <p>Also if you want it to be more than a toy image viewer the lat long to XY scaling can get 'interesting'</p>
11,213
<p>I keep hearing that Flex is open source and I figured that a great way to learn about the inner workings would be to look at it. I can easily find the Flex SDK (<a href="http://opensource.adobe.com/wiki/display/flexsdk/Get+Source+Code" rel="noreferrer">http://opensource.adobe.com/wiki/display/flexsdk/Get+Source+Code</a>), but I'm wanting to look at the class definitions for the MXML core library (like NumericStepper). Have I misunderstood, or is this kind of thing available somewhere?</p> <p>Note, I'm looking for the source of some core MXML components so I can see how they work internally, not for the compiler's source. Does what I've linked above have what I'm looking for and I just can't find it in the director structure?</p>
<p>If you have installed the sdk or Flex builder all of the source files are installed locally on your computer, I believe.</p> <p>I have flex builder 3 installed source is located here(depending on where you installed):</p> <p><em>Source for flex 3 sdk</em></p> <p>C:\Program Files\Adobe\Flex Builder 3\sdks\3.0.0\frameworks\projects\framework\src\mx</p> <p><em>Source for flex 2 sdk</em></p> <p>C:\Program Files\Adobe\Flex Builder 3\sdks\2.0.1\frameworks\source\mx</p> <p>Hope this helps and alleviates the need to be online to view the source...</p>
<p>The open source stuff appears to be at:</p> <pre><code>http://opensource.adobe.com/wiki/display/flexsdk/Downloads </code></pre> <p>I don't know if everything is available there yet, there may be issues with third-party stuff.</p>
20,484
<p>I'm working on a C++ application that needs detailed timing information, down to the millisecond level. </p> <p>We intend to gather the time to second accuracy using the standard <code>time()</code> function in <code>&lt;ctime&gt;</code>. We would like to additionally gather the milliseconds elapsed since the last second given by <code>time()</code>. </p> <p>Does anyone know a convenient method for obtaining this information? </p>
<p>Boost.DateTime has millisecond and nanosecond representations <strong>IF</strong> the underlying platform supports them. While it is using platform specific code, it is keeping those details out of your code. </p> <p>If that is a big deal, they do have another way of doing platform independent subsecond resolution. <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/date_time/posix_time.html#time_duration_intro" rel="noreferrer">This page</a> a couple of paragraphs down talks about how to do it.</p> <p>(From the Page)</p> <p>For example, let's suppose we want to construct using a count that represents tenths of a second. That is, each tick is 0.1 second.</p> <pre><code>int number_of_tenths = 5; //create a resolution independent count -- divide by 10 since there are //10 tenths in a second. int count = number_of_tenths*(time_duration::ticks_per_second()/10); time_duration td(1,2,3,count); //01:02:03.5 //no matter the resolution settings </code></pre>
<p>Look into the QueryPerformanceCounter methods if this is for Windows.</p>
14,288
<p>Lets just say you have a table in Oracle:</p> <pre><code>CREATE TABLE person ( id NUMBER PRIMARY KEY, given_names VARCHAR2(50), surname VARCHAR2(50) ); </code></pre> <p>with these function-based indices:</p> <pre><code>CREATE INDEX idx_person_upper_given_names ON person (UPPER(given_names)); CREATE INDEX idx_person_upper_last_name ON person (UPPER(last_name)); </code></pre> <p>Now, given_names has no NULL values but for argument's sake last_name does. If I do this:</p> <pre><code>SELECT * FROM person WHERE UPPER(given_names) LIKE 'P%' </code></pre> <p>the explain plan tells me its using the index but change it to:</p> <pre><code>SELECT * FROM person WHERE UPPER(last_name) LIKE 'P%' </code></pre> <p>it doesn't. The Oracle docs say that to use the function-based index will only be used when several conditions are met, one of which is ensuring there are no NULL values since they aren't indexed.</p> <p>I've tried these queries:</p> <pre><code>SELECT * FROM person WHERE UPPER(last_name) LIKE 'P%' AND UPPER(last_name) IS NOT NULL </code></pre> <p>and</p> <pre><code>SELECT * FROM person WHERE UPPER(last_name) LIKE 'P%' AND last_name IS NOT NULL </code></pre> <p>In the latter case I even added an index on last_name but no matter what I try it uses a full table scan. Assuming I can't get rid of the NULL values, how do I get this query to use the index on UPPER(last_name)?</p>
<p>The index can be used, though the optimiser may have chosen not to use it for your particular example:</p> <pre><code>SQL&gt; create table my_objects 2 as select object_id, object_name 3 from all_objects; Table created. SQL&gt; select count(*) from my_objects; 2 / COUNT(*) ---------- 83783 SQL&gt; alter table my_objects modify object_name null; Table altered. SQL&gt; update my_objects 2 set object_name=null 3 where object_name like 'T%'; 1305 rows updated. SQL&gt; create index my_objects_name on my_objects (lower(object_name)); Index created. SQL&gt; set autotrace traceonly SQL&gt; select * from my_objects 2 where lower(object_name) like 'emp%'; 29 rows selected. Execution Plan ---------------------------------------------------------- ------------------------------------------------------------------------------------ | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| ------------------------------------------------------------------------------------ | 0 | SELECT STATEMENT | | 17 | 510 | 355 (1)| | 1 | TABLE ACCESS BY INDEX ROWID| MY_OBJECTS | 17 | 510 | 355 (1)| |* 2 | INDEX RANGE SCAN | MY_OBJECTS_NAME | 671 | | 6 (0)| ------------------------------------------------------------------------------------ </code></pre> <p>The documentation you read was presumably pointing out that, just like any other index, all-null keys are not stored in the index.</p>
<p>Are you sure you want the index to be used? Full table scans are not bad. Depending on the size of the table, it might be more efficient to do a table scan than use an index. It also depends on the density and distribution of the data, which is why statistics are gathered. The cost based optimizer can usually be trusted to make the right choice. Unless you have a specific performance problem, I wouldn't worry too much about it.</p>
21,348
<p>(This is a followup to my <a href="https://stackoverflow.com/questions/42468/how-do-i-measure-bytes-inout-of-an-ip-port-used-for-net-remoting">previous question</a> about measuring .NET remoting traffic.)</p> <p>When I am testing our Windows service / service controller GUI combination, it is often most convenient to run both pieces on my development box. With this setup, the remoting traffic between the two is via loopback, not through the Ethernet card.</p> <p>Are there any software packet sniffers that can capture loopback traffic on a WinXP machine? <a href="http://www.wireshark.org/" rel="nofollow noreferrer">Wireshark</a> is a great package, but it can only capture external traffic on a Windows machine, not loopback.</p>
<p>What you should do is to run RawCap, which is a sniffer that can capture traffic to/from the loopback interface in Windows. Just start it with "RawCap.exe 127.0.0.1 loopback.pcap".</p> <p>You can then open up loopback.pcap in Wireshark or <a href="http://www.netresec.com/?page=NetworkMiner" rel="noreferrer">NetworkMiner</a> to look at the network traffic.</p> <p>You can find RawCap here: <a href="http://www.netresec.com/?page=RawCap" rel="noreferrer">http://www.netresec.com/?page=RawCap</a></p> <p>Good Luck!</p>
<p>You should definitely try Npcap, it works perfectly with Wireshark to capture loopback traffic in Windows, see here: <a href="https://wiki.wireshark.org/CaptureSetup/Loopback" rel="nofollow">https://wiki.wireshark.org/CaptureSetup/Loopback</a></p>
6,848
<p>Is there a way to merge two primary keys into one and then cascade update all affected relationships? Here's the scenario:</p> <p>Customers (idCustomer int PK, Company varchar(50), etc)</p> <p>CustomerContacts (idCustomerContact int PK, idCustomer int FK, Name varchar(50), etc)</p> <p>CustomerNotes (idCustomerNote int PK, idCustomer int FK, Note Text, etc)</p> <p>Sometimes customers need to be merged into one. For example, you have a customer with the id of 1 and another with the id of 2. You want to merge both, so that everything that was 2 is now 1. I know I could write a script that updates all affected tables one by one, but I'd like to make it more future proof by using the cascade rules, so I don't have to update the script every time there is a new relationship added.</p> <p>Any ideas?</p>
<p>There's no automatic way to do it, but you have a couple options, you can manually write the procedures, or you can either code generate the merge on a regular basis or dynamically generate it at run-time. To do this, you can use the <code>INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS</code> and <code>INFORMATION_SCHEMA.KEY_COLUMN_USAGE</code> and <code>INFORMATION_SCHEMA.TABLE_CONSTRAINTS</code> and <code>INFORMATION_SCHEMA.COLUMNS and INFORMATION_SCHEMA.TABLES</code> to build the procedure dynamically.</p> <p>You can also simply wrap the entire operation in a transaction (a good idea anyway). The last step will be to remove the customer being merged out of, so if there is RI on a table you never added and you try to do a merge, it will fail because you cannot remove the customer being merged out of since there are dependent records in a table which wasn't already added to the merge procedure.</p>
<p>Consider using Triggers instead. On update of the Customers (idCustomer column), you do whatever needed modifications (Delete, Update ...) on the related tables.</p>
27,638
<p>I have a BLTouch clone (3DTouch) on my printer (Artillery Sidewinder X1). I installed it on the printer ages ago and has been working fine since. Recently, I did a BTT smart filament sensor upgrade.</p> <p>I updated and edited both the Marlin firmware and the MKS TFT28 screen firmware to get it to work with the smart filament sensor. The filament sensor runs through the screen not the motherboard so it is enabled in screen firmware instead.</p> <p>The sensor works fine and every other part of the printer is fine as well, except that after the BLTouch does a <code>G29</code> (I have it do that before every print in my start G-code, followed by an <code>M500</code>), It will not adjust the Z-axis to compensate for the unevenness of the bed. I can see the Z motors not move and I cannot feel the lead screws rotate in my hand if I touch my hand against them.</p> <p>I have been through several other forums, videos, etc. on the internet but none of them have the same problem as me and/or their solutions do not fix the problems.</p> <p>I have also tried flashing the display with the original firmware, which did not work so I guess is that I have something wrong with the firmware. I have checked and double-checked my firmware but maybe there is something I missed or do not know about that could be causing my problem.</p> <p>Firmware can be found <a href="https://github.com/Smartich0ke/Artillery-Sidewinder-X1-firmware" rel="nofollow noreferrer">here.</a></p> <hr /> <p><em>I have tried running the original firmware with changes only made to enable the BLTouch. The Z-axis does still not compensate.</em></p> <hr /> <p><em>I have also replaced the mainboard. I don’t know if that could affect the operation or not.</em></p> <hr /> <p><em>Recently, I needed to print a part so I put the default Marlin firmware using the Artillery SWX1 example in Marlin's collection of examples with modifications made only to work with the BLTouch. I can post this copy of the firmware but it is probably identical to the GitHub repo below. This way I could just print with no Z compensation, however, now whenever I try to home the printer or do a <code>G29</code>, the BLTouch doesn't deploy and it will crash into the bed. I posted an unlisted video on YouTube demonstrating the issue <a href="https://www.youtube.com/watch?v=lyyazOalsc8" rel="nofollow noreferrer">here</a>. Also note that in the video, I attempt to move the Z-axis by 1 mm, but instead, the stepper motors spin at full speed and the gantry comes zooming towards the bed.</em></p> <hr /> <p><em>I tried flashing the firmware yet again and for some reason, the BLTouch worked. it could home is and to a probing routine. I have been using the printer without the compensation and it works fine but it is really bizarre that this is happening. I know it is unlikely to solve the problem, but I am thinking of purchasing a replacement BLTouch. They are only 20 bucks to replace and I did accidental slightly bend the plastic probe before the Z stopped compensating. So is it possible the BLTouch is cactus?</em></p> <hr /> <p><em>So recently, I noticed when running a G29 T through Octoprint or Pronterface, etc. that the printer will return a set of numbers for each probing point. Does this indicate that the BLTouch has taken the measurements but the printer will not use them to compensate the bed?</em></p> <p>I have tried all the answers below.</p>
<p>So I discovered that the fade height must have been set to something really off.</p> <p>I didn't know this at the time so I thought I should set the fade height to the default 10 mm just to make sure nothing was wrong and tested it. The printer now levels and compensates perfectly!</p>
<p>Make sure <code>RESTORE_LEVELING_AFTER_G28</code> is uncommented in <code>configuration.h</code>.</p>
1,941
<p>It's a tricky question I was asked the other day... We're working on a pretty complex telephony (SIP) application with mixed C++ and PHP code with MySQL databases and several open source components.</p> <p>A telecom engineer asked us to estimate the performance of the application (which is not ready yet). He went like 'well, you know how many packets can pass through the Linux kernel per second, plus you might know how quick your app is, so tell me how many calls will pass through your stuff per second'. </p> <p>Seems nonsense to me, as there are a million scenarios that might happen (well, literally...) </p> <p>However... is there a way to estimate application performance (knowing the hardware it will run on, being able to run standard benchmarks on it, etc) before actual testing?</p>
<p>You certainly can bound the problem with upper (max throughput) limits. There is nothing nonsense about that. In fact, not knowing that stuff indicates a pretty haphazard approach to a problem - especially in the telephony world. </p> <p>You can work through the problem yourself - what is the minimum "work" you have to accomplish for a transaction or whatever unit of task you have in your app?</p> <p>Some messages to and from, some processing and a database hit for example? Getting information on the individual pieces will give you an idea of the fastest possible throughput. If you load up the system and see significantly lower performance then you can take time to figure out where you are possibly losing throughput with inefficient algorithms, etc.</p> <p><strong>EDIT</strong></p> <p>To do this exercise you need to know all the steps your app does for each use case. Then you can identify the max throughput for each use case. You should definitely know this stuff prior to release and going live. </p> <p>I'm ignoring the worst case analysis as that - as you point out - is quite a bit harder.</p>
<p>This is true in some domains, but unless you are an expert in that domain then you don't have any idea. For example I write code to controlling industrial robots. The speed is limited by the robot motion, not by the execution speed of the code. Knowing how fast the robot is and how far it has to go, we can make fairly good estimates of "speed". I'd have no idea how to estimate time for your application.</p>
37,032
<p>I am maintaining an app for a client that is used in two locations. One in England and one in Poland.</p> <p>The database is stored in England and uses the format £1000.00 for currency, but the information is being gathered locally in Poland where 1000,00 is the format.</p> <p>My question is, in VB6 is there a function that takes a currency string in a local format and converts to another, or will I just have to parse the string and replace , or . ?</p> <p>BTW I have looked at CCur, but not sure if that will do what I want. </p>
<p>The data is not actually stored as the string <code>&quot;£1000.00&quot;</code>; it's stored in some numeric format.</p> <blockquote> <p><strong>Sidebar:</strong> Usually databases are set up to store money amounts using either the <strong>decimal</strong> data type (also called <strong>money</strong> in some DBs), or as a floating point number (also called <strong>double</strong>).</p> <p>The difference is that when it's stored as <strong>decimal</strong> certain numbers like 0.01 are represented exactly whereas in <strong>double</strong> those numbers can only be stored approximately, causing rounding errors.</p> </blockquote> <p>The database <em>appears</em> to be storing the number as <code>&quot;£1000.00&quot;</code> because something is formatting it for display. In VB6, there's a function <code>FormatCurrency</code> which would take a number like 1000 and return a string like <code>&quot;£1000.00&quot;</code>.</p> <p>You'll notice that the <code>FormatCurrency</code> function does not take an argument specifying what type of currency to use. That's because it, along with all the other locale-specific functions in VB, figures out the currency from the current locale of the system (from the Windows Control Panel).</p> <p>That means that on my system,</p> <pre><code>Debug.Print FormatCurrency(1000) </code></pre> <p>will print <code>$1,000.00</code>, but if I run that same program on a Windows computer set to the UK locale, it will probably print <code>£1,000.00</code>, which, of course, is something completely different.</p> <p>Similarly, you've got some code, somewhere, I can't tell where, in Poland, it seems, that is responsible for parsing the user's string and converting it to a number. And if that code is in Visual Basic, again, it's relying on the control panel to decide whether &quot;.&quot; or &quot;,&quot; is the thousands separator and whether &quot;,&quot; or &quot;.&quot; is the decimal point.</p> <p>The function <code>CDbl</code> converts its argument to a number. So for example on my system in the US</p> <pre><code>Debug.Print CDbl(&quot;1.200&quot;) </code></pre> <p>produces the number one point two, on a system with the Control Panel set to European formatting, it would produce the number one thousand, two hundred.</p> <p>It's possible that the problem is that you have someone sitting a computer with the regional control panel set to use &quot;.&quot; as the decimal separator, but they're typing &quot;,&quot; as the decimal separator.</p>
<p>What database are you using? And what data type is the amount stored in?</p> <p>As long as you are always converting from one format to another, you do not need to do any parsing, just replace "." with "," or the other way around. You may need to remove the "£"-sign as well if that is stored in your string.</p>
4,017
<p>I have several .NET <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="nofollow noreferrer">Windows Forms</a> applications that I'm preparing to convert into a <a href="http://en.wikipedia.org/wiki/ClickOnce" rel="nofollow noreferrer">ClickOnce</a>/smart-client deployment scenario. I've read the isn't-this-great tutorials, but are there pitfalls or "gotchas" that I should be aware of?</p> <p>There are several minor applications used off and on, but the main application is in C#, runs 24/7, is quite large, but only changes every few weeks. It also writes to a log file locallly and talks to local hardware devices.</p>
<p>Here are a few that I am aware of.</p> <ol> <li><p><strike>Can't put an icon on the desktop.</strike> You can now.</p></li> <li><p>I can't install for all users.</p></li> <li><p>I need to jump through hoops to move the deployment to a different server. It is not a problem if you are developing internally, and the users can see the server that you are publishing to or if you are deploying to the public web, but it is not great if you need to roll out to multiple customer sites independently.</p></li> <li><p>Since <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="nofollow noreferrer">.NET</a> 3.5 SP1 you do not need to sign the deployment manifest anymore which makes it much easier to move deployments to new servers.</p></li> <li><p>I can't install assemblies in the <a href="http://en.wikipedia.org/wiki/Global_Assembly_Cache" rel="nofollow noreferrer">GAC</a>. You can get around this by creating regular install packages that are pre-requisites of the ClickOnce application.</p></li> </ol>
<p>You can't install if the client is behind a proxy that requires authentication.</p>
18,040
<p>I have a program that will calculate the minimal area taken by fitting rectangles together.</p> <p>Input: Rectangles of different height and width.<br> Output: One rectangle that contains all these rectangles.<br> Rules: One cannot turn or roll the rectangles around and they cannot overlap.</p> <p>I understand that this is related or is possibly defined as a bin packing problem (NP-hard). However the algorithms i found for those often set a limit on for example width. I have no such limits, the only goal is to get the resulting area as small as possible.</p> <p>Any pointers on what algorithm is appropriate to get a decent solution?</p>
<p><a href="http://www-rcf.usc.edu/~skoenig/icaps/icaps04/icapspapers/ICAPS04KorfR.pdf" rel="noreferrer">http://www-rcf.usc.edu/~skoenig/icaps/icaps04/icapspapers/ICAPS04KorfR.pdf</a></p> <p>Apparently this problem is harder than it looks at first. It's an interesting algorithm, since first it guesses a solution and then improves on it, so if you don't want to wait for the optimal solution, you can just run it for a set number of iterations to get an approximate solution (the longer you run it, the better the approximation).</p>
<p>I'd start by skimming through <a href="http://mathworld.wolfram.com" rel="nofollow noreferrer">http://mathworld.wolfram.com</a> - they're awesome for stuff like this.</p> <p>Second, I could envision a dopey algorithm that would put the longest (in the X dimension) box on the bottom, then the tallest (in the Y dimension) on top of it on one side or the other. Then continue stacking them in this "stair-stepped" fashion going right wards and upwards (for example go right until you can't, then go up, etc, etc).</p> <p>That's probably non-ideal, and may very well give you bad results, but it's what popped to mind first.</p>
31,326
<p>When my app is run in the iPhone simulator, the delegate method</p> <pre><code>- (void)applicationWillTerminate:(UIApplication *)application </code></pre> <p>is only called the first time I hit the iPhone simulator's home button.</p> <p>After the home button is pressed and the app is launched again, hitting the home button does not call the delegate method.</p> <p>What is going on here? Am I misunderstanding something fundamental?</p>
<p>I suspect that it is being called, but that you are getting confused because after you hit the Home button in the Simulator, you've ended the current session in Xcode. You probably have an <code>NSLog</code> in your <code>applicationWillTerminate:</code> method, yes? Once you hit the Home button, <code>NSLog</code>s no longer show up in Xcode's run console. If you open <code>/Applications/Console.app</code> I expect they'll show up there.</p>
<pre><code>- (void)applicationWillTerminate:(UIApplication *)application </code></pre> <p>is called when the application "terminates". If you are using iOS then the app will NOT terminate when the home button is pressed, unless you have disabled multi-tasking for your app or the user does not have a "multi-tasking supported" device.</p> <pre><code>- (void)applicationDidEnterBackground { </code></pre> <p>is now used when the user presses the home button. Unless (as I previously said) you have disabled multi-tasking for your app or the user does not have a "multi-tasking supported" device.</p>
48,043