instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I have this code:</p> <pre><code>if (file.exists()) { Document doc = builder.parse(file); NodeList list = doc.getElementsByTagName("property"); System.out.println("XML Elements: "); for (int ii = 0; ii &lt; list.getLength(); ii++) { </code></pre> <p>line 2 gives following exception</p> <pre> E:\workspace\test\testDomain\src\com\test\ins\nxg\maps\Right.hbm.xml ...***java.net.SocketException: Operation timed out: connect:could be due to invalid address at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:372) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:233) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:220) </pre>
<p>Parhaps the DocumentBuilder is unsuccessfully trying to access a DTD via a network socket for your XML document?</p> <p>If there are DTD references in the XML document, try editing them out to prove the cause.</p> <p>If that fixes your problem, I think you can use an EntityResolver for a more permanent solution, but I've not done it myself.</p>
<p>Try to simplify your problem.</p> <p>Can you get the code, you have to parse, manually?</p> <p>If yes, try to parse it. I don't think it's the problem of your DocumentBuilder but your network connection. So you have to ensure, that the DocumentBuilder is able to access <em>every bit</em> of the xml document.</p> <p>If your manually stored document fails when it is validated, there will be a different error message.</p> <p>Hope it helps.</p>
44,654
<p>We need to set up a secure certificate on an Apache reverse proxy. We've been advised that we need to use a virtual host directive.</p> <p>I've looked these up in the O'Reilly book bit can't find any examples that pick up https specifically.</p> <p>Does anyone have any examples of config snippets to do this?</p>
<p>I'm not exactly sure what you are asking for, but there are multiple things you need. For example, you need to get a SSL certificate, then you need to install mod_ssl into your Apache. I suggest you install it using your system's package manager, etc..</p> <p>This is an example virtualhost:</p> <pre><code>&lt;VirtualHost IP.ADDRESS.HERE:443&gt; DocumentRoot /web/domain.com/www/htdocs ServerName www.domain.com ServerAdmin server@domain.com SSLEngine on SSLCertificateFile /usr/local/etc/apache/ssl.crt/www.domain.com.crt SSLCertificateKeyFile /usr/local/etc/apache/ssl.key/www.domain.com.key ErrorLog "/var/logs/domain.com/error_log" CustomLog "|/usr/local/sbin/cronolog /var/logs/domain.com/%Y/%m/access_log" combined &lt;/VirtualHost&gt; </code></pre> <p>A proxy configuration inside the <code>&lt;VirtualHost /&gt;</code> can look different. This assumes that the domain points to a directory on your server, but what you do inside <code>&lt;VirtualHost /&gt;</code> is up to you.</p> <p>As I said, I also had to install ssl into Apache, to load the module I needed the following:</p> <pre><code>LoadModule ssl_module libexec/apache/libssl.so ... AddModule mod_ssl.c </code></pre> <p>And that's basically it. Let me know if you need more pointers. In case, it also helps if you tell us if you run Apache 1.3 or 2.x.</p>
<p>Not sure if this is what you're after, but I used something like the following in the past:</p> <pre><code>&lt;IfModule mod_ssl.c&gt; SSLProxyEngine On ProxyPreserveHost On RewriteRule ^/whatever(.*)$ https://otherhost/whatever$1 [P] &lt;/IfModule&gt; </code></pre> <p>I needed to proxy secure content from another host, and that's what we ended up using. Works fine, and has for some time now. Does that sort of cover what you're looking for?</p>
35,966
<p>Is there any performance impact or any kind of issues? The reason I am doing this is that we are doing some synchronization between two set of DBs with similar tables and we want to avoid duplicate PK errors when synchronizing data.</p>
<p>Yes, it's okay.</p> <p>Note: If you have perfomance concerns you could use the "CACHE" option on "CREATE SEQUENCE":</p> <p><em>"Specify how many values of the sequence the database preallocates and keeps in memory for faster access. This integer value can have 28 or fewer digits. The minimum value for this parameter is 2. For sequences that cycle, this value must be less than the number of values in the cycle. You cannot cache more values than will fit in a given cycle of sequence numbers. Therefore, the maximum value allowed for CACHE must be less than the value determined by the following formula:"</em></p> <pre><code>(CEIL (MAXVALUE - MINVALUE)) / ABS (INCREMENT) </code></pre> <p><em>"If a system failure occurs, all cached sequence values that have not been used in committed DML statements are lost. The potential number of lost values is equal to the value of the CACHE parameter."</em></p>
<p>If you are synching two tables why not change the PK seed/increment amount so that everything takes care of itself when a new PK is added?</p> <p>Let's say you had to synch the data from 10 patient tables in 10 different databases.<br> Let's also say that eventually all databases had to be synched into a Patient table at headquarters.</p> <p>Increment the PK by ten for each row but ensure the last digit was different for each database.</p> <p>DB0 10,20,30..<br> DB1 11,21,31..<br> .....<br> DB9 19,29,39..<br></p> <p>When everything is merged there is guaranteed to be no conflicts.</p> <p>This is easily scaled to n database tables. Just make sure your PK key type will not overflow. I think BigInt could be big enough for you...</p>
27,426
<p>I'm trying to run a shell command using the backtick operators, but the fact that the child process inherits php's open file descriptors is problematic. Is there a way to keep this from happening?</p> <p>I'm running PHP 5.1.2</p>
<p>The only way I really know of is to have the children open up their own resources after forking.</p> <p>There is a fairly decent tutorial on pcntl here:</p> <p><a href="http://www.hackingwithphp.com/16/0/0/miscellaneous-topics" rel="nofollow noreferrer">http://www.hackingwithphp.com/16/0/0/miscellaneous-topics</a> <a href="http://www.hackingwithphp.com/16/1/4/duplication-of-resources-when-forking" rel="nofollow noreferrer">http://www.hackingwithphp.com/16/1/4/duplication-of-resources-when-forking</a></p>
<p>This worked for me:</p> <pre><code>$cmd_to_run = escapeshellarg('/path/to/file --args'); `echo $cmd_to_run | /bin/at now`; </code></pre> <p>Replace the '/path/to/file --args' part with the command that you want to run. The 'at' command uses your cron daemon to schedule tasks.</p>
30,302
<p>Does anyone know of a set of bindings for C# to drive the FFMpeg library directly ? I could shell to ffmpeg.exe directly but I found it hard to sync/control as a separate process. any help would be appreciated.</p>
<p>Tao.ffmpeg: <a href="http://www.taoframework.com/project/ffmpeg" rel="noreferrer">http://www.taoframework.com/project/ffmpeg</a> it compiles and has a binary dist which is more than can be said for ffmpeg-sharp at this point. It is, however, not particularly easy to use. </p>
<p><a href="http://jasonjano.wordpress.com/2010/02/09/a-simple-c-wrapper-for-ffmpeg/" rel="nofollow noreferrer">http://jasonjano.wordpress.com/2010/02/09/a-simple-c-wrapper-for-ffmpeg/</a></p>
34,073
<p>I want to build a 3D printer with a heating chamber of around 90 °C with build area 200x200x200 mm. I have never build a CoreXY system, so my design is currently an XY system with moving X motor (mounted on Y). Since it has a heating chamber I can't use normal stepper motor (there's a way, but I have to provide forced air cooling like NASA did, or water cooling). Extruder is Bowden type. I have already sourced almost all components, but I'm stuck at choosing the motor.</p> <p>I could find high temperature stepper motor in India (that's where I'm from), but it cost too much. I <a href="https://visionminer.com/products/high-temp-motorx-extruder?_pos=1&amp;_sid=7b5e5e603&amp;_ss=r" rel="nofollow noreferrer">found one at the Visionminer website</a>, they're the dealers for Intamsys printers, which has a chamber of 90 °C and they are providing replacement stepper motors as well.</p> <p>Comparing the cost, the motor I found in India costs three times as above. Even with shipping I will save a lot. But one issue is they're not providing any details about torque and current rating. There's one image in the website and it says,</p> <pre><code>MOONS STEPPING MOTOR TYPE 17HDB001-11N 60904162 18/04/12 </code></pre> <p>I thought it might be a MOONS motor, so I contacted them, no reply so far. I tried to find the motor by part number, but failed. I tried mailing Visionminer as well.</p> <p>Anyone have any idea which motor is this or know any high temperature motors?</p> <p>Also they use Gates belts, which is rated for 85 °C. How reliable will it be in 90 °C chamber?</p> <p>I will heat the chamber using a external heater with fan.</p> <p>My extruder is Bowden, same as you've shown E3D V6, with updated high temp parts. Plated Cu heater block + Nozzle, High temp heating coil and Thermocouple.</p> <p>But In my design X axis motor is moving one. I mean it's mounted on Y Similar to this <a href="https://drive.google.com/open?id=1g-pOCmL_2Vm1df78jYKZNPT7aMvoe8Ke" rel="nofollow noreferrer">image</a></p> <p><a href="https://i.stack.imgur.com/BJ3qe.jpg" rel="nofollow noreferrer" title="X axis stepper mounted on Y axis"><img src="https://i.stack.imgur.com/BJ3qe.jpg" alt="X axis stepper mounted on Y axis" title="X axis stepper mounted on Y axis" /></a></p> <p>So it will be inside the chamber and I have to cool it somehow or looks for high temp motor</p> <p>What I'm trying to print is PEEK, and it requires around 80-90 Degree chamber, and most stepper motors are rated for an ambient temperature of 50 Degrees. And I'm really planning to seal the chamber using SS sheet. It's going to be something like <a href="https://www.intamsys.com/funmat-ht-3d-printer/" rel="nofollow noreferrer">Intamsys funmat HT</a>. What is the biggest print, I mean duration that you run your printer at 60 Degrees?</p>
<p>An alternative to finding steppers that can withstand the heat, you can consider not getting the heat near the steppers:</p> <ul> <li><em>Moving the steppers outside the heated build volume</em><br> With 2 extra pulleys per stepper you can get the steppers outside the build volume.</li> </ul> <p><a href="https://i.stack.imgur.com/he7hz.png" rel="nofollow noreferrer" title="CoreXY kinematics based on source image of Greg Hoge"><img src="https://i.stack.imgur.com/he7hz.png" alt="CoreXY kinematics, steppers brought outside chamber" title="CoreXY kinematics based on source image of Greg Hoge"></a></p> <ul> <li><em>Shield the motors from the heat by placing them in a cooler tunnel or behind a face plate/cover</em><br> You can also shield the steppers from the heat, e.g. the Ultimaker 3(E) the steppers are behind a cover.</li> </ul> <p>Be aware that creating a 90&nbsp;&deg;C heat chamber, all the printed parts for the CoreXY need to be printed in a filament type that can withstand prolonged exposure to the temperature you want the chamber to be (or be made in metal). For the mentioned temperature this implies the use of some more exotic filament types, see e.g. <a href="/a/6120/">this answer</a>.</p>
<p>You don't need to worry about the stepper for heating chamber since the direct drive uses a fan for cooling the motor area.</p> <p><a href="https://i.stack.imgur.com/MfR7h.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MfR7h.jpg" alt="enter image description here"></a></p> <p>When I started to make my own printer I had the same question but in order to make me feel good and peace. I prefer to use a bowder extruder.</p> <p><a href="https://i.stack.imgur.com/AChjC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AChjC.jpg" alt="enter image description here"></a></p> <p>This bowden extruder comes in different sizes: Normal as picture shows above, small, and mini like the other that shows pre assembled below.</p> <p><a href="https://i.stack.imgur.com/plV2c.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/plV2c.jpg" alt="enter image description here"></a></p> <p>However the question should be different like, <strong>Can I print inside an oven?</strong> for this will address the question to other possibilities:</p> <p>1.- Cover or shield the motor with some foil to avoid the heating <br> 2.- Add a water cooling like CPU, so the water flows from outside to the motor to keep a low temperature. <br> 3.- Add cooling fans, this ones should take te air from outside and tha air can be directed with a corrugated tube for the Extruder motor and the radiator. For the X, Y and Z motors can be a rigid tube. </p> <p>This cooling fans won't affect the internal chamber temperature due the cooling process is punctual. </p> <p>4.- Many electronics components are designed to work at 105°, so won't be affected in short terms, however the life of circutry will decrease a lot, since designs cover until 5 years at normal conditions so your printer can last up to 1.5 years.</p> <p>Recommendations:</p> <p>I don't see a real reason to keep the printer isolated to high temperatures while the porpuse of this is to keep temperature variations from clime like winter and summer. In my case the print room has a normal temperature of 38°C on summers and -2°C on winter, so how can I print with the same quality on winter if the printer is so cold? <em>ah, I need a chamber to keep that temperature of summer</em>. then I made the chamber to acheive 38°C not the whole temperature of the bed print. </p> <p>If I need to print ABS so I set the bed temperature to 80°C so the parts won´t get warped, due the temperature for adhesive for ABS is the correct; also this temperature won´t over heat the chamber at least near to 60°C, but can it be reduced extracting the heat with other fan. For this case is just only one or two fans.</p> <p><a href="https://i.stack.imgur.com/KPzRf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KPzRf.jpg" alt="enter image description here"></a></p> <p>Note: The Idea to have the whole printer inside an oven will help to keep that 80°-95°C under control is good, but some times is hard to implement it due materials and its purposes are different and serviseable life will be too low.</p> <p>So your chamber should include the printing area only or follow the recommendation as the picture above. Those photo was taken from the site <a href="https://www.engineering.com/3DPrinting/3DPrintingArticles/ArticleID/5353/A-New-Industrial-RepRap-Emerges.aspx" rel="nofollow noreferrer">industrial RepRap</a> and also exposes som e features as i'm suggesting.</p>
1,429
<p>I am looking for a better solution than what we currently have to deal with <strong>unexpected production errors</strong>, without reinventing the wheel.</p> <p>A larger number of our products are WinForm and WPF applications that are installed at remote sites. Inevitably unexpected errors occur, from NullReferenceExceptions to 'General network errors'. Thus ranging from programmer errors to environment problems.</p> <p>Currently all these unhandled exceptions are logged using log4net and then emailed back to us for <strong>analysis</strong>. However we found that sometimes these error 'reports' contain too little information to identify the problem. </p> <p>In these reports we need information such as:</p> <ol> <li>Application name</li> <li>Application Version</li> <li>Workstation</li> <li>Maybe a screen shot</li> <li>Exception details</li> <li>Operating system</li> <li>Available RAM </li> <li>Running processes</li> <li>And so on...</li> </ol> <p>I don't really want to re-invent the wheel by developing this from scratch. Components that are required:</p> <ol> <li>Error collection (details as mentioned above)</li> <li>Error 'sender' (Queuing required if DB or Internet is unavailable)</li> <li>Error database</li> <li>Analysis and reporting of these errors. E.g. 10 most frequent errors or timeouts occur between 4:00PM and 5:00PM. How do the errors compare between version x and y?</li> </ol> <p>Note: We looked at <a href="http://www.smartassembly.com" rel="nofollow noreferrer">SmartAssembly</a> as a possible solution but although close it didn't quite met our needs and I was hoping to hear what other developers do and if some alternatives exist.</p> <p><strong>Edit:</strong> Thanks for the answers so far. Maybe I wasn't clear in my original question, the problem is not how to catch all unhanded exceptions but rather how to deal with them and to create a reporting engine (analysis) around them.</p>
<p>I'd suggest Jeff Atwood's article on <a href="http://www.codeproject.com/KB/exception/ExceptionHandling.aspx" rel="nofollow noreferrer">User Friendly Exception Handling</a>, which does most of what you ask already (Application Info, Screenshot, Exception Details, OS, Logging to text files and Emailing), and contains the source code so you add the extra stuff you need.</p>
<p>You may want to study the error reporting feature built into JetBrain's <a href="http://www.jetbrains.com/omea/reader/" rel="nofollow noreferrer">Omea Reader</a>. It has a catch-all error-handling component that pops a dialog when an unexpected error occurs. The user can input more details before submitting the problem to JetBrain's public error-collection web service.</p> <p>They made Omea open source to allow the community to upgrade the .NET 1.1 code base to v2 or 3. <a href="http://www.jetbrains.net/confluence/display/OMEA/this+link" rel="nofollow noreferrer">http://www.jetbrains.net/confluence/display/OMEA/this+link</a></p>
13,574
<p>Context: I'm in charge of running a service written in .NET. Proprietary application. It uses a SQL Server database. It ran as a user member of the Administrators group in the local machine. It worked alright before I added the machine to a domain.</p> <p>So, I added the machine to a domain (Win 2003) and changed the user to a member of the Power Users group and now, the</p> <p>Problem: Some of the SQL sentences it tries to execute are "magically" in spanish localization (where , separates floating point numbers instead of .), leading to errors. </p> <blockquote> <p>There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)</p> </blockquote> <p>Operating System and Regional Settings in the machine are in English. I asked the provider of the application and he said:</p> <blockquote> <p>Looks like you have a combination of code running under Spanish locale, and SQL server under English locale. So the SQL expects '15.28' and not '15,28'</p> </blockquote> <p>Which looks wrong to me in various levels (how can SQL Server distinguish between commas to separate arguments and commas belonging to a floating point number?).</p> <p>So, the code seems to be grabbing the spanish locale from somewhere, I don't know if it's the user it runs as, or someplace else (global policy, maybe?). But the question is</p> <p>What are the places where localization is defined on a machine/user/domain basis?</p> <p>I don't know all the places I must search for the culprit, so please help me to find it!</p>
<p>There are two types of localisation in .NET, both the settings for the cultures can be found in these variables (fire up a .NET command line app on the machine to see what it says):</p> <p>System.Thread.CurrentThread.CurrentCulture &amp; System.Thread.CurrentThread.CurrentUICulture</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.threading.thread_members.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.threading.thread_members.aspx</a></p> <p>They relate to the settings in the control panel (in the regional settings part). Create a .NET command line app, then just call ToString() on the above properties, that should tell you which property to look at.</p> <p><strong>Edit:</strong></p> <p>It turns out the setting for the locales per user are held here:</p> <pre><code>HKEY_CURRENT_USER\Control Panel\International </code></pre> <p>It might be worth inspecting the registry of the user with the spanish locale, and comparing it to one who is set to US or whichever locale you require.</p>
<p>Great, I created the console app and indeed, the app is not crazy, CurrentCulture is in spanish, but for THAT User in THAT machine only. If I run the console app as another user it returns english for all cultures.</p> <p>Should I open a new question asking where are user-wise locale settings?</p>
8,347
<p>I installed the ReSharper evaluation version and uninstalled it. Afterwards Visual Studio's Intellisense stopped working. I have restarted computer but I still have this problem. </p> <p>Can anyone please help me here?</p> <p>I am using Visual Studio 2005. Thanks.</p>
<p>Try opening Visual Studio Command Prompt and entering:</p> <pre><code>devenv.exe /ResetSettings </code></pre>
<p>I would try a "repair" on the installation first. Control Panel, Add/Remove Programs, select Microsoft Visual Studio 2005, click "Change/Remove". It will load up the install dialog and give you the option to do a "repair".</p> <p>YMMV, but at least it should reset a lot of the VS resources to their "fresh" state.</p>
21,560
<p>I need to script the creation of app pools and websites on IIS 6.0. I have been able to create these using adsutil.vbs and iisweb.vbs, but don't know how to set the version of ASP.NET for the sites I have just created to 2.0.50727.0.</p> <p>Ideally I would like to adsutil.vbs to update the metabase. How do I do this?</p>
<p>@<a href="https://stackoverflow.com/questions/20923/vbscriptiis-how-do-i-automatically-set-aspnet-version-for-a-particular-website#20953">Chris</a> beat me to the punch on the ADSI way</p> <p>You can do this using the aspnet_regiis.exe tool. There is one of these tools per version of ASP.NET installed on the machine. You could shell out to -</p> <p>This configures ASP.NET 1.1</p> <pre><code>%windir%\microsoft.net\framework\v1.1.4322\aspnet_regiis -s W3SVC/[iisnumber]/ROOT </code></pre> <p>This configures ASP.NET 2.0</p> <pre><code>%windir%\microsoft.net\framework\v2.0.50727\aspnet_regiis -s W3SVC/[iisnumber]/ROOT </code></pre> <p>You probably already know this, but if you have multiple 1.1 and 2.0 sites on your machine, just remember to switch the website you're changing ASP.NET versions on to compatible app pool. ASP.NET 1.1 and 2.0 sites don't mix in the same app pool.</p>
<p>I found the following script <a href="http://www.diablopup.net/post/Set-an-IIS-Object%27s-ASPNET-Version-Using-VBScript.aspx" rel="nofollow noreferrer">posted</a> on Diablo Pup's blog. It uses ADSI automation.</p> <pre><code>'****************************************************************************************** ' Name: SetASPDotNetVersion ' Description: Set the script mappings for the specified ASP.NET version ' Inputs: objIIS, strNewVersion '****************************************************************************************** Sub SetASPDotNetVersion(objIIS, strNewVersion) Dim i, ScriptMaps, arrVersions(2), thisVersion, thisScriptMap Dim strSearchText, strReplaceText Select Case Trim(LCase(strNewVersion)) Case "1.1" strReplaceText = "v1.1.4322" Case "2.0" strReplaceText = "v2.0.50727" Case Else wscript.echo "WARNING: Non-supported ASP.NET version specified!" Exit Sub End Select ScriptMaps = objIIS.ScriptMaps arrVersions(0) = "v1.1.4322" arrVersions(1) = "v2.0.50727" 'Loop through all three potential old values For Each thisVersion in arrVersions 'Loop through all the mappings For thisScriptMap = LBound(ScriptMaps) to UBound(ScriptMaps) 'Replace the old with the new ScriptMaps(thisScriptMap) = Replace(ScriptMaps(thisScriptMap), thisVersion, strReplaceText) Next Next objIIS.ScriptMaps = ScriptMaps objIIS.SetInfo wscript.echo "&lt;-------Set ASP.NET version to " &amp; strNewVersion &amp; " successfully.-------&gt;" End Sub </code></pre>
4,129
<p>I am having a number of panels in my page in which I am collecting user information and saving the page details. The page panel has textbox, dropdown list, listbox.</p> <p>When I need to come to this page. I need to show the Page if these controls have any values. How to do this?</p>
<p>It boils down to enumerating all the controls in the control hierarchy:</p> <pre><code> IEnumerable&lt;Control&gt; EnumerateControlsRecursive(Control parent) { foreach (Control child in parent.Controls) { yield return child; foreach (Control descendant in EnumerateControlsRecursive(child)) yield return descendant; } } </code></pre> <p>You can use it like this:</p> <pre><code> foreach (Control c in EnumerateControlsRecursive(Page)) { if(c is TextBox) { // do something useful } } </code></pre>
<p>Depeding on which UI library or language you are using, container controls such as panels maintain a list of child controls. To test if a form/page has any data you need to recursively search each panel for data entry controls such as text boxes. Then test if any of the data entry controls contain values other than default value.</p> <p>A simpler solutions would be to implement an observer class that attaches to the changed events of your data controls. If the observer is triggered then your page has changes. You will need to take into consideration actions such as changing and then reverting data. </p>
35,044
<p>Are there any ports to WPF of Silverlight's MultiScaleImage (aka DeepZoom)? Have Microsoft road-mapped this at all for WPF?</p> <p>I want to move from WinForms to WPF and require something like DeepZoom, using Silverlight isn't an option.</p>
<p>At the moment there is no port. However, DeepZoom is based on the technology found in the "World Wide Telescope" and the "Microsoft Photo Synth", so they have desktop versions of the technology running. I guess it would be safe to assume that Microsoft will be releasing a multi scale image control for WPF soon. If you just want the "panning and zooming", and don't care about the efficient breakdown of high resolution images you can certainly achieve the same effects in WPF. This post is <a href="http://blogs.windowsclient.net/joeyw/archive/2008/08/05/pan-and-zoom-deepzoom-style-in-wpf.aspx" rel="nofollow noreferrer">one example on how to do zoom and pan</a>.</p>
<p>Sad bit of news (or 'rumor'?)... in this <a href="http://blogs.msdn.com/jaimer/archive/2009/05/27/wpf-4-and-net-framework-4-beta-1-list-of-features-totrack.aspx" rel="nofollow noreferrer">List of features to track in WPF4 </a>, Jaime says</p> <p>"Note: At PDC, we said that DeepZoom would be in WPF4. Unfortunately that feature has been cut. We just could not squeeze it into the schedule. There are workarounds to it: you can host Silverlight inWPF using web browser control or using the <a href="http://msdn.microsoft.com/en-us/library/cc296246(VS.95).aspx" rel="nofollow noreferrer">Silverlight hosting APIs</a>. "</p> <p>I guess those <a href="http://msdn.microsoft.com/en-us/library/cc296246(VS.95).aspx" rel="nofollow noreferrer">hosting APIs</a> might be useful if you're brave - but I'm guessing just putting a Silverlight object inside a WPF WebBrowser control would be simpler...</p>
9,317
<p>I'm building a project using a GNU tool chain and everything works fine until I get to linking it, where the linker complains that it is missing/can't find <code>crti.o</code>. This is not one of my object files, it seems to be related to libc but I can't understand why it would need this <code>crti.o</code>, wouldn't it use a library file, e.g. <code>libc.a</code>?</p> <p>I'm cross compiling for the arm platform. I have the file in the toolchain, but how do I get the linker to include it? </p> <p><code>crti.o</code> is on one of the 'libraries' search path, but should it look for <code>.o</code> file on the library path? </p> <p>Is the search path the same for <code>gcc</code> and <code>ld</code>?</p>
<p><code>crti.o</code> is the bootstrap library, generally quite small. It's usually statically linked into your binary. It should be found in <code>/usr/lib</code>.</p> <p>If you're running a binary distribution they tend to put all the developer stuff into -dev packages (e.g. libc6-dev) as it's not needed to run compiled programs, just to build them.</p> <p>You're not cross-compiling are you? </p> <p>If you're cross-compiling it's usually a problem with gcc's search path not matching where your crti.o is. It should have been built when the toolchain was. The first thing to check is <code>gcc -print-search-dirs</code> and see if crti.o is in any of those paths.</p> <p>The linking is actually done by ld but it has its paths passed down to it by gcc. Probably the quickest way to find out what's going on is compile a helloworld.c program and strace it to see what is getting passed to ld and see what's going on.</p> <pre><code>strace -v -o log -f -e trace=open,fork,execve gcc hello.c -o test </code></pre> <p>Open the log file and search for crti.o, as you can see my non-cross compiler:</p> <pre><code>10616 execve("/usr/bin/ld", ["/usr/bin/ld", "--eh-frame-hdr", "-m", "elf_x86_64", "--hash-style=both", "-dynamic-linker", "/lib64/ld-linux-x86-64.so.2", "-o" , "test", "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "-L/usr/lib/gcc/x86_64-linux-g nu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/lib/../lib", "-L/usr/lib/../lib", "-L/usr/lib/gcc/x86_64-linux-gnu /"..., "/tmp/cc4rFJWD.o", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "-lc", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "/usr/lib/gcc/x86_ 64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."...], "COLLECT_GCC=gcc", "COLLECT_GCC_OPTIONS=\'-o\' \'test\' "..., "COMPILER_PATH=/usr/lib/gcc/x86_6"..., "LIBRARY_PATH=/usr/lib/gcc/x86_64"..., "CO LLECT_NO_DEMANGLE="]) = 0 10616 open("/etc/ld.so.cache", O_RDONLY) = 3 10616 open("/usr/lib/libbfd-2.18.0.20080103.so", O_RDONLY) = 3 10616 open("/lib/libc.so.6", O_RDONLY) = 3 10616 open("test", O_RDWR|O_CREAT|O_TRUNC, 0666) = 3 10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crt1.o", O_RDONLY) = 4 10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crti.o", O_RDONLY) = 5 10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/crtbegin.o", O_RDONLY) = 6 10616 open("/tmp/cc4rFJWD.o", O_RDONLY) = 7 </code></pre> <p>If you see a bunch of attempts to <code>open(...crti.o) = -1 ENOENT</code>, <code>ld</code> is getting confused and you want to see where the path it's opening came from...</p>
<p>I get the same kind of issue on a default Ubuntu 8.04 install. I had to get the libc developer headers/files manually for it to work.</p>
11,698
<p>I have seen the error "The ';' character, hexadecimal value 0x3B, cannot be included in a name." in my log files for an ASP.NET Web App. The url that's logged looks something like this:</p> <pre><code>mypage.aspx?paramone=one+two&amp;amp;paramtwo=zero+1 </code></pre> <p>So my first question is what type of system/browser is encoding the original query string? (This happens rarely)</p> <p>I've tried to address this problem with the following snippet of code in the Page_Load() event:</p> <pre><code>string rawUrl = Request.RawUrl; if (rawUrl.Contains(amp)) { rawUrl = rawUrl.Replace("&amp;amp;", "&amp;"); Server.Transfer(rawUrl, false); return; } </code></pre> <p>However when it transfers back to this page the <code>&amp;amp;</code> is back in the query string. So I'm guessing that the .Transfer() function encodes the first param.</p> <p>Suggestions about solving this problem?</p>
<ol> <li><p>Your web server should be able to log the "user agent" field from the HTTP Request, which should enable you to identify the culprit.</p></li> <li><p>Don't fix it - there's a very well defined set of legal syntaxes for URI parameters, and this ain't one of them.</p></li> </ol>
<p>When you try to export a Microsoft catalog to XML, the resulting file cannot be imported, and you receive the following error message "The XML file path/filename contains an error at line. " "A Name contained an invalid character."</p> <p>If you validate the XML catalog by using Microsoft Visual Studio .NET you receive the following error message:</p> <p>"The '(' character, hexadecimal value 0x28, cannot begin a name. Line #, Position #"</p> <p>This problem occurs because the Commerce Server export was not encoding the following special characters:</p> <pre><code>The range 0x0021 – 0x002F includes ! “ # $ % &amp; ‘ ( ) * + , - . / The range 0x03A – 0x0040 includes : ; &lt; = &gt; ? @ The range 0x007B – 0x007E includes { | } ~ The range 0x005B – 0x005E [ \ ] ^** </code></pre>
41,523
<p><strong>Edit:</strong> This was accidentally posted twice. Original: <a href="https://stackoverflow.com/questions/243900/vb-net-importing-classes">VB.NET Importing Classes</a></p> <p>I've seen some code where a <em>Class</em> is imported, instead of a namespace, making all the static members/methods of that class available. Is this a feature of VB? Or do other languages do this as well?</p> <p>TestClass.vb</p> <pre><code>public class TestClass public shared function Somefunc() as Boolean return true end function end class </code></pre> <p>MainClass.vb</p> <pre><code>imports TestClass public class MainClass public sub Main() Somefunc() end sub end class </code></pre> <p>These files are in the App_Code directory. Just curious, because I've never thought of doing this before, nor have I read about it anywhere. </p>
<p>Having written the MyBlogLog plugin (the original one, that is) I found that the Wordpress Hooks list (can't remember the link offhand) was incredibly useful, as was the sample code from the Codex and WP Install files. Reading through other developer's plugins is also a good way to learn, as you can see how they implemented things and use those techniques to save yourself some R&amp;D time.</p> <p>What are you looking to create, anyways?</p> <p><strong>Edit:</strong></p> <p>I posted a comment with this, but just in case it gets lost...</p> <p>For your specific needs, you're going to want to store data and be able to manage and retrieve it so creating a custom database table in your plugin is something you will want to do. See this codex link:</p> <p><a href="http://codex.wordpress.org/Creating_Tables_with_Plugins" rel="noreferrer">http://codex.wordpress.org/Creating_Tables_with_Plugins</a></p> <p>Then you can just add your management code into the admin screens using the techniques found on this Codex page:</p> <p><a href="http://codex.wordpress.org/Adding_Administration_Menus" rel="noreferrer">http://codex.wordpress.org/Adding_Administration_Menus</a></p> <p>If you want to display the items on a page, you can either write yourself a custom PHP WP Page template to query the DB directly:</p> <p><a href="http://codex.wordpress.org/Pages#Page_Templates" rel="noreferrer">http://codex.wordpress.org/Pages#Page_Templates</a></p> <p>Or just add a hook filter on your plugin to write the results to the page based on a keyword you specify:</p> <p><a href="http://codex.wordpress.org/Plugin_API#Filters" rel="noreferrer">http://codex.wordpress.org/Plugin_API#Filters</a></p>
<p>Although technically still information found within the Codex, the Codex contains links to external resources. Apologies for not posting a direct link, but look again, and you should find them.</p>
30,221
<p>Code like this often happens:</p> <pre><code>l = [] while foo: # baz l.append(bar) # qux </code></pre> <p>This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.</p> <p>In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.</p> <p>I understand that code like this can often be refactored into a list comprehension. If the <em>for</em>/<em>while</em> loop is very complicated, though, this is unfeasible. Is there an equivalent for us Python programmers?</p>
<h2>Warning: This answer is contested. See comments.</h2> <pre><code>def doAppend( size=10000 ): result = [] for i in range(size): message= &quot;some unique object %d&quot; % ( i, ) result.append(message) return result def doAllocate( size=10000 ): result=size*[None] for i in range(size): message= &quot;some unique object %d&quot; % ( i, ) result[i]= message return result </code></pre> <p><strong>Results</strong>. (evaluate each function 144 times and average the duration)</p> <pre><code>simple append 0.0102 pre-allocate 0.0098 </code></pre> <p><strong>Conclusion</strong>. It barely matters.</p> <p>Premature optimization is the root of all evil.</p>
<p>From what I understand, Python lists are already quite similar to ArrayLists. But if you want to tweak those parameters I found this post on the Internet that may be interesting (basically, just create your own <code>ScalableList</code> extension):</p> <p><a href="http://mail.python.org/pipermail/python-list/2000-May/035082.html" rel="nofollow noreferrer">http://mail.python.org/pipermail/python-list/2000-May/035082.html</a></p>
40,179
<p>I get the following error while building OpenCV on OS X 10.5 (intel):</p> <pre><code>ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture ld: warning in .libs/_cv_la-error.o, file is not of required architecture ld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture ld: warning in .libs/_cv_la-cvshadow.o, file is not of required architecture ld: warning in ../../../cv/src/.libs/libcv.dylib, file is not of required architecture ld: warning in /Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib/libcxcore.dylib, file is not of required architecture Undefined symbols for architecture i386: "_fputs$UNIX2003", referenced from: _PySwigObject_print in _cv_la-_cv.o _PySwigPacked_print in _cv_la-_cv.o _PySwigPacked_print in _cv_la-_cv.o ld: symbol(s) not found for architecture i386 collect2: ld returned 1 exit status lipo: can't open input file: /var/folders/Sr/Srq9N4R8Hr82xeFvW3o-uk+++TI/-Tmp-//cchT0WVX.out (No such file or directory) make[4]: *** [_cv.la] Error 1 make[3]: *** [all-recursive] Error 1 make[2]: *** [all-recursive] Error 1 make[1]: *** [all-recursive] Error 1 make: *** [all] Error 2 </code></pre> <p>While running ./configure --without-python everything is ok. Another strange thing is that when I used Python 2.4.5 or 2.5.1 everything has built ok, the problem occured after switching to Python Framework 2.5.2</p>
<p>It seems a little weird that it is warning about different architectures when looking for /Developer/SDKs/MacOSX10.4u.sdk while linking - can you give us some more detail about your build environment (version of XCode, GCC, Python, $PATH etc)</p> <p>Alternatively, won't any of the OpenCV binaries available work for you?</p>
<p>/Developer/SDKs/MacOSX10.4u.sdk/usr/local/lib is just a link to /usr/local/lib after deleting files that caused the warnings I'm getting :</p> <pre><code>ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture ld: warning in .libs/_cv_la-error.o, file is not of required architecture ld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture ld: warning in .libs/_cv_la-cvshadow.o, file is not of required architecture ld: warning in ../../../cv/src/.libs/libcv.dylib, file is not of required architecture ld: warning in /Users/Pietras/opencv/cxcore/src/.libs/libcxcore.dylib, file is not of required architecture Undefined symbols for architecture i386: ... ` </code></pre> <p>And these files are created by make.</p> <p>gcc: i686-apple-darwin9-gcc-4.0.1</p> <p>$PATH:</p> <pre><code>/Library/Frameworks/Python.framework/Versions/Current/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/sw/bin:/sw/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/AVRMacPack/bin:/usr/X11R6/bin </code></pre> <p>XCode 3 (latest)</p> <p>Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) - MacPython from python.org (tried to downgrade and use it instead of 2.5.2, but that doesn't work anymore...)</p> <pre><code>which python /Library/Frameworks/Python.framework/Versions/Current/bin/python </code></pre> <p>I didn't find any Python OpenCV binaries for OS X. I've tried to make it while setting python2.4 or 2.5 from macports as default and it compiles and installs, but when I try to import there is a bus error or Fatal Python error Interpreter not initialized (version mismatch?) and it quits.</p>
40,777
<p>Suppose you're working on an enterprise project in which you have to get management signoff in order for you to develop a new feature set. Usually your management has no problem signing off on some bright shiny new UI feature. Unfortunately they have a hard time appreciating some behind-the-scenes issues that are crucial to the application's well-being such as transactions, data integrity, workflow routing, configurability, security, etc. Since they're non-technical and these issues are not immediately visible, it's not obvious to them that this is crucial.</p> <p>How have you convinced them that these infrastructural issues have to be dealt with and that it is important to their business process?</p>
<p>Every craft has its unsexy sides. Things that HAVE to be done, but nobody notices them directly. In a grocery store somebody has to organize how and when to fill the grocery shelves so they always look fresh. In a laundry you need somebody who thinks about how the processes should be optimized so that the customer gets his clothes in time. </p> <p>The tricky part is: The customer won't notice when these subtle things have been done right UNTIL HE NOTICES THEY ARE MISSING! Like when the laundry is not ready on time but two days late, or the veggies in the super market have brown spots and look terrible. </p> <p>Same goes for IT. You don't notice good transactions until your major customer knocks on your door and tells you that an important and expensive project has failed because the database entries of your product were mysteriously mixed up. You don't notice good security until customer credit card information shows up in <a href="http://en.wikipedia.org/wiki/Elbonia" rel="noreferrer">Elbonia</a> (and soon after word is in the national newspapers warning customers of your company). </p> <p>The thing you really have to hammer in again and again and again is that software is NOT static. It has to be cared for even after its initial development phase is over. It is not just a product you buy once and forget about. Every car manufacturer knows that services is of prime importance to the products they build, simply because things WILL occur that have to be fixed and improved. It's the same with software.</p> <p>So make a presentation, visualize, verbalize, translate your technical information into benefits. Business people don't care about your wish for code aesthetics in a refactoring project, but they WILL understand that your changes will help the product to become more reliable, gain a better reputation and reduce the amount of future service requests. Make them understand by showing them the benefits!</p>
<p>Robustness. When it comes down to it, you need to talk their language, which is how it affects their bottom line. If its a security or correctness issue, you need to tell them that customers aren't going to want incorrectly acting products, no matter how nice they look.</p>
20,488
<p>I would like to make 2 TB or so available via NFS and CIFS. I am looking for a 2 (or more) server solution for high availability and the ability to load balance across the servers if possible. Any suggestions for clustering or high availability solutions?</p> <p>This is business use, planning on growing to 5-10 TB over next few years. Our facility is almost 24 hours a day, six days a week. We could have 15-30 minutes of downtime, but we want to minimize data loss. I want to minimize 3 AM calls. </p> <p>We are currently running one server with ZFS on Solaris and we are looking at AVS for the HA part, but we have had minor issues with Solaris (CIFS implementation doesn't work with Vista, etc) that have held us up. </p> <p>We have started looking at </p> <ul> <li>DRDB over GFS (GFS for distributed lock capability)</li> <li>Gluster (needs client pieces, no native CIFS support?)</li> <li>Windows DFS (doc says only replicates after file closes?)</li> </ul> <p>We are looking for a "black box" that serves up data.</p> <p>We currently snapshot the data in ZFS and send the snapshot over the net to a remote datacenter for offsite backup.</p> <p>Our original plan was to have a 2nd machine and rsync every 10 - 15 min. The issue on a failure would be that ongoing production processes would lose 15 minutes of data and be left "in the middle". They would almost be easier to start from the beginning than to figure out where to pickup in the middle. That is what drove us to look at HA solutions.</p>
<p>I've recently deployed hanfs using DRBD as the backend, in my situation, I'm running active/standby mode, but I've tested it successfully using OCFS2 in primary/primary mode too. There unfortunately isn't much documentation out there on how best to achieve this, most that exists is barely useful at best. If you do go along the drbd route, I highly recommend joining the drbd mailing list, and reading all of the documentation. Here's my ha/drbd setup and script I wrote to handle ha's failures:</p> <hr> <p>DRBD8 is required - this is provided by drbd8-utils and drbd8-source. Once these are installed (I believe they're provided by backports), you can use module-assistant to install it - m-a a-i drbd8. Either depmod -a or reboot at this point, if you depmod -a, you'll need to modprobe drbd.</p> <p>You'll require a backend partition to use for drbd, do not make this partition LVM, or you'll hit all sorts of problems. Do not put LVM on the drbd device or you'll hit all sorts of problems.</p> <p>Hanfs1:</p> <pre><code> /etc/drbd.conf global { usage-count no; } common { protocol C; disk { on-io-error detach; } } resource export { syncer { rate 125M; } on hanfs2 { address 172.20.1.218:7789; device /dev/drbd1; disk /dev/sda3; meta-disk internal; } on hanfs1 { address 172.20.1.219:7789; device /dev/drbd1; disk /dev/sda3; meta-disk internal; } }</code></pre> <p>Hanfs2's /etc/drbd.conf:</p> <p><pre><code> global { usage-count no; } common { protocol C; disk { on-io-error detach; } } resource export { syncer { rate 125M; } on hanfs2 { address 172.20.1.218:7789; device /dev/drbd1; disk /dev/sda3; meta-disk internal; } on hanfs1 { address 172.20.1.219:7789; device /dev/drbd1; disk /dev/sda3; meta-disk internal; } }</pre></code></p> <p>Once configured, we need to bring up drbd next.</p> <pre> drbdadm create-md export drbdadm attach export drbdadm connect export </pre> <p>We must now perform an initial synchronization of data - obviously, if this is a brand new drbd cluster, it doesn't matter which node you choose.</p> <p></p> <p>Once done, you'll need to mkfs.yourchoiceoffilesystem on your drbd device - the device in our config above is /dev/drbd1. <a href="http://www.drbd.org/users-guide/p-work.html" rel="noreferrer">http://www.drbd.org/users-guide/p-work.html</a> is a useful document to read while working with drbd.</p> <p>Heartbeat</p> <p>Install heartbeat2. (Pretty simple, apt-get install heartbeat2).</p> <p>/etc/ha.d/ha.cf on each machine should consist of:</p> <p>hanfs1: <pre><code> logfacility local0 keepalive 2 warntime 10 deadtime 30 initdead 120</p> <p>ucast eth1 172.20.1.218</p> <p>auto_failback no</p> <p>node hanfs1 node hanfs2 </pre></code></p> <p>hanfs2:</p> <p><pre><code> logfacility local0 keepalive 2 warntime 10 deadtime 30 initdead 120</p> <p>ucast eth1 172.20.1.219</p> <p>auto_failback no</p> <p>node hanfs1 node hanfs2 </pre></code></p> <p>/etc/ha.d/haresources should be the same on both ha boxes:</p> <pre> hanfs1 IPaddr::172.20.1.230/24/eth1 hanfs1 HeartBeatWrapper</pre> <p>I wrote a wrapper script to deal with the idiosyncracies caused by nfs and drbd in a failover scenario. This script should exist within /etc/ha.d/resources.d/ on each machine.</p> <p><pre><code></p> <h1>!/bin/bash</h1> <h1>heartbeat fails hard.</h1> <h1>so this is a wrapper</h1> <h1>to get around that stupidity</h1> <h1>I'm just wrapping the heartbeat scripts, except for in the case of umount</h1> <h1>as they work, mostly</h1> <p>if [[ -e /tmp/heartbeatwrapper ]]; then runningpid=$(cat /tmp/heartbeatwrapper) if [[ -z $(ps --no-heading -p $runningpid) ]]; then echo "PID found, but process seems dead. Continuing." else<br> echo "PID found, process is alive, exiting."<br> exit 7<br> fi<br> fi </p> <p>echo $$ > /tmp/heartbeatwrapper</p> <p>if [[ x$1 == "xstop" ]]; then</p> <p>/etc/init.d/nfs-kernel-server stop #>/dev/null 2>&amp;1</p> <h1>NFS init script isn't LSB compatible, exit codes are 0 no matter what happens.</h1> <h1>Thanks guys, you really make my day with this bullshit.</h1> <h1>Because of the above, we just have to hope that nfs actually catches the signal</h1> <h1>to exit, and manages to shut down its connections.</h1> <h1>If it doesn't, we'll kill it later, then term any other nfs stuff afterwards.</h1> <h1>I found this to be an interesting insight into just how badly NFS is written.</h1> <p>sleep 1</p> <pre><code>#we don't want to shutdown nfs first! #The lock files might go away, which would be bad. #The above seems to not matter much, the only thing I've determined #is that if you have anything mounted synchronously, it's going to break #no matter what I do. Basically, sync == screwed; in NFSv3 terms. #End result of failing over while a client that's synchronous is that #the client hangs waiting for its nfs server to come back - thing doesn't #even bother to time out, or attempt a reconnect. #async works as expected - it insta-reconnects as soon as a connection seems #to be unstable, and continues to write data. In all tests, md5sums have #remained the same with/without failover during transfer. #So, we first unmount /export - this prevents drbd from having a shit-fit #when we attempt to turn this node secondary. #That's a lie too, to some degree. LVM is entirely to blame for why DRBD #was refusing to unmount. Don't get me wrong, having /export mounted doesn't #help either, but still. #fix a usecase where one or other are unmounted already, which causes us to terminate early. if [[ "$(grep -o /varlibnfs/rpc_pipefs /etc/mtab)" ]]; then for ((test=1; test &lt;= 10; test++)); do umount /export/varlibnfs/rpc_pipefs &gt;/dev/null 2&gt;&amp;1 if [[ -z $(grep -o /varlibnfs/rpc_pipefs /etc/mtab) ]]; then break fi if [[ $? -ne 0 ]]; then #try again, harder this time umount -l /var/lib/nfs/rpc_pipefs &gt;/dev/null 2&gt;&amp;1 if [[ -z $(grep -o /varlibnfs/rpc_pipefs /etc/mtab) ]]; then break fi fi done if [[ $test -eq 10 ]]; then rm -f /tmp/heartbeatwrapper echo "Problem unmounting rpc_pipefs" exit 1 fi fi if [[ "$(grep -o /dev/drbd1 /etc/mtab)" ]]; then for ((test=1; test &lt;= 10; test++)); do umount /export &gt;/dev/null 2&gt;&amp;1 if [[ -z $(grep -o /dev/drbd1 /etc/mtab) ]]; then break fi if [[ $? -ne 0 ]]; then #try again, harder this time umount -l /export &gt;/dev/null 2&gt;&amp;1 if [[ -z $(grep -o /dev/drbd1 /etc/mtab) ]]; then break fi fi done if [[ $test -eq 10 ]]; then rm -f /tmp/heartbeatwrapper echo "Problem unmount /export" exit 1 fi fi #now, it's important that we shut down nfs. it can't write to /export anymore, so that's fine. #if we leave it running at this point, then drbd will screwup when trying to go to secondary. #See contradictory comment above for why this doesn't matter anymore. These comments are left in #entirely to remind me of the pain this caused me to resolve. A bit like why churches have Jesus #nailed onto a cross instead of chilling in a hammock. pidof nfsd | xargs kill -9 &gt;/dev/null 2&gt;&amp;1 sleep 1 if [[ -n $(ps aux | grep nfs | grep -v grep) ]]; then echo "nfs still running, trying to kill again" pidof nfsd | xargs kill -9 &gt;/dev/null 2&gt;&amp;1 fi sleep 1 /etc/init.d/nfs-kernel-server stop #&gt;/dev/null 2&gt;&amp;1 sleep 1 #next we need to tear down drbd - easy with the heartbeat scripts #it takes input as resourcename start|stop|status #First, we'll check to see if it's stopped /etc/ha.d/resource.d/drbddisk export status &gt;/dev/null 2&gt;&amp;1 if [[ $? -eq 2 ]]; then echo "resource is already stopped for some reason..." else for ((i=1; i &lt;= 10; i++)); do /etc/ha.d/resource.d/drbddisk export stop &gt;/dev/null 2&gt;&amp;1 if [[ $(egrep -o "st:[A-Za-z/]*" /proc/drbd | cut -d: -f2) == "Secondary/Secondary" ]] || [[ $(egrep -o "st:[A-Za-z/]*" /proc/drbd | cut -d: -f2) == "Secondary/Unknown" ]]; then echo "Successfully stopped DRBD" break else echo "Failed to stop drbd for some reason" cat /proc/drbd if [[ $i -eq 10 ]]; then exit 50 fi fi done fi rm -f /tmp/heartbeatwrapper exit 0 </code></pre> <p>elif [[ x$1 == "xstart" ]]; then</p> <pre><code>#start up drbd first /etc/ha.d/resource.d/drbddisk export start &gt;/dev/null 2&gt;&amp;1 if [[ $? -ne 0 ]]; then echo "Something seems to have broken. Let's check possibilities..." testvar=$(egrep -o "st:[A-Za-z/]*" /proc/drbd | cut -d: -f2) if [[ $testvar == "Primary/Unknown" ]] || [[ $testvar == "Primary/Secondary" ]] then echo "All is fine, we are already the Primary for some reason" elif [[ $testvar == "Secondary/Unknown" ]] || [[ $testvar == "Secondary/Secondary" ]] then echo "Trying to assume Primary again" /etc/ha.d/resource.d/drbddisk export start &gt;/dev/null 2&gt;&amp;1 if [[ $? -ne 0 ]]; then echo "I give up, something's seriously broken here, and I can't help you to fix it." rm -f /tmp/heartbeatwrapper exit 127 fi fi fi sleep 1 #now we remount our partitions for ((test=1; test &lt;= 10; test++)); do mount /dev/drbd1 /export &gt;/tmp/mountoutput if [[ -n $(grep -o export /etc/mtab) ]]; then break fi done if [[ $test -eq 10 ]]; then rm -f /tmp/heartbeatwrapper exit 125 fi #I'm really unsure at this point of the side-effects of not having rpc_pipefs mounted. #The issue here, is that it cannot be mounted without nfs running, and we don't really want to start #nfs up at this point, lest it ruin everything. #For now, I'm leaving mine unmounted, it doesn't seem to cause any problems. #Now we start up nfs. /etc/init.d/nfs-kernel-server start &gt;/dev/null 2&gt;&amp;1 if [[ $? -ne 0 ]]; then echo "There's not really that much that I can do to debug nfs issues." echo "probably your configuration is broken. I'm terminating here." rm -f /tmp/heartbeatwrapper exit 129 fi #And that's it, done. rm -f /tmp/heartbeatwrapper exit 0 </code></pre> <p>elif [[ "x$1" == "xstatus" ]]; then</p> <pre><code>#Lets check to make sure nothing is broken. #DRBD first /etc/ha.d/resource.d/drbddisk export status &gt;/dev/null 2&gt;&amp;1 if [[ $? -ne 0 ]]; then echo "stopped" rm -f /tmp/heartbeatwrapper exit 3 fi #mounted? grep -q drbd /etc/mtab &gt;/dev/null 2&gt;&amp;1 if [[ $? -ne 0 ]]; then echo "stopped" rm -f /tmp/heartbeatwrapper exit 3 fi #nfs running? /etc/init.d/nfs-kernel-server status &gt;/dev/null 2&gt;&amp;1 if [[ $? -ne 0 ]]; then echo "stopped" rm -f /tmp/heartbeatwrapper exit 3 fi echo "running" rm -f /tmp/heartbeatwrapper exit 0 </code></pre> <p>fi </pre></code></p> <p>With all of the above done, you'll then just want to configure /etc/exports</p> <pre>/export 172.20.1.0/255.255.255.0(rw,sync,fsid=1,no_root_squash)</pre> <p>Then it's just a case of starting up heartbeat on both machines and issuing hb_takeover on one of them. You can test that it's working by making sure the one you issued the takeover on is primary - check /proc/drbd, that the device is mounted correctly, and that you can access nfs. </p> <p>--</p> <p>Best of luck man. Setting it up from the ground up was, for me, an extremely painful experience.</p>
<p>Are you looking for an "enterprise" solution or a "home" solution? It is hard to tell from your question, because 2TB is very small for an enterprise and a little on the high end for a home user (especially two servers). Could you clarify the need so we can discuss tradeoffs?</p>
10,562
<p>When I load my iPhone app it always loads a black screen first then pops up the main window. This happens even with a simple empty app with a single window loaded. </p> <p>I've noticed that when loading, most apps zoom in on the main window (or scale it to fit the screen, however you want to think about it) and then load the content of the screen, with no black screen (see the Contacts app for an example).</p> <p>How do I achieve this effect?</p>
<p>Add a Default.png to your project. This should be the image you want shown instead of the black launch screen.</p>
<p>You can also take a screenshot of your app as an aid to creating the Default.png - while holding the Home button, press and release the Lock Sleep/Wake button. The screenshot can be find in your Camery Roll library in the Photos app and can be synced back to your desktop.</p>
8,888
<p>I'm using a ASP.NET menu control. I'd like the menu to look like this, where link 1 through 10 are in one sitemap file and link 11 through 20 in another. </p> <pre><code>root --link 1 (...) --link 10 --link 11 (...) --link 20 </code></pre> <p>However, sitemap file MUST have a root which I cannot seem to suppress.</p> <p>Any thoughts?</p> <p>-Edoode</p>
<p>Is there any reason that you can't add a dummy root node and then subclass the ASP.NET menu control to ignore your dummy "root" node?</p> <p>You should be able to tell your SiteMapProvider to use different site maps for the menu.</p> <p>The other question I have is what's the purpose of having multiple sitemap files? I'm sure you have a valid reason for this, but knowing what's going on would make it easier to understand and come up with a better solution.</p> <p>That being said, I would come up with a homegrown menu system. You could use jQuery and the superfish plugin on the front end and use C# to read your site map files on the back end to build the menuing structure.</p>
<p>Is there any reason that you can't add a dummy root node and then subclass the ASP.NET menu control to ignore your dummy "root" node?</p> <p>You should be able to tell your SiteMapProvider to use different site maps for the menu.</p> <p>The other question I have is what's the purpose of having multiple sitemap files? I'm sure you have a valid reason for this, but knowing what's going on would make it easier to understand and come up with a better solution.</p> <p>That being said, I would come up with a homegrown menu system. You could use jQuery and the superfish plugin on the front end and use C# to read your site map files on the back end to build the menuing structure.</p>
12,573
<p>I have a simple application with the following code:</p> <pre><code> FileInfo[] files = (new DirectoryInfo(initialDirectory)).GetFiles(); List&lt;Thread&gt; threads = new List&lt;Thread&gt;(files.Length); foreach (FileInfo f in files) { Thread t = new Thread(delegate() { Console.WriteLine(f.FullName); }); threads.Add(t); } foreach (Thread t in threads) t.Start(); </code></pre> <p>Lets say in 'I=initialDirectory' directory I have 3 files. This application should then create 3 threads, with each thread printing off one of the file names; however, instead each thread will print off the name of the last file in the 'files' array.</p> <p>Why is this? Why is the current file 'f' variable not getting setup in the anonymous method correctly?</p>
<p>The anonymous method keeps a <strong>reference</strong> to the variable in the enclosing block -- not the actual value of the variable.</p> <p>By the time the methods are actually executed (when you start the threads) <code>f</code> has been assigned to point to the last value in the collection, so all 3 threads print that last value.</p>
<p>It's because the underlying code for iterator (foreach) has already 'iterated' through all the values in the List before the threads start... So when they start, the value 'pointed' at by the iterator is the last one in the list...</p> <p>Start the thread inside the iteration instead.... </p> <pre><code>foreach (FileInfo f in files) { string filName = f.FullName; Thread t = new Thread(delegate() { Console.WriteLine(filName); }); t.Start(); } </code></pre> <p>I don't believe a race is possible here since there's no shared memory accessible from all threads. </p>
31,131
<p>I understand that they force you to implement methods and such but what I cant understand is why you would want to use them. Can anybody give me a good example or explanation on why I would want to implement this.</p>
<p><strong>One specific example:</strong> interfaces are a good way of specifying a contract that other people's code must meet.</p> <p>If I'm writing a library of code, I may write code that is valid for objects that have a certain set of behaviours. The best solution is to specify those behaviours in an interface (no implementation, just a description) and then use references to objects implementing that interface in my library code.</p> <p>Then any random person can come along, create a class that implements that interface, instantiate an object of that class and pass it to my library code and expect it to work. <em>Note: it is of course possible to strictly implement an interface while ignoring the intention of the interface, so merely implementing an interface is no guarantee that things will work. Stupid always finds a way! :-)</em></p> <p><strong>Another specific example:</strong> two teams working on different components that must co-operate. If the two teams sit down on day 1 and agree on a set of interfaces, then they can go their separate ways and implement their components around those interfaces. Team A can build test harnesses that simulate the component from Team B for testing, and vice versa. Parallel development, and fewer bugs.</p> <p>The key point is that interfaces provide a layer of <strong>abstraction</strong> so that you can write code that is ignorant of unnecessary details. </p> <p><strong>The canonical example</strong> used in most textbooks is that of sorting routines. You can sort any class of objects so long as you have a way of comparing any two of the objects. You can make any class sortable therefore by implementing the <code>IComparable</code> interface, which forces you to implement a method for comparing two instances. All of the sort routines are written to handle references to IComparable objects, so as soon as you implement IComparable you can use any of those sort routines on collections of objects of your class.</p>
<p>As you noted, interfaces are good for when you want to force someone to make it in a certain format.</p> <p>Interfaces are good when data not being in a certain format can mean making dangerous assumptions in your code.</p> <p>For example, at the moment I'm writing an application that will transform data from one format in to another. I want to force them to place those fields in so I <em>know</em> they will exist and will have a greater chance of being properly implemented. I don't care if another version comes out and it doesn't compile for them because it's more likely that data is required anyways.</p> <p>Interfaces are rarely used because of this, since usually you can make assumptions or don't really <em>require</em> the data to do what you need to do.</p>
29,724
<p>This post is similar to <a href="https://stackoverflow.com/questions/16829/structure-of-projects-in-version-control">this previously asked question.</a> I really want to set up my SVN repository in TTB format, but when creating a project in Visual Studio 2008 (ASP.NET/VB.NET), the structure created tends to be incompatible when considering the solution file, project files, folders for projects, multiple projects within solutions, etc. Does anyone have a script or procedure to take a newly created ASP.NET project and move it to a TTB format as painlessly as possible?</p> <hr> <p>Let me be more specific. Suppose I have a project that I'm creating called StackOverflowIsAwesome. I can put that into my local folder structure (let's say that it's c:\working). When I create it, VS creates c:\working\StackOverflowIsAwesome and a whole bunch of subfolders (bin, app_data, etc.). But I want my repository structure to look like...</p> <pre> StackOverflowIsAwesome /trunk /bin /app_data /tags /branches </pre> <p>So, is there a clean way to do this consistently or do I need to resort to constantly moving/modifying files and folders to make this work?</p>
<p>We went with a very simplistic approach:</p> <p><strong>File Structure:</strong></p> <ul> <li>Solution Folder (contains solution file, build scripts, maybe more?) <ul> <li>Project Folder</li> <li>Project Folder 2</li> <li>References (contains shared assemblies for the solution).</li> </ul></li> </ul> <p>Then we just check the entire solution folder's contents into our repository. We use one repository for each solution. I'm not sure if this is the optimal way to organize the solution, but it works for us.</p> <p>Also, we branch at the highest level, not per project.</p>
<p>I do it this way:</p> <ol> <li>Create the project in VS</li> <li>Import everything in the project folder to repos/projectname/trunk</li> <li>Add the repos/branches and repos/tags folders</li> </ol> <p>That gives me a repository structure like:</p> <pre><code>projectname / trunk /bin /obj /Properties projectname.sln /tags /branches </code></pre> <p>And I can just leave all of the files in their default places in the file system.</p>
16,428
<p>I'm trying to get my head around mutable vs immutable objects. Using mutable objects gets a lot of bad press (e.g. returning an array of strings from a method) but I'm having trouble understanding what the negative impacts are of this. What are the best practices around using mutable objects? Should you avoid them whenever possible?</p>
<p>Well, there are a few aspects to this.</p> <ol> <li><p>Mutable objects without reference-identity can cause bugs at odd times. For example, consider a <code>Person</code> bean with a value-based <code>equals</code> method:</p> <pre><code>Map&lt;Person, String&gt; map = ... Person p = new Person(); map.put(p, "Hey, there!"); p.setName("Daniel"); map.get(p); // =&gt; null </code></pre> <p>The <code>Person</code> instance gets "lost" in the map when used as a key because its <code>hashCode</code> and equality were based upon mutable values. Those values changed outside the map and all of the hashing became obsolete. Theorists like to harp on this point, but in practice I haven't found it to be too much of an issue.</p></li> <li><p>Another aspect is the logical "reasonability" of your code. This is a hard term to define, encompassing everything from readability to flow. Generically, you should be able to look at a piece of code and easily understand what it does. But more important than that, you should be able to convince yourself that it does what it does <em>correctly</em>. When objects can change independently across different code "domains", it sometimes becomes difficult to keep track of what is where and why ("<a href="https://en.wikipedia.org/wiki/Action_at_a_distance_%28computer_programming%29" rel="noreferrer">spooky action at a distance</a>"). This is a more difficult concept to exemplify, but it's something that is often faced in larger, more complex architectures.</p></li> <li><p>Finally, mutable objects are <em>killer</em> in concurrent situations. Whenever you access a mutable object from separate threads, you have to deal with locking. This reduces throughput and makes your code <em>dramatically</em> more difficult to maintain. A sufficiently complicated system blows this problem so far out of proportion that it becomes nearly impossible to maintain (even for concurrency experts).</p></li> </ol> <p>Immutable objects (and more particularly, immutable collections) avoid all of these problems. Once you get your mind around how they work, your code will develop into something which is easier to read, easier to maintain and less likely to fail in odd and unpredictable ways. Immutable objects are even easier to test, due not only to their easy mockability, but also the code patterns they tend to enforce. In short, they're good practice all around!</p> <p>With that said, I'm hardly a zealot in this matter. Some problems just don't model nicely when everything is immutable. But I do think that you should try to push as much of your code in that direction as possible, assuming of course that you're using a language which makes this a tenable opinion (C/C++ makes this very difficult, as does Java). In short: the advantages depend somewhat on your problem, but I would tend to prefer immutability.</p>
<p>If you return references of an array or string, then outside world can modify the content in that object, and hence make it as mutable (modifiable) object.</p>
26,392
<p>Given an instance <code>x</code> of <code>Callable&lt;T&gt;</code>, how can I run <code>x</code> in a separate process such that I can redirect the standard input and output of the process? For example, is there a way to build a <code>Process</code> from a <code>Callable</code>? Is there a standard <code>Executor</code> that gives control over input and output?</p> <p>[UPDATE] It's not important that the <code>Callable</code> execute in a new process as opposed to a new thread. What I want is to put the <code>Callable</code> instance in a "harness", so that I can control its stdin/stdout. AFAIK, this calls for a new process.</p>
<p>More generally:</p> <blockquote> <p>Given an instance x of Callable utilizing global variables A and B, how can I run x concurrently such that x sees custom values for A and B, rather than the "original" values of A and B?</p> </blockquote> <p>And the best answer is, don't use global variables. Dependency inject things like that. Extend Callable and add methods setStdIn, setStdOut (and setStdErr if you need it).</p> <p>I know this isn't the answer you're looking for, but the solutions I have seen for this all require a new process, and the only way you are getting that Callable into a new process is to change the code of the Callable so it is serializable, or provides a class name, or some other hack, so instead of making changes that will give you a nasty, brittle solution, just do it right*</p> <p>* "right" being to use the widely accepted pattern of dependency injection to provide loose coupling. YMMV</p> <p>UPDATE: In response to comment 1. Here is your new interface:</p> <pre><code>import java.io.InputStream; import java.io.PrintStream; import java.util.concurrent.Callable; public interface MyCallable&lt;V&gt; extends Callable&lt;V&gt; { void setStdIn(InputStream in); void setStdOut(PrintStream out); } </code></pre> <p>and your tasks would look like:</p> <pre><code>import java.io.InputStream; import java.io.PrintStream; public class CallableTask implements MyCallable&lt;Object&gt; { private InputStream in = System.in; private PrintStream out = System.out; public void setStdIn(InputStream in) { this.in = in; } public void setStdOut(PrintStream out) { this.out = out; } public Object call() throws Exception { out.write(in.read()); return null; } </code></pre> <p>}</p> <p>No need for a process. Any solution (even one using processes) is almost certainly going to require code changes to the Callables in some way. This is the simplest (just replace System.out with this.out).</p>
<p>Have a look at ProcessBuilder class, it gives you the option to capture the stdout and stderr of the process that it launches.</p> <p>You can create a Main class that runs a Callable, and then launch it as another jvm with a ProcessBuilder. The Main class can accept your callable's class name as command line input parameter and load it with Class.forName() and Class.newInstance().</p> <p>An alternative, if you want it to run a specific callable instance, is to serialize the instance to a file before launching the other process (that would be a very crude form of communicating between the two processes).</p> <p>The question is, why do you want to do it? can't you just run your callable in another thread? java.util.concurrent has some useful thread pools, just for that.</p>
44,518
<p>I'm using a custom-built inhouse application that generates a standard set of reports on a weekly basis. I have no access to the source code of the application, and everyone tells me there is no documentation available for the Oracle database schema. (Aargh!)</p> <p>I've been asked to define the specs for a variant of an existing report (e.g., apply additional filters to constrain the data set, and modify the layout slightly). This sounds simple enough in principle, but is difficult without any existing documentation. </p> <p>It's my understanding that the logs can't help me because the report only queries the database; it does not actually insert, delete, or update database values, so there is nothing to log (is this correct?).</p> <p>So my question is this: is there a tool or utility (Oracle or otherwise) that I can use to see the actual SQL statement that is being executed while the report generation job is still running? I figure, if I can see what tables are actually being accessed to produce the existing report, I'll have a very good starting point for exploring the schema and determining the correct SQL to use for my own report.</p>
<p>On the data dictionary side there are a lot of tools you can use to such as <a href="http://schemaspy.sourceforge.net/" rel="noreferrer">Schema Spy</a></p> <p>To look at what queries are running look at views sys.v_$sql and sys.v_$sqltext. You will also need access to sys.all_users</p> <p>One thing to note that queries that use parameters will show up once with entries like </p> <pre><code>and TABLETYPE=’:b16’ </code></pre> <p>while others that dont will show up multiple times such as:</p> <pre><code>and TABLETYPE=’MT’ </code></pre> <p>An example of these tables in action is the following SQL to find the top 20 diskread hogs. You could change this by removing the <strong>WHERE rownum &lt;= 20</strong> and maybe add <strong>ORDER BY module</strong>. You often find the module will give you a bog clue as to what software is running the query (eg: "TOAD 9.0.1.8", "JDBC Thin Client", "runcbl@somebox (TNS V1-V3)" etc)</p> <pre><code>SELECT module, sql_text, username, disk_reads_per_exec, buffer_gets, disk_reads, parse_calls, sorts, executions, rows_processed, hit_ratio, first_load_time, sharable_mem, persistent_mem, runtime_mem, cpu_time, elapsed_time, address, hash_value FROM (SELECT module, sql_text , u.username , round((s.disk_reads/decode(s.executions,0,1, s.executions)),2) disk_reads_per_exec, s.disk_reads , s.buffer_gets , s.parse_calls , s.sorts , s.executions , s.rows_processed , 100 - round(100 * s.disk_reads/greatest(s.buffer_gets,1),2) hit_ratio, s.first_load_time , sharable_mem , persistent_mem , runtime_mem, cpu_time, elapsed_time, address, hash_value FROM sys.v_$sql s, sys.all_users u WHERE s.parsing_user_id=u.user_id and UPPER(u.username) not in ('SYS','SYSTEM') ORDER BY 4 desc) WHERE rownum &lt;= 20; </code></pre> <p>Note that if the query is long .. you will have to query v_$sqltext. This stores the whole query. You will have to look up the ADDRESS and HASH_VALUE and pick up all the pieces. Eg:</p> <pre><code>SELECT * FROM sys.v_$sqltext WHERE address = 'C0000000372B3C28' and hash_value = '1272580459' ORDER BY address, hash_value, command_type, piece ; </code></pre>
<p>I had (have) a similar problem in a Java application. I wrote a JDBC driver wrapper around the Oracle driver so all output is sent to a log file. </p>
7,974
<p>Although the <a href="http://www.adobe.com/devnet/pdf/pdf_reference.html" rel="noreferrer">PDF specification</a> is available from Adobe, it's not exactly the simplest document to read through. PDF allows documents to be encrypted so that either a user password and/or an owner password is required to do various things with the document (display, print, etc). A common use is to lock a PDF so that end users can read it without entering any password, but a password is required to do anything else.</p> <p>I'm trying to parse PDFs that are locked in this way (to get the same privileges as you would get opening them in any reader). Using an empty string as the user password doesn't work, but it seems (section 3.5.2 of the spec) that there has to be a user password to create the hash for the admin password.</p> <p>What I would like is either an explanation of how to do this, or any code that I can read (ideally Python, C, or C++, but anything readable will do) that does this so that I can understand what I'm meant to be doing. Standalone code, rather than reading through (e.g.) the gsview source, would be best.</p>
<p>A plugin for GSview for viewing encrypted PDFs is <a href="http://www.cs.cmu.edu/~dst/Adobe/Gallery/Keating/" rel="nofollow noreferrer">here</a>.</p> <p>If this works for you, you may be able to look at the source.</p>
<p>xpdf is probably a good reference implementation for this sort of problem. I have successfully used them to open encrypted pdfs before.</p>
7,202
<p>I am working on a solo project, writing all code myself so no collaboration is required,</p> <p>However, I do need the following features:</p> <ol> <li>Check in a current version, with comments</li> <li>Assign a label to a version</li> <li>Retrieve a version using label/tag</li> <li>NOT HOSTED (meaning I hold the repository on my local machine)</li> <li>free/open source</li> <li>With a nice GUI, not command line?</li> </ol> <p>I think SVN is a good one, but it seems a bit overkill for me. Anyone ever came across anything like that?</p>
<p>I don't think svn is overkill for what you are doing. It's pretty trivial to set up a local repository.</p>
<p>This is a shameless plug, but I couldn't resist.</p> <p>I'm working on a tool that might be useful for you.</p> <p>I haven't figured out the name yet, so I'm using a code name of "Code Agent".</p> <p>It's designed mainly as a compliment to a source control setup, but if you are just a single developer on one machine, it might be a useful replacement for you.</p> <p>It's a service that runs on your development machine. You point it at the folders that contain your source code, and then it will automatically create a backup every time you change a file. </p> <p>It's designed to fill in a big gap left by source control systems:</p> <p>They only protect your files when you explictly check them in. </p> <p>Source control is mainly about managing the output of a team (several developers) over several releases of a project. As a result, it's generally not a good idea to check-in broken code into source control. Most of the time, developers only checkin code when it's "mostly working". </p> <p>In the best of enviornments, with the best team of developers, this usually means you are probably only averaging (over the whole project) one checkin per day.</p> <p>It can probably go as low as once every several days or several weeks in the worst cases.</p> <p>Even in the best case, though, a lot of stuff can happen in day. I know that if I'm on a roll, for example, I can introduce quite a large number of bugs in the course of day. Over a week or two, I can really messs stuff up.</p> <p>Having history of code changes at a more granular level then once a day or once a week, can therefore be really helpful.</p> <p>It's possible to do this using "private" source control branches, but that requires you to:</p> <ol> <li>Setup the private branch</li> <li>Spend time managing the branch by taking regular integrations to / from the main branch</li> <li>Remember to checkin your changes at regular intervals into the private branch.</li> </ol> <p>The last one is probably the killer. It’s an easy thing to forget.</p> <p>And of course as soon as you setup a private branch, someone else is going to want to access the code in it for one reason or another, which is then going to end up preventing you from checking in as regularly as you want, which ends defeating the whole purpose of the private branch in the first place.</p> <p>"Code Agent" fixes all of this.</p> <p>You can setup it up once, and forget it about it.</p> <p>You then have local source code history, at whatever granularity you need, whenever you need it. All automatically, and without having to checkin in “bad code” into your team’s source control repository. </p> <p>For developers on teams, my tool is not a replacement for source control, but instead is designed as a complement to it. On a team you still need to explicitly manage checkins to a shared source code tree.</p> <p>In your case, because you are not on a team, however, it might be perfect for you to use as a replacement for source control. You can add labels, or “snapshots” that correspond to specific points in time (like “fixed bug 1234”, “finished feature x”, etc).</p> <p>It's not, however, free or open source.. It's a tool I'm going to be charging money for.</p> <p>However, it should definitely be affordable for an individual developer to purchase (I haven't finalized the price yet).</p> <p>I am going to be looking for Beta-testers sometime in early to mid January. If you are interested, let me know, and I would be happy to set you up with a private beta.</p>
45,319
<p>Can somebody explain what is <a href="https://stackoverflow.com/tags/rest/info">REST</a> and what is <a href="https://stackoverflow.com/tags/soap/info">SOAP</a> in plain english? And how Web Services work? </p>
<h2>Simple explanation about SOAP and REST</h2> <p><strong>SOAP - "Simple Object Access Protocol"</strong></p> <p>SOAP is a method of transferring messages, or small amounts of information, over the Internet. SOAP messages are formatted in XML and are typically sent using HTTP (hypertext transfer protocol).</p> <hr> <p><strong>Rest - Representational state transfer</strong></p> <p>Rest is a simple way of sending and receiving data between client and server and it doesn't have very many standards defined. You can send and receive data as JSON, XML or even plain text. It's light weighted compared to SOAP.</p> <hr> <p><img src="https://i.stack.imgur.com/GwRYd.jpg" alt="enter image description here"></p>
<p>SOAP­based Web Services In short, the SOAP­based Services model views the world as an ecosystem of co­equal peers that cannot control each other, but have to work together by honoring published contracts. It's a valid model of the messy real world, and the metadata ­based contracts form the SOAP Service Interface.</p> <p>we can still associate SOAP with XML­based Remote Procedure Calls, but SOAP­based Web Services technology has emerged into a flexible and powerful messaging model.</p> <p>SOAP assumes all systems are independent and no system has any knowledge of the internals of another and internal functionality. The most such systems can do is send messages to one another and hope they will be acted upon. Systems publish contracts that they undertake to honor, and other systems rely upon these contracts to exchange messages with them.</p> <p>Contracts between systems are collectively called metadata, and comprise service descriptions, the message exchange patterns supported and the policies governing qualities of service (a service may need to be encrypted, reliably delivered, etc.) A service description, in turn, is a detailed specification of the data (message documents) that will be sent and received by the system. The documents are described using an XML description language like XML Schema Definition. As long as all systems honor their published contracts, they can inter operate, and changes to the internals of systems never affect any other. Every system is responsible for translating its own internal implementations to and from its contracts</p> <p>REST - REpresentational State Transfer. The physical protocol is HTTP. Basically, REST is that all distinct resources on the web that are uniquely identifiable by a URL. All operations that can be performed on these resources can be described by a limited set of verbs (the “CRUD” verbs) which in turn map to HTTP verbs. </p> <p>REST's is much less “heavyweight” than SOAP. </p> <p><a href="http://acs.lbl.gov/projects/gtg/projects/pyGridWare/doc/tutorial/html/x284.html" rel="nofollow">Working of web service</a></p>
25,767
<p>I'm writing a server that I expect to be run by many different people, not all of whom I will have direct contact with. The servers will communicate with each other in a cluster. Part of the server's functionality involves selecting a small subset of rows from a potentially very large table. The exact choice of what rows are selected will need some tuning, and it's important that it's possible for the person running the cluster (eg, myself) to update the selection criteria without getting each and every server administrator to deploy a new version of the server.</p> <p>Simply writing the function in Python isn't really an option, since nobody is going to want to install a server that downloads and executes arbitrary Python code at runtime.</p> <p>What I need are suggestions on the simplest way to implement a Domain Specific Language to achieve this goal. The language needs to be capable of simple expression evaluation, as well as querying table indexes and iterating through the returned rows. Ease of writing and reading the language is secondary to ease of implementing it. I'd also prefer not to have to write an entire query optimiser, so something that explicitly specifies what indexes to query would be ideal.</p> <p>The interface that this will have to compile against will be similar in capabilities to what the App Engine datastore exports: You can query for sequential ranges on any index on the table (eg, less-than, greater-than, range and equality queries), then filter the returned row by any boolean expression. You can also concatenate multiple independent result sets together.</p> <p>I realise this question sounds a lot like I'm asking for SQL. However, I don't want to require that the datastore backing this data be a relational database, and I don't want the overhead of trying to reimplement SQL myself. I'm also dealing with only a single table with a known schema. Finally, no joins will be required. Something much simpler would be far preferable.</p> <p>Edit: Expanded description to clear up some misconceptions.</p>
<p>Building a DSL to be interpreted by Python.</p> <p>Step 1. Build the run-time classes and objects. These classes will have all the cursor loops and SQL statements and all of that algorithmic processing tucked away in their methods. You'll make heavy use of the <a href="http://exciton.cs.rice.edu/javaresources/DesignPatterns/command.htm" rel="nofollow noreferrer">Command</a> and <a href="http://exciton.cs.rice.edu/javaresources/DesignPatterns/StrategyPattern.htm" rel="nofollow noreferrer">Strategy</a> design patterns to build these classes. Most things are a command, options and choices are plug-in strategies. Look at the design for Apache Ant's <a href="http://ant.apache.org/manual/develop.html" rel="nofollow noreferrer">Task</a> API -- it's a good example.</p> <p>Step 2. Validate that this system of objects actually works. Be sure that the design is simple and complete. You're tests will construct the Command and Strategy objects, and then execute the top-level Command object. The Command objects will do the work. </p> <p>At this point you're largely done. Your run-time is just a configuration of objects created from the above domain. [This isn't as easy as it sounds. It requires some care to define a set of classes that can be instantiated and then "talk among themselves" to do the work of your application.]</p> <p>Note that what you'll have will require nothing more than declarations. What's wrong with procedural? One you start to write a DSL with procedural elements, you find that you need more and more features until you've written Python with different syntax. Not good.</p> <p>Further, procedural language interpreters are simply hard to write. State of execution, and scope of references are simply hard to manage.</p> <p>You can use native Python -- and stop worrying about "getting out of the sandbox". Indeed, that's how you'll unit test everything, using a short Python script to create your objects. Python will be the DSL. </p> <p>["But wait", you say, "If I simply use Python as the DSL people can execute arbitrary things." Depends on what's on the PYTHONPATH, and sys.path. Look at the <a href="http://docs.python.org/lib/module-site.html" rel="nofollow noreferrer">site</a> module for ways to control what's available.]</p> <p>A declarative DSL is simplest. It's entirely an exercise in representation. A block of Python that merely sets the values of some variables is nice. That's what Django uses.</p> <p>You can use the <a href="http://docs.python.org/lib/module-ConfigParser.html" rel="nofollow noreferrer">ConfigParser</a> as a language for representing your run-time configuration of objects.</p> <p>You can use <a href="http://pypi.python.org/pypi/python-json/" rel="nofollow noreferrer">JSON</a> or <a href="http://pyyaml.org/" rel="nofollow noreferrer">YAML</a> as a language for representing your run-time configuration of objects. Ready-made parsers are totally available.</p> <p>You can use XML, too. It's harder to design and parse, but it works fine. People love it. That's how Ant and Maven (and lots of other tools) use declarative syntax to describe procedures. I don't recommend it, because it's a wordy pain in the neck. I recommend simply using Python.</p> <p>Or, you can go off the deep-end and invent your own syntax and write your own parser.</p>
<p>Why not create a language that when it "compiles" it generates SQL or whatever query language your datastore requires ?</p> <p>You would be basically creating an abstraction over your persistence layer. </p>
16,941
<p>We have an application that downloads some files in the background. Our application pops up when an Internet connection is made, and after prompting the user to accept the downloads, we'd like to switch back to the home screen while we do our stuff.</p> <p>We can't work out how to do to this. We can emulate pressing "back" a few times, which sometimes works, but where you end up depends on what the user was doing when the Internet connection happened.</p> <p>So, can someone provide pointers to how to do this?</p> <p>Thanks.</p> <p>Paul.</p>
<p>Since data will be bound on the server side, you don't have a client-side event for that specific event, however, one the page has rendered, the data will be there, so you may want to run your client script in the document.load event, or using something like jQuery's document.ready event. That will trigger your script to run once the page (including your bound drop down) is finished loading.</p>
<p>i use the following code in my master pages for my websites. This stops the user from attempting to use a control before its completely bound. I have found that if a control hasn't been completely bound (slow connections) then the page blows up.</p> <p>Essentially the script hijacks the post back if that page isn't done. Allowing the user to not do anything until the page has finished processing. I wrote this a year ago and its come in very handy.</p> <ol> <li><p>first set the onload body tag to setdopostback()</p></li> <li><p>add this in a scrip block in the body.</p> <pre><code> var boolDoPostBack = false; if (__doPostBack) { // save a reference to the original __doPostBack var __oldDoPostBack = __doPostBack; //replace __doPostBack with another function __doPostBack = AlwaysFireBeforeFormSubmit; } function setdopostback() { boolDoPostBack = true; } function AlwaysFireBeforeFormSubmit (eventTarget, eventArgument) { var x= document.readyState if (x != "complete") { if (x == "loading" || x == "interactive" || x == "unitialized" || x == "loaded") { //do nothing with IE postback } else if (!boolDoPostBack) { //do nothing with FireFox postback } else { //alert('Allow Postback 1'); return __oldDoPostBack (eventTarget, eventArgument); } } else { //alert('Allow Postback 2'); return __oldDoPostBack (eventTarget, eventArgument); } } </code></pre></li> </ol>
35,121
<p>I'm using the XML data source feature in Reporting Services 2005 but having some issues with missing data. When there is no value for the first column in a row, it appears that the entire column is ignored by SSRS!</p> <p>The web method request is very simple:</p> <pre><code>&lt;Query&gt; &lt;Method Name="GetIssues" Namespace="http://www.mycompany.com/App/"&gt; &lt;/Method&gt; &lt;SoapAction&gt;http://www.mycompany.com/App/GetIssues&lt;/SoapAction&gt; &lt;ElementPath IgnoreNamespaces="true"&gt;*&lt;/ElementPath&gt; &lt;/Query&gt; </code></pre> <p>Equally, the response is very simple:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;soap:Body&gt; &lt;GetIssuesResponse xmlns="http://www.mycompany.com/App/"&gt; &lt;GetIssuesResult&gt; &lt;Issue&gt; &lt;Title&gt;ABC&lt;/Title&gt; &lt;RaisedBy /&gt; &lt;Action&gt;Do something&lt;/Action&gt; &lt;/Issue&gt; &lt;Issue&gt; &lt;Title&gt;ABC&lt;/Title&gt; &lt;RaisedBy&gt;Jeff Smith&lt;/RaisedBy&gt; &lt;Action&gt;Do something&lt;/Action&gt; &lt;/Issue&gt; &lt;/GetIssuesResult&gt; &lt;/GetIssuesResponse&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre> <p>In this example the RaisedBy column will be completely empty. If the 'Issues' are reversed so RaisedBy first has a value, there is no problem. Any ideas?</p>
<p>In the Query itself, try to define your columns explicitly, instead of letting SSRS determine them for you.</p> <p>In other words, where you have:</p> <pre><code>&lt;ElementPath IgnoreNamespaces="true"&gt;*&lt;/ElementPath&gt; </code></pre> <p>Replace the * with something like:</p> <pre><code>&lt;ElementPath IgnoreNamespaces="true"&gt;GetIssues/GetIssuesItemsResult/listitems/data/row{@Title,@RaisedBy,@Action}&lt;/ElementPath&gt; </code></pre> <p>Of course, that exact XPath may not be correct for your example.</p>
<p>Is it possible to eliminate the NULLs in the XML? Replace them with an empty string? Then you won't have to wrestle with SSRS.</p> <p>If the XML is generated from a database call, that's easy enough to do (ISNULL in SQL Server).</p>
35,179
<p>In the E3D Kraken cooler block, there is a big, 10&nbsp;mm grub screw, along the side of the cooler block.</p> <p>I watched the entire Kraken assembly video:</p> <p><div class="youtube-embed"><div> <iframe width="640px" height="395px" src="https://www.youtube.com/embed/wEw4UDUUbIE?start=0"></iframe> </div></div></p> <p>There was no mention of this very thick grub screw. The <a href="https://wiki.e3d-online.com/Kraken_Assembly" rel="nofollow noreferrer">E3D Kraken assembly wiki page</a> may refer to this part as the "stainless plug".</p> <p>Does the depth of the screw inside the Kraken heatbreak affect the effectiveness of the water cooling?</p> <p>Why was it included in the design at all?</p> <p>I'm asking because water frequently leaks out of this pore for me, ever since I had to repair some damaged tubing. Additionally I often have to use an extra fan when printing at high temperatures. I'm wondering, before I epoxy this grub screw into place, whether the amount it is tightened into the Kraken has some advantages or disadvantages.</p> <p>The video shows the part already assembled on the Kraken. This is what the part looks like - it is much larger than the screws used to secure heat throats. <img src="https://static.e3d-online.com/media/catalog/product/cache/b3b166914d87ce343d4dc5ec5117b502/p/l/plugs_10.jpg" alt="enter image description here"></p>
<p>My problem was 2 things. The <strong>heatbreak</strong>, which was switched out for the MK2 version(Explantation below). And the <strong>Teflon Tube</strong> that runs down the heatsink.</p> <h2>Heatbreak</h2> <p>Change the heat-break to a generic E3D one. You can order the heatbreak for the <strong>MK2</strong> from prusa, or any generic heat break for the E3D hot-end assembly.</p> <p>On the Prusa i3 MK3(s), this component has been given a 45° taper in the middle, between 2.2 and 2&nbsp;mm. This is done to ease filament retraction for the MMU, and will be nothing but problematic if you are not using the multi-material upgrade. Especially with higher nozzle pressures(eq. with lower layer lines), the filament may be squeezed into this taper, clogging the hot-end.</p> <p>You may not experience full clogs, but partial ones that will show themselves as streaks in certain layers on the print.</p> <h2>Heatsink Teflon Tube</h2> <p>There is a teflon tube that runs down the heatsink. It's crucial that this is mounted correctly and it is not entirely intuative how.</p> <p>First, press the teflon tube into the heatsink all the way to the bottom. Then, try to pull it out slightly. You'll notice that the small plastic ring at the top of the heatsink will pull out slightly along with it. Now, hold this black plastic part at it's current position with your fingernail, and push the teflon tube in the extra amount. When done, there should be no play in the tube.</p>
<p>The problem with low layer heights is that the filament flow is low, this means that the filament is at prolonged times at temperature, filament cooking can cause clogging. Try increasing the layer height to 0.2&nbsp;mm to observe if the same clogging problems still occur, furthermore, try lowering the extrusion temperature.</p> <p>Also, heat creep is a known issue (insufficient cooling of the cold end) to cause clogging. Note that this is unlikely on the Prusa MK3S, but you could check whether the fan rotates freely and that there are no additional obstructions in the flow path. </p> <p>It could be that a combination of too much hotend temperature and a low filament flow is causing this issue.</p>
1,512
<p>I'm using watermark extenders on textboxes and an exception is being thrown from the AJAX Control Toolkit .dll. It's strange because this just started happening. </p> <p>I tried debugging from the Ajax solution and Ajax examples (but with my code), but no dice. </p> <p>Is there a way to step into the Ajax .dll from my solution to see where this is happening? </p>
<p>Couldn't you just get the source for the Ajax Control Toolkit and include it as a project in your solution and then reference it? You'd then be able to step into the code and if you really needed to, you can just put the precompiled one out when you deploy out.</p>
<p>You don't need to include the AjaxControlToolkit project. Just open the file you need (in the VS instance where your code that currently breaks is), and set a breakpoint where appropriate.</p>
18,815
<p>My question is... Is there a SIMPLE/easy way to load TPU without tearing my printer apart to insert a hose that probably wont work anyways. It keeps curling up by the cog. I have read a few topics in other places but I didn't like the answers. Hoping you all might have a simple fix. </p>
<p>Loading TPU/TPE can be particularly challenging because many printer loading scripts run too fast for the soft flexible filament to effectively purge whatever normal filament you were using before. A couple tips:</p> <ul> <li>Load with a slightly higher temp than either the TPU or previous filament require, so as to minimize the melt viscosity and reduce the force required.</li> <li>Make a custom gcode file that contains a slower loading routine: wait for heat, then advance the extruder at a very slow rate for a long distance. Then you just "print" this gcode file whenever you need to load TPU.</li> </ul> <p>However, simply being able to load is not necessarily enough. <strong>Not all extruders can reliably print flexible filaments, period.</strong> The larger the gap between the pinch wheel and inlet to the hot end, the more likely the filament is to buckle and come out the side. You need to make sure this gap is as short as possible. If there is more than a couple mm of gap, you'll need to make gap-filler or print yourself a new extruder designed for flexibles.</p> <p>Printing slow and without major velocity changes can help, too. Use relatively low layer heights and low, constant feedrates so the extruder doesn't have to run fast or change pressure often. </p> <p>Harder flexible filaments will be easier to print if your setup is borderline. Ninjaflex is one of the hardest to print because it is relatively soft. Semi-flex type filaments are much easier to print if your hardware isn't set up optimally.</p>
<p>I've noticed that the first layer seems more prone to wrapping flexible filament around the drive, particularly if the nozzle is a bit on the low side. The extra extrusion force required to push the filament against the resistance of the bed means that the filament can't sustain enough pressure without folding. </p> <p>As a quick workaround for this, I lowered the extrusion multiplier to 60% on the fly for the first layer (as well as keeping the speed right down).</p>
347
<p>Do you have a simple debounce routine handy to deal with a single switch input?</p> <p>This is a simple bare metal system without any OS.</p> <p>I would like to avoid a looping construct with a specific count, as the processor speed might fluctuate.</p>
<p>I think you could learn a lot about this here: <a href="http://www.ganssle.com/debouncing.pdf" rel="noreferrer">http://www.ganssle.com/debouncing.pdf</a></p> <p>Your best bet is always to do this in hardware if possible, but there are some thoughts on software in there as well.</p> <p>Simple example code from TFA:</p> <pre class="lang-cpp prettyprint-override"><code>#define CHECK_MSEC 5 // Read hardware every 5 msec #define PRESS_MSEC 10 // Stable time before registering pressed #define RELEASE_MSEC 100 // Stable time before registering released // This function reads the key state from the hardware. extern bool_t RawKeyPressed(); // This holds the debounced state of the key. bool_t DebouncedKeyPress = false; // Service routine called every CHECK_MSEC to // debounce both edges void DebounceSwitch1(bool_t *Key_changed, bool_t *Key_pressed) { static uint8_t Count = RELEASE_MSEC / CHECK_MSEC; bool_t RawState; *Key_changed = false; *Key_pressed = DebouncedKeyPress; RawState = RawKeyPressed(); if (RawState == DebouncedKeyPress) { // Set the timer which allows a change from current state. if (DebouncedKeyPress) Count = RELEASE_MSEC / CHECK_MSEC; else Count = PRESS_MSEC / CHECK_MSEC; } else { // Key has changed - wait for new state to become stable. if (--Count == 0) { // Timer expired - accept the change. DebouncedKeyPress = RawState; *Key_changed=true; *Key_pressed=DebouncedKeyPress; // And reset the timer. if (DebouncedKeyPress) Count = RELEASE_MSEC / CHECK_MSEC; else Count = PRESS_MSEC / CHECK_MSEC; } } </code></pre> <p>}</p>
<p>What I usually do is have three or so variables the width of the input register. Every poll, usually from an interrupt, shift the values up one to make way for the new sample. Then I have a debounced variable formed by setting the logical-and of the samples, and clearing the inverse logical-or. i.e. (untested, from memory)</p> <pre><code>input3 = input2; input2 = input1; input1 = (*PORTA); debounced |= input1 &amp; input2 &amp; input3; debounced &amp;= (input1 | input2 | input3); </code></pre> <p>Here's an example:</p> <p>debounced has xxxx (where 'x' is "whatever")</p> <pre><code>input1 = 0110, input2 = 1100, input3 = 0100 </code></pre> <p>With the information above,</p> <p>We need to switch only bit 2 to 1, and bit 0 to 0. The rest are still "bouncing".</p> <pre><code>debounced |= (0100); //set only bit 2 debounced &amp;= (1110); //clear only bit 0 </code></pre> <p>The result is that now debounced = x1x0</p>
18,747
<p>Stacker Nobody asked about the <a href="https://stackoverflow.com/questions/214452/what-surprised-you-the-most-about-the-software-industry">most shocking thing new programmers find as they enter the field</a>.</p> <p>Very high on the list, is the impact of inheriting a codebase with which one must rapidly become acquainted. It can be quite a shock to suddenly find yourself charged with maintaining N lines of code that has been clobbered together for who knows how long, and to have a short time in which to start contributing to it.</p> <p>How do you efficiently absorb all this new data? What eases this transition? Is the only real solution to have already contributed to enough open-source projects that the shock wears off?</p> <p>This also applies to veteran programmers. What techniques do you use to ease the transition into a new codebase?</p> <p>I added the Community-Building tag to this because I'd also like to hear some war-stories about these transitions. Feel free to share how you handled a particularly stressful learning curve.</p>
<p>Write unit tests. You'll find the warts quicker, and you'll be more confident when the time comes to change the code.</p>
<p>One thing vi and emacs users can do is use tags. Tags are contained in a file ( usually called TAGS ). You generate one or more tags files by a command ( etags for emacs vtags for vi ). Then we you edit source code and you see a confusing function or variable you load the tags file and it will take you to where the function is declared ( not perfect by good enough ). I've actually written some macros that let you navigate source using Alt-cursor, sort of like popd and pushd in many flavors of UNIX.</p> <p>BubbaT</p>
26,377
<p>That's it. If you want to document a function or a class, you put a string just after the definition. For instance:</p> <pre><code>def foo(): """This function does nothing.""" pass </code></pre> <p>But what about a module? How can I document what a <em>file.py</em> does?</p>
<p>For the packages, you can document it in <code>__init__.py</code>. For the modules, you can add a docstring simply in the module file.</p> <p>All the information is here: <a href="http://www.python.org/dev/peps/pep-0257/" rel="noreferrer">http://www.python.org/dev/peps/pep-0257/</a></p>
<p>It's easy, you just add a docstring at the top of the module.</p>
6,572
<p>I have just noticed that a multidimensional array in C# does not implement <code>IEnumerable&lt;T&gt;</code>, while it does implement <code>IEnumerable</code>. For single-dimensional arrays, both <code>IEnumerable&lt;T&gt;</code> and <code>IEnumerable</code> are implemented.</p> <p>Why this difference? If a multi-dimensional array is <code>IEnumerable</code>, surely it should also implement the generic version? I noticed this because I tried to use an extension method on a multidimensional array, which fails unless you use <code>Cast&lt;T&gt;</code> or similar; so I can definitely see the an argument for making multidimensional arrays implement <code>IEnumerable&lt;T&gt;</code>.</p> <p>To clarify my question in code, I would expect the following code to print <code>true</code> four times, while it actually prints <code>true</code>, <code>false</code>, <code>true</code>, <code>true</code>:</p> <pre><code>int[] singleDimensionArray = new int[10]; int[,] multiDimensional = new int[10, 10]; Debug.WriteLine(singleDimensionArray is IEnumerable&lt;int&gt;); Debug.WriteLine(multiDimensional is IEnumerable&lt;int&gt;); Debug.WriteLine(singleDimensionArray is IEnumerable); Debug.WriteLine(multiDimensional is IEnumerable); </code></pre>
<p>The CLR has two different kinds of arrays: <em>vectors</em> which are guaranteed to be one-dimensional with a lower bound of 0, and more general arrays which can have non-zero bounds and a rank other than 0.</p> <p>From section 8.9.1 of the CLI spec: </p> <blockquote> <p>Additionally, a created vector with element type T, implements the interface <code>System.Collections.Generic.IList&lt;U&gt;</code> (§8.7), where U := T.</p> </blockquote> <p>I have to say it seems pretty weird to me. Given that it already implements <code>IEnumerable</code> I don't see why it shouldn't implement <code>IEnumerable&lt;T&gt;</code>. It wouldn't make as much sense to implement <code>IList&lt;T&gt;</code>, but the simple generic interface would be fine.</p> <p>If you want this, you could either call <code>Cast&lt;T&gt;</code> (if you're using .NET 3.5) or write your own method to iterate through the array. To avoid casting you'd have to write your own method which found the lower/upper bounds of each dimension, and fetched things that way. Not terribly pleasant.</p>
<p>Think inversely. The 2d array already exists. Just enumerate it. Create a 2d array with score and place of an initial array or marks, including duplicate values.</p> <pre><code>int[] secondmarks = {20, 15, 31, 34, 35, 50, 40, 90, 99, 100, 20}; IEnumerable&lt;int&gt; finallist = secondmarks.OrderByDescending(c =&gt; c); int[,] orderedMarks = new int[2, finallist.Count()]; Enumerable.Range(0, finallist.Count()).ToList().ForEach(k =&gt; {orderedMarks[0, k] = (int) finallist.Skip(k).Take(1).Average(); orderedMarks[1, k] = k + 1;}); Enumerable.Range(0, finallist.Count()).Select(m =&gt; new {Score = orderedMarks[0, m], Place = orderedMarks[1, m]}).Dump(); </code></pre> <p>Results:</p> <pre><code>Score Place 100 1 99 2 90 3 50 4 40 5 35 6 34 7 31 8 20 9 20 10 15 11 </code></pre>
34,666
<p>On PHP, they have a way to restrict file size AFTER uploading, but not BEFORE uploading. I use the <a href="http://malsup.com/jquery/form/" rel="noreferrer">Malsup jQuery Form Plugin</a> for my form posting, and it supports image file posting.</p> <p>I was wondering if perhaps there's a restriction where I can set how many bytes can pass through that AJAX stream up to the server? That could permit me to check that file size and return an error if the file is too big. </p> <p>By doing this on the client side, it blocks those newbies who take a 10MB photo shot from their Pentax and try to upload that.</p>
<p>This is a copy from my answers in a very similar question: <a href="https://stackoverflow.com/questions/1601455/check-file-input-size-with-jquery/3937404#3937404">How to check file input size with jQuery?</a></p> <hr> <p>You actually don't have access to the filesystem (for example reading and writing local files). However, due to the HTML5 File API specification, there are some file properties that you do have access to, and the file size is one of them.</p> <p>For this HTML:</p> <pre><code>&lt;input type="file" id="myFile" /&gt; </code></pre> <p>try the following: </p> <pre><code>//binds to onchange event of your input field $('#myFile').bind('change', function() { //this.files[0].size gets the size of your file. alert(this.files[0].size); }); </code></pre> <p>As it is a part of the HTML5 specification, it will only work for modern browsers (v10 required for IE) and I added <a href="http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/" rel="noreferrer">here</a> more details and links about other file information you should know: <a href="http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/" rel="noreferrer">http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/</a></p> <hr> <p><strong>Old browsers support</strong></p> <p>Be aware that old browsers will return a <code>null</code> value for the previous <code>this.files</code> call, so accessing <code>this.files[0]</code> will raise an exception and you should <a href="https://stackoverflow.com/a/20550591/429521">check for File API support</a> before using it</p>
<p>It's not possible to verify the image size, width or height on the client side. You need to have this file uploaded on the server and use PHP to verify all this info. PHP has special functions like: <code>getimagesize()</code></p> <pre><code>list($width, $height, $type, $attr) = getimagesize("img/flag.jpg"); echo "&lt;img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" /&gt;"; </code></pre>
39,605
<p>I am completely new to 3D printing. I need to build a calibration plate, which I was told can be built using vero back plastic and a 3d printer. But I am afraid I need to know more if I give this to someone for fabrication. In particular, I am wondering how to get the white dots on the surfaces. My question is probably ill-posed, but I am trying to get as much info as I can before I consult any 3d printing vendors. Thanks</p> <p><a href="https://i.stack.imgur.com/32GtS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/32GtS.jpg" alt="Calibration plate"></a></p>
<p>The photo is too small to be clear about the entire objective and there are no dimensions provided. A quick google search returns nothing 3d printer related to "black vera plastics" other than a reference to vera bradley, vera wang and an obscure reference to a woven black carpet with white spots of increasing size. </p> <p>Even within those limitations, one can certainly print a strip of black with white dots. One method involves a dual extruder printer, enabling two colors to be printed, one layer at a time. The black layer would be extruded with suitable holes and the white layer would be place within those holes.</p> <p>Another method involves printing the black layer with holes, swapping out the filament with white and creating white plugs of appropriate sizes for the necessary fit.</p> <p>You've used the term calibration plate, which implies some level of precision. Is the precision related to spacing, dot size, dot color, or a combination of the above?</p> <p>Such requirements may make the cost slightly higher, but not excessively. I can print up to to 290 mm long strip, possibly longer by going diagonal on my 290 mm print bed, with or without the two colors done simultaneously.</p> <p>If you require crisp edges to the white/black transition, the holes-and-plugs method will give best results and require a bit of post processing. It may be necessary to ream the holes to correct diameter and sand the plugs to fit. Dual extrusion rarely provides sharp delineation from one color to the next.</p>
<p>What are the characteristics of the white dots? (That is, are the dots small raised bumps, do they denote where a hole will be drilled, are they integral to a piece-to-piece connection, etc...) </p> <p>If these are small bumps that need to be added to the top of the black surfaces, your most time-effective solution is probably print the black component first (with placement references for where the white dots are to go), then switch materials and print the dots, and attach them to the black component.</p> <p>Otherwise, you'll need a machine capable of printing in two materials simultaneously(ish). See some of the newer Stratasys machines if you have a good budget ha!</p>
435
<p>We have a SQL Server 2005 database, and currently all our users are connecting to the database via the TCP/IP protocol. </p> <p>The SQL Server Configuration Manager allows you to "enable" both Named Pipes, and TCP/IP connections at the same time. Is this a good idea? My question is not whether we should use named pipes instead of TCP/IP, but are there problems associated with enabling both?</p> <p>One of our client's IT guys, says that enabling database communication with both protocols will limit the bandwidth that either protocol can use - to like 50% of the total. I would think that the bandwidth that TCP/IP could use would be directly tied (inversely) to the amount of traffic that Named Pipes (or any of the other types of traffic) were occupying on the network at that moment. However, this IT person is indicating that the fact that we have enabled two protocols on the server, artificially limits the bandwidth that TCP/IP can use. Is this correct?</p> <p>I did Google searches but could not come up with an answer to this question. Any help would be appreciated.</p>
<p>This is not correct. Your thought on network traffic is correct - capacity is not 'reserved'.</p> <p>You should not enable named pipes if it is not needed.</p>
<p>no there is no limit on the bandwidth. the problem with named pipes is that they can be quite "chatty" in a slow network and can take a lot of bandwidth. there is a priority list of protocols to try first. but there is no internal threshold for this that i know of.</p>
44,948
<p>I am a big fan of letting the compiler do as much work for you as possible. When writing a simple class the compiler can give you the following for 'free':</p> <ul> <li>A default (empty) constructor</li> <li>A copy constructor</li> <li>A destructor</li> <li>An assignment operator (<code>operator=</code>)</li> </ul> <p>But it cannot seem to give you any comparison operators - such as <code>operator==</code> or <code>operator!=</code>. For example:</p> <pre><code>class foo { public: std::string str_; int n_; }; foo f1; // Works foo f2(f1); // Works foo f3; f3 = f2; // Works if (f3 == f2) // Fails { } if (f3 != f2) // Fails { } </code></pre> <p>Is there a good reason for this? Why would performing a member-by-member comparison be a problem? Obviously if the class allocates memory then you'd want to be careful, but for a simple class surely the compiler could do this for you?</p>
<p>The argument that if the compiler can provide a default copy constructor, it should be able to provide a similar default <code>operator==()</code> makes a certain amount of sense. I think that the reason for the decision not to provide a compiler-generated default for this operator can be guessed by what Stroustrup said about the default copy constructor in "The Design and Evolution of C++" (Section 11.4.1 - Control of Copying):</p> <blockquote> <p>I personally consider it unfortunate that copy operations are defined by default and I prohibit copying of objects of many of my classes. However, C++ inherited its default assignment and copy constructors from C, and they are frequently used.</p> </blockquote> <p>So instead of "why doesn't C++ have a default <code>operator==()</code>?", the question should have been "why does C++ have a default assignment and copy constructor?", with the answer being those items were included reluctantly by Stroustrup for backwards compatibility with C (probably the cause of most of C++'s warts, but also probably the primary reason for C++'s popularity).</p> <p>For my own purposes, in my IDE the snippet I use for new classes contains declarations for a private assignment operator and copy constructor so that when I gen up a new class I get no default assignment and copy operations - I have to explicitly remove the declaration of those operations from the <code>private:</code> section if I want the compiler to be able to generate them for me.</p>
<p>I agree, for POD type classes then the compiler could do it for you. However what you might consider simple the compiler might get wrong. So it is better to let the programmer do it. </p> <p>I did have a POD case once where two of the fields were unique - so a comparison would never be considered true. However the comparison I needed only ever compared on the payload - something the compiler would never understand or could ever figure out on it's own.</p> <p>Besides - they don't take long to write do they?!</p>
26,790
<p>I need to calculate averages, standard deviations, medians etc for a bunch of numerical data. Is there a good open source .NET library I can use? I have found NMath but it is not free and may be overkill for my needs.</p>
<p>I found this on the CodeProject website. It looks like a good C# class for handling most of the basic statistical functions.</p> <ul> <li><a href="http://www.codeproject.com/KB/cs/csstatistics.aspx" rel="noreferrer">http://www.codeproject.com/KB/cs/csstatistics.aspx</a></li> </ul>
<p>If you just need to do some one-off number crunching, a spreadsheet is far and away your best tool. It's trivial to spit out a simple CSV file from C#, which you can then load up in Excel (or whatever):</p> <pre><code>class Program { static void Main(string[] args) { using (StreamWriter sw = new StreamWriter("output.csv", false, Encoding.ASCII)) { WriteCsvLine(sw, new List&lt;string&gt;() { "Name", "Length", "LastWrite" }); DirectoryInfo di = new DirectoryInfo("."); foreach (FileInfo fi in di.GetFiles("*.mp3", SearchOption.AllDirectories)) { List&lt;string&gt; columns = new List&lt;string&gt;(); columns.Add(fi.Name.Replace(",", "&lt;comma&gt;")); columns.Add(fi.Length.ToString()); columns.Add(fi.LastWriteTime.Ticks.ToString()); WriteCsvLine(sw, columns); } } } static void WriteCsvLine(StreamWriter sw, List&lt;string&gt; columns) { sw.WriteLine(string.Join(",", columns.ToArray())); } } </code></pre> <p>Then you can just 'start excel output.csv' and use functions like "=MEDIAN(B:B)", "=AVERAGE(B:B)", "=STDEV(B:B)". You get charts, histograms (if you install the analysis pack), etc.</p> <p>The above doesn't handle everything; generalized CSV files are more complex than you might think. But it's "good enough" for much of the analysis I do.</p>
16,862
<p>I would like to create a Delphi application for Windows XP which allows dropping of files dragged from Windows Explorer (the Desktop or folder windows) or other applications which support this operation (such as Total Commander). What about vice-versa? When the user drags an icon from my application, I should be able to set the contents of the dragged object to custom data. <br /><br /> My goal is to create a custom application toolbar, onto which I can drop applications and show their icons or drag applications or other entities from it. <br /><br /> How can this be done?</p>
<p>This can be done with <a href="http://melander.dk/delphi/dragdrop/" rel="noreferrer">The Drag and Drop Component Suite</a>. It also has examples for what you want.</p>
<p><a href="http://blogs.msdn.com/oldnewthing" rel="nofollow noreferrer">Raymond Chen</a> has a nice series of articles about drag&amp;drop:</p> <ul> <li><a href="https://devblogs.microsoft.com/oldnewthing/tag/what-a-drag" rel="nofollow noreferrer">What a drag Archives | The Old New Thing</a></li> <li><a href="https://devblogs.microsoft.com/oldnewthing/20080318-00/?p=23083" rel="nofollow noreferrer">What a drag: Dragging a virtual file (HGLOBAL edition)</a></li> <li><a href="https://devblogs.microsoft.com/oldnewthing/20080320-00/?p=23063" rel="nofollow noreferrer">What a drag: Dragging a virtual file (IStorage edition)</a></li> <li><a href="https://devblogs.microsoft.com/oldnewthing/20080319-00/?p=23073" rel="nofollow noreferrer">What a drag: Dragging a virtual file (IStream edition)</a></li> </ul> <p>There are many other good articles on his blog when you search for drag and drop.</p>
37,726
<p>Use case:</p> <ol> <li>A does something on his box and gots stuck. He asks B (remote) for support.</li> <li>B logs into the session of A, sees all windows, A was seeing and is able to manipulate the GUI.</li> </ol> <p>If A uses Windows it is very convenient to log into a running session e.g. via VNC. But if A uses Linux, AFAIK, this is not possible. Using VNC requires a "vncserver"-session, which is a separate session. You could get screen captures from remote by querying the X-server, but you cannot press buttons on the screen.</p> <p>Is there some workaround for this?</p>
<p>Actually, I revise my statement... <strong>in IE7</strong>, you <strong>CAN</strong> do some scaling.</p> <pre><code>&lt;div style="zoom:5;font-size:20%;overflow-x:auto;"&gt; Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! &lt;/div&gt; </code></pre> <p>zoom tells IE to scale up the contents by 500%, and I've set the font-size to be 1/5 of normal (thus remain the same)... this scales the scrollbars (but it looks a bit ugly at this zoom, since the images are raster based, not vector based.</p>
<p>There is a way, but it's IMO not possible with JS or CSS.</p> <p>If you have access to the terminal in question, you can set the theme property to have a larger scrollbar. It's at Control Panels -> Display -> tab Appearance -> Advanced -> item Scrollbar -> adjust size as desired (<a href="http://i33.tinypic.com/idt7x1.png" rel="nofollow noreferrer">screenshot</a>)</p>
32,367
<h3>Problem</h3> <p>I've got a collection of <code>IThing</code>s and I'd like to create a <code>HierarchicalDataTemplate</code> for a <code>TreeView</code>. The straightforward <code>DataType={x:Type local:IThing}</code> of course doesn't work, probably because the WPF creators didn't want to handle the possible ambiguities.</p> <p>Since this should handle <code>IThing</code>s from different sources at the same time, referencing the implementing class is out of question. </p> <h3>Current solution</h3> <p>For now I'm using a ViewModel which proxies IThing through a concrete implementation:</p> <pre><code>public interface IThing { string SomeString { get; } ObservableCollection&lt;IThing&gt; SomeThings { get; } // many more stuff } public class IThingViewModel { public IThing Thing { get; } public IThingViewModel(IThing it) { this.Thing = it; } } &lt;!-- is never applied --&gt; &lt;HierarchicalDataTemplate DataType="{x:Type local:IThing}"&gt; &lt;!-- is applied, but looks strange --&gt; &lt;HierarchicalDataTemplate DataType="{x:Type local:IThingViewModel}" ItemsSource="{Binding Thing.SomeThings}"&gt; &lt;TextBox Text="{Binding Thing.SomeString}"/&gt; &lt;/HierarchicalDataTemplate&gt; </code></pre> <h3>Question</h3> <p>Is there a better (i.e. no proxy) way?</p>
<p>The reason for this is that the default template selector supports only concrete types, not interfaces. You need to create a custom DataTemplateSelector and apply it to the ItemTemplateSelector property of the TreeView. I can't find the URL where I found an example of it, but hopefully with this info, you can Google it.</p>
<p>Another solution is you give a key to the HierarchicalDataTemplate and put it in the Windows.Resources, and manually reference to it in the TreeView. <code>&lt;TreeView ItemDataTemplate={StaticResource templateKey}/&gt;</code> </p> <p>But that limits the autoselection of data template according to data type, which is provided by WPF TreeView.</p>
32,355
<p>I have a J2ME application that needs to communicate with my server, and download information for the application in XML. My application could run a lot faster if I had a better format of data, which would allow me to have more efficient parsing code.</p> <p>Does anyone know an efficient substitute for XML? Maybe something specific for mobile phones?</p>
<p><a href="https://stackoverflow.com/questions/8599/best-binary-xml-format-for-javame">Best binary XML format for JavaME</a></p> <p>The conclusion being <a href="http://en.wikipedia.org/wiki/WBXML" rel="nofollow noreferrer">WBXML</a> which I would agree with.</p>
<p>There's always JSON, but I don't know if it is what you need.</p> <p><a href="http://java.sun.com/developer/technicalArticles/javame/json-me/" rel="nofollow noreferrer">http://java.sun.com/developer/technicalArticles/javame/json-me/</a></p>
21,953
<p>I'm working on a regular expression in a <code>.NET</code> project to get a specific tag. I would like to match the entire DIV tag and its contents:</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;title&gt;Test&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;p&gt;The first paragraph.&lt;/p&gt; &lt;div id='super_special'&gt; &lt;p&gt;The Store paragraph&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/head&gt; </code></pre> <p>Code:</p> <pre><code> Regex re = new Regex("(&lt;div id='super_special'&gt;.*?&lt;/div&gt;)", RegexOptions.Multiline); if (re.IsMatch(test)) Console.WriteLine("it matches"); else Console.WriteLine("no match"); </code></pre> <p>I want to match this:</p> <pre><code>&lt;div id="super_special"&gt; &lt;p&gt;Anything could go in here...doesn't matter. Let's get it all&lt;/p&gt; &lt;/div&gt; </code></pre> <p>I thought <code>.</code> was supposed to get all characters, but it seems to having trouble with the carriage returns. What is my regex missing?</p> <p>Thanks.</p>
<p>Please, pretty please, do yourself a <em>huge</em> favor: use an HTML parser for parsing HTML. Seriously. That's what they are there for.</p> <p>HTML is a <em>very</em> complex language. No matter <em>how long</em> you will be tweaking, fiddling, fixing, honing your Regexp, there will <em>always</em> be a case you're missing.</p> <p>Anyway, you have to tell your Regexp engine to match multiple lines instead of just one. In some of the most popular ones you do that by applying the <code>/m</code> modifier.</p> <p>But let me repeat: <em>please</em> use an HTML parser. Everytime someone uses a Regexp to parse HTML, a kitten dies ...</p>
<p>. (dot) Matches any single character except line break characters \r and \n. Most regex flavors have an option to make the dot match line break characters too. . matches x or (almost) any other character </p>
10,440
<p>In follow up to <a href="https://stackoverflow.com/questions/56820/round-in-python-doesnt-seem-to-be-rounding-properly">this question</a>, it appears that some numbers cannot be represented by floating point at all, and instead are approximated.</p> <p>How are floating point numbers stored?</p> <p>Is there a common standard for the different sizes?</p> <p>What kind of gotchas do I need to watch out for if I use floating point?</p> <p>Are they cross-language compatible (ie, what conversions do I need to deal with to send a floating point number from a python program to a C program over TCP/IP)?</p>
<p>As mentioned, the <a href="http://en.wikipedia.org/wiki/IEEE_754-1985" rel="noreferrer">Wikipedia article on IEEE 754</a> does a good job of showing how floating point numbers are stored on most systems.</p> <p>Now, here are some common gotchas:</p> <ul> <li>The biggest is that you almost never want to compare two floating point numbers for equality (or inequality). You'll want to use greater than/less than comparisons instead.</li> <li>The more operations you do on a floating point number, the more significant rounding errors can become.</li> <li>Precision is limited by the size of the fraction, so you may not be able to correctly add numbers that are separated by several orders of magnitude. (For example, you won't be able to add 1E-30 to 1E30.)</li> </ul>
<p>What I remember is a 32 bit floating point is stored using 24 bits for a actual number, and the remain 8 bits are used as a power of 10, determining where the decimal point is.</p> <p>I'm a bit rusty on the subject tho...</p>
8,111
<p>I have an ASP.NET webservice with along the lines of:</p> <pre><code>[WebService(Namespace = "http://internalservice.net/messageprocessing")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class ProvisioningService : WebService { [WebMethod] public XmlDocument ProcessMessage(XmlDocument message) { // ... do stuff } } </code></pre> <p>I am calling the web service from ASP using something like:</p> <pre><code>provWSDL = "http://servername:12011/MessageProcessor.asmx?wsdl" Set service = CreateObject("MSSOAP.SoapClient30") service.ClientProperty("ServerHTTPRequest") = True Call service.MSSoapInit(provWSDL) xmlMessage = "&lt;request&gt;&lt;task&gt;....various xml&lt;/task&gt;&lt;/request&gt;" result = service.ProcessMessage(xmlMessage) </code></pre> <p>The problem I am encountering is that when the XML reaches the ProcessMessage method, the web service plumbing has added a default namespace along the way. i.e. if I set a breakpoint inside ProcessMessage(XmlDocument message) I see:</p> <pre><code>&lt;request xmlns="http://internalservice.net/messageprocessing"&gt; &lt;task&gt;....various xml&lt;/task&gt; &lt;/request&gt; </code></pre> <p>When I capture packets on the wire I can see that the XML sent by the SOAP toolkit is slightly different from that sent by the .NET WS client. The SOAP toolkit sends:</p> <pre><code>&lt;SOAP-ENV:Envelope xmlns:SOAPSDK1="http://www.w3.org/2001/XMLSchema" xmlns:SOAPSDK2="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAPSDK3="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;SOAP-ENV:Body&gt; &lt;ProcessMessage xmlns="http://internalservice.net/messageprocessing"&gt; &lt;message xmlns:SOAPSDK4="http://internalservice.net/messageprocessing"&gt; &lt;request&gt; &lt;task&gt;...stuff to do&lt;/task&gt; &lt;/request&gt; &lt;/message&gt; &lt;/ProcessMessage&gt; &lt;/SOAP-ENV:Body&gt; &lt;/SOAP-ENV:Envelope&gt; </code></pre> <p>Whilst the .NET client sends:</p> <pre><code>&lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;soap:Body&gt; &lt;ProcessMessage xmlns="http://internalservice.net/messageprocessing"&gt; &lt;message&gt; &lt;request xmlns=""&gt; &lt;task&gt;...stuff to do&lt;/task&gt; &lt;/request&gt; &lt;/message&gt; &lt;/ProcessMessage&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre> <p>It's been so long since I used the ASP/SOAP toolkit to call into .NET webservices, I can't remember all the clever tricks/SOAP-fu I used to pull to get around stuff like this.</p> <p>Any ideas? One solution is to knock up a COM callable .NET proxy that takes the XML as a string param and calls the WS on my behalf, but it's an extra layer of complexity/work I hoped not to do.</p>
<p>I solved this:</p> <p>The SOAP client <em>request</em> node was picking up the default namespace from:</p> <pre><code>&lt;ProcessMessage xmlns="http://internalservice.net/messageprocessing"&gt; </code></pre> <p>Adding an empty default namespace to the XML sent by the ASP client overrides this behaviour:</p> <pre><code>xmlMessage = "&lt;request xmlns=''&gt;&lt;task&gt;....various xml&lt;/task&gt;&lt;/request&gt;" </code></pre>
<p>I take it you have access to the Services code, not just the consuming client right?</p> <p>Just pull the namespace out of the XmlDocument as the first part of the method.</p> <p>Something like:</p> <pre><code>XmlDocument changeDocumentNamespace(XmlDocument doc, string newNamespace) { if (doc.DocumentElement.NamespaceURI.Length &gt; 0) { doc.DocumentElement.SetAttribute("xmlns", newNameSpace); XmlDocument newDoc = new XmlDocument(); newDoc.LoadXml(doc.OuterXml); return newDoc; } else { return doc; } } </code></pre> <p>Then:</p> <pre><code>[WebService(Namespace = "http://internalservice.net/messageprocessing")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class ProvisioningService : WebService { [WebMethod] public XmlDocument ProcessMessage(XmlDocument message) { message = changeDocumentNamespace(message,String.Empty); // Do Stuff... } } </code></pre>
3,975
<p>What is the order of topics to explain to a .NET developer or user group to get them started and interested with alt.net tools and practices.</p> <ul> <li>ORM</li> <li>IoC</li> <li>TDD</li> <li>DDD</li> <li>DSL</li> <li>CI</li> <li>MVC - MVP</li> <li>Version Control (I think this is the one they get the fastest)</li> <li>Agile</li> <li>Etc, etc...</li> </ul>
<p>ALT.NET is more of an attitude than a set of tools and practices. </p> <p>I don't know that you can "get someone started with ALT.NET," per se.</p> <hr> <p>To me it is an attitude born of experience, not something you can put on like a coat. But that is <em>my</em> opinion, subject to change.</p>
<p>I don't mean becoming an <em>ALT.NETter</em> just in a way of letting them know that the stuff are out there but in a way that they can understand it and feel that it can help them.</p>
10,569
<p>Why can't you do this and is there are work around?</p> <p>You get this error.</p> <p>Msg 2714, Level 16, State 1, Line 13 There is already an object named '#temptable' in the database.</p> <pre><code>declare @x int set @x = 1 if (@x = 0) begin select 1 as Value into #temptable end else begin select 2 as Value into #temptable end select * from #temptable drop table #temptable </code></pre>
<p>This is a two-part question and while Kev Fairchild provides a good answer to the second question he totally ignores the first - <em>why is the error produced?</em></p> <p>The answer lies in the way the preprocessor works. This</p> <pre><code>SELECT field-list INTO #symbol ... </code></pre> <p>is resolved into a parse-tree that is directly equivalent to </p> <pre><code>DECLARE #symbol_sessionid TABLE(field-list) INSERT INTO #symbol_sessionid SELECT field-list ... </code></pre> <p>and this puts #symbol into the local scope's name table. The business with _sessionid is to provide each user session with a private namespace; if you specify two hashes (##symbol) this behaviour is suppressed. Munging and unmunging of the sessionid extension is (ovbiously) transparent.</p> <p>The upshot of all this is that multiple INTO #symbol clauses produce multiple declarations in the same scope, leading to Msg 2714.</p>
<p>I am going to guess that the issue is that you haven't created the #temptable.</p> <p>Sorry I can't be more detailed but since you haven't even tried to explain what you are seeing you get a less than stellar answer.</p>
6,863
<p>We are developing a web application, which will have a database with over 5 millon documents, all of them will be in various languages. The site is planned to have more than 3 million visits per month (hopefully more).</p> <p>We need a stable and scalable solution.</p> <p>We are now using Java EE over JBoss application server with PGSQL DB, but we would like to know if this fits the problem or there is a better solution, because the project is a the beginning and changes are yet viable.</p> <p>Also, as many of us, doesn't have a lot of experience with this type of projects, the opinions of the ones who does, will be very useful!</p> <p>I hope I made myself clear. Please let me know if you need more information.<br> Thanks in advance.</p>
<p>The architectural design considerations of your solution are probably more important than the choice of "platform". In other words, how are you going to make your application scale? Do you need to store distributed session? Do you need real-time database synchronization or something a little less up to date? How will you do request load balancing, or handle fail over? Can the business logic work over a distributed set of nodes/sites or whatever you envisage. </p> <p>Once you have a design that suits your purposes then the choice of your implementation platform can be a better informed decision. Whether it's java, .net, rails or whatever doesn't really matter. They all have their strength and weaknesses, as do the members of your team. Use their strengths to guide this part of your decision making process. Don't try to learn a new technology in tandem with building what sounds like a fairly serious site. </p> <p>I've used JBoss on a pretty large distributed ebook delivery system with tens of thousands of page views per day and it never missed a beat. Likewise I think Stack Overflow is a more than adequate example of the capabilities of the ASP.NET platform with regards to the numbers you are mentioning. </p> <p>Hope that helps.</p>
<p>I personally would not take responsibility to offer own solution to a team without asking for advice from somewhere else first. Same way as chaKa does. What I would not do is to rely on one source of help making final decision.</p> <p>You may need to consider following criteria:</p> <ol> <li>How much time do you have? What is development plan? Should you start right away or you will be given time to learn.</li> <li>Do you need framework? Are you expected to deliver quickly? How many requirements do you have? It all affects will it be framework based solution or from scratch.</li> <li>Will you support project as well? How many people will do it? You need to know also will project grow slowly or it should be deployed quickly and forgotten.</li> <li>What skills does your team have? What are they good at?</li> <li>What would make you excited and want to do your best implementing solution?</li> </ol> <p>I believe there is more to think about...</p>
44,370
<p>Got a bluescreen in windows while cloning a mercurial repository.</p> <p>After reboot, I now get this message for almost all hg commands:</p> <pre> c:\src\>hg commit waiting for lock on repository c:\src\McVrsServer held by '\x00\x00\x00\x00\x00\ x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' interrupted! </pre> <p>Google is no help.</p> <p>Any tips?</p>
<p>When "waiting for lock on repository", delete the repository file: <code>.hg/wlock</code> (or it may be in <code><code>.hg/store/lock</code></code>)</p> <p>When deleting the lock file, you must make sure nothing else is accessing the repository. (If the lock is a string of zeros or blank, this is almost certainly true).</p>
<p>If it only happens on mapped drives it might be bug <a href="https://bitbucket.org/tortoisehg/thg/issue/889/cant-commit-file-over-network-share" rel="nofollow">https://bitbucket.org/tortoisehg/thg/issue/889/cant-commit-file-over-network-share</a>. Using UNC path instead of drive letter seems to sidestep the issue.</p>
3,393
<p>Is it possible to use batch file (for XP) to call another batch file from <strong>different</strong> computer? if yes, how identify the target computer? Is it by IP comp ID?</p>
<p>Personally, as along as all the tables in the database are for the same application, I would recommend keeping them in the same database. If you run into performance problems, you should get more hardware. The most important reason not to split them up, is that no matter how much you think there is a partition in the data, you will inevitably need to join tables across the two databases which is a very costly, in terms of performance, operation to do.</p>
<p>If you want to start moving some things out to a second database make sure to do it with purpose. I do this when I realize some of the data will be reference data for several projects I'm working on. It becomes my "reference" database.</p> <p>Then my database list would look something like the following:<br> project1<br> project2<br> project3<br> reference </p>
36,812
<p>I have a structure which I need to populate and write to disk (several actually).</p> <p>An example is:</p> <pre><code>byte-6 bit0 - original_or_copy bit1 - copyright bit2 - data_alignment_indicator bit3 - PES_priority bit4-bit5 - PES_scrambling control. bit6-bit7 - reserved </code></pre> <p>In C I might do something like the following:</p> <pre><code>struct PESHeader { unsigned reserved:2; unsigned scrambling_control:2; unsigned priority:1; unsigned data_alignment_indicator:1; unsigned copyright:1; unsigned original_or_copy:1; }; </code></pre> <p>Is there any way to do this in C# that would enable me to access the bits using the struct dereferencing dot operator? </p> <p>For a couple of structures, I can just do bit shifting wrapped in an accessor function.</p> <p>I have loads of structures to handle in this way, so I'm looking for something that's easier to read and quicker to write.</p>
<p>I'd probably knock together something using attributes, then a conversion class to convert suitably attributed structures to the bitfield primitives. Something like...</p> <pre><code>using System; namespace BitfieldTest { [global::System.AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] sealed class BitfieldLengthAttribute : Attribute { uint length; public BitfieldLengthAttribute(uint length) { this.length = length; } public uint Length { get { return length; } } } static class PrimitiveConversion { public static long ToLong&lt;T&gt;(T t) where T : struct { long r = 0; int offset = 0; // For every field suitably attributed with a BitfieldLength foreach (System.Reflection.FieldInfo f in t.GetType().GetFields()) { object[] attrs = f.GetCustomAttributes(typeof(BitfieldLengthAttribute), false); if (attrs.Length == 1) { uint fieldLength = ((BitfieldLengthAttribute)attrs[0]).Length; // Calculate a bitmask of the desired length long mask = 0; for (int i = 0; i &lt; fieldLength; i++) mask |= 1 &lt;&lt; i; r |= ((UInt32)f.GetValue(t) &amp; mask) &lt;&lt; offset; offset += (int)fieldLength; } } return r; } } struct PESHeader { [BitfieldLength(2)] public uint reserved; [BitfieldLength(2)] public uint scrambling_control; [BitfieldLength(1)] public uint priority; [BitfieldLength(1)] public uint data_alignment_indicator; [BitfieldLength(1)] public uint copyright; [BitfieldLength(1)] public uint original_or_copy; }; public class MainClass { public static void Main(string[] args) { PESHeader p = new PESHeader(); p.reserved = 3; p.scrambling_control = 2; p.data_alignment_indicator = 1; long l = PrimitiveConversion.ToLong(p); for (int i = 63; i &gt;= 0; i--) { Console.Write( ((l &amp; (1l &lt;&lt; i)) &gt; 0) ? "1" : "0"); } Console.WriteLine(); return; } } } </code></pre> <p>Which produces the expected ...000101011. Of course, it needs more error checking and a slightly saner typing, but the concept is (I think) sound, reusable, and lets you knock out easily maintained structures by the dozen.</p> <p>adamw</p>
<p>I wrote one this morning with T4. :) Same example as Zbyl, though I threw in a bit of uint sizing fun. This is just a first pass, it could obviously use a little error checking. Also the bitFields spec array would be nicer in a separate file, maybe a .ttinclude, or a json/yaml..</p> <pre><code>=== BitFields.tt === &lt;#@ template language=&quot;C#&quot; #&gt; &lt;#@ assembly name=&quot;System.Core&quot; #&gt; &lt;#@ import namespace=&quot;System.Linq&quot; #&gt; &lt;# var bitFields = new[] { new { Name = &quot;rcSpan2&quot;, Fields = new[] { (&quot;smin&quot;, 13), (&quot;smax&quot;, 13), (&quot;area&quot;, 6) }, }, }; foreach (var bitField in bitFields) { static string getType(int size) =&gt; size switch { &gt; 32 =&gt; &quot;ulong&quot;, &gt; 16 =&gt; &quot;uint&quot;, &gt; 8 =&gt; &quot;ushort&quot;, _ =&gt; &quot;byte&quot;, }; var bitFieldType = getType(bitField.Fields.Sum(f =&gt; f.Item2)); #&gt; public struct &lt;#=bitField.Name#&gt; { &lt;#=bitFieldType#&gt; _bitfield; &lt;# var offset = 0; foreach (var (fieldName, fieldSize) in bitField.Fields) { var fieldType = getType(fieldSize); var fieldMask = $&quot;0x{((1UL&lt;&lt;fieldSize)-1):X}U&quot;; #&gt; public &lt;#=fieldType#&gt; &lt;#=fieldName#&gt; // : &lt;#=fieldSize#&gt; { get =&gt; (&lt;#=fieldType#&gt;)(&lt;#=offset &gt; 0 ? $&quot;(_bitfield &gt;&gt; {offset})&quot; : &quot;_bitfield&quot;#&gt; &amp; &lt;#=fieldMask#&gt;); set =&gt; _bitfield = (&lt;#=bitFieldType#&gt;)((_bitfield &amp; ~((&lt;#=bitFieldType#&gt;)&lt;#=fieldMask#&gt; &lt;&lt; &lt;#=offset#&gt;)) | ((&lt;#=bitFieldType#&gt;)(value &amp; &lt;#=fieldMask#&gt;) &lt;&lt; &lt;#=offset#&gt;)); } &lt;# offset += fieldSize; } #&gt; } &lt;#}#&gt; === BitFields.cs === (generated) public struct rcSpan2 { uint _bitfield; public ushort smin // : 13 { get =&gt; (ushort)(_bitfield &amp; 0x1FFFU); set =&gt; _bitfield = (uint)((_bitfield &amp; ~((uint)0x1FFFU &lt;&lt; 0)) | ((uint)(value &amp; 0x1FFFU) &lt;&lt; 0)); } public ushort smax // : 13 { get =&gt; (ushort)((_bitfield &gt;&gt; 13) &amp; 0x1FFFU); set =&gt; _bitfield = (uint)((_bitfield &amp; ~((uint)0x1FFFU &lt;&lt; 13)) | ((uint)(value &amp; 0x1FFFU) &lt;&lt; 13)); } public byte area // : 6 { get =&gt; (byte)((_bitfield &gt;&gt; 26) &amp; 0x3FU); set =&gt; _bitfield = (uint)((_bitfield &amp; ~((uint)0x3FU &lt;&lt; 26)) | ((uint)(value &amp; 0x3FU) &lt;&lt; 26)); } } </code></pre>
3,529
<p>I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?</p> <p>I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?</p>
<p>The answer is no.</p> <p>At least, not until something like the following is implemented:</p> <pre><code>from __future__ import braces </code></pre>
<p>Many Python IDEs and generally-capable text/source editors can handle the whitespace for you.</p> <p>However, it is best to just "let go" and enjoy the whitespace rules of Python. With some practice, they won't get into your way at all, and you will find they have many merits, the most important of which are:</p> <ol> <li>Because of the forced whitespace, Python code is simpler to understand. You will find that as you read code written by others, it is easier to grok than code in, say, Perl or PHP.</li> <li>Whitespace saves you quite a few keystrokes of control characters like { and }, which litter code written in C-like languages. Less {s and }s means, among other things, less RSI and wrist pain. This is not a matter to take lightly.</li> </ol>
8,862
<p>I would like to use a secure SSL login on my website! I have not used SSL before, so I am looking for some good reading. Can anyone tell me where I can find some sample code of SSL snippets or page code. (Not too technical)</p> <ul> <li>I do have a static IP</li> <li>My host is set-up to handle SSL Pages. </li> </ul> <p>Interested in: Basic page code. / Tree structure. / Other </p> <p>Paul </p>
<p>My first thought would be to simply call a function to redirect to the https: version of the current page when you need to be secure.</p> <p>Some code like this:</p> <pre><code>if($requireSSL &amp;&amp; $_SERVER['SERVER_PORT'] != 443) { header("HTTP/1.1 301 Moved Permanently"); header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); exit(); } </code></pre> <p><a href="http://www.somacon.com/p536.php" rel="nofollow noreferrer">Reference</a></p>
<p>SSL happens before the request ever reaches PHP. The only impact on your PHP would be in the self-facing links you're publishing, which you'd want to switch from http://... to https://... There's a $_SERVER['HTTPS'] variable you could use to trigger this change if you'll be accepting both SSL and non-SSL connections. But if you're moving everything to SSL, you'll want to move all your links once rather than having it check on each request.</p>
22,522
<p>I have a set of radio buttons where a selection is required. In addition, there is an optional text box that shows up next to one of the selections.</p> <p>What would be the best way to make it clear what is required and what is optional?</p> <pre><code>&lt;strong&gt;User Availability:&lt;/strong&gt;&lt;br&gt; &lt;input value="Available" type="radio"&gt; Available&lt;br /&gt; &lt;input value="Unvailable" type="radio"&gt; Unvailable until &lt;input type="text"&gt; &lt;small&gt;MM/DD/YYYY&lt;/small&gt; </code></pre> <p>Thanks in advance for any ideas. I'm also open to a completely different approach.</p> <p><strong>Clarification:</strong> The "optional" part is the date. You MUST select either Available or Unavailable. But the date is optional.</p> <p>This is a UI question, not a technical one.</p>
<p>Assuming "mm/dd/yyy" is the textbox, I'd put the this text in the textbox, with it being cleared when the user clicks or otherwise sets focus on the textbox:</p> <p>(date) (optional)</p>
<p>Why bother displaying something that nobody cares about? If you, or your users cared about the date then it would be compulsory. </p>
41,153
<p>How can you <strong>cascade</strong> filter the attributes of more dimensions in a SSAS cube, viewed in Excel 2007.</p> <p>For example, if we have a cube <em>Sales</em> with the dimension <em>Time</em> and dimension <em>Client</em>, once the dimension <em>Time</em> is filtered to show only the sales from a particular date, if "Client.ClientName" is chosen as a filter in the filter area, how can the list of clients be filtered so that only the clients that have sales in the particular date, be shown.</p>
<p>Take a look at <a href="http://www.clicksoft.ro" rel="nofollow noreferrer">www.clicksoft.ro</a> </p> <p>The product named QuickCubeFiltrator is a wizard like addin for excel 2007 that does cascade filtering. Might be what you need.</p>
<p>I have tried this before and haven't had much luck. Not sure you can really do it easily. You can try using named sets and calculated members but most of the time it depends on your data and hierarchies. You can also look at reporting services, and how it does it behind the scenes in MDX, but I don't know what good that will do you in Excel though. Like I said, this is a tough one.</p>
8,981
<p>One of my co-workers has resigned and was made to leave the premises before checking in all of his code to TFS. I have access to the physical files. Is there a way for me to access his workspace and check in some of the changes that are still left unchecked in? From tfs I can see which files he has checked out but no way of seeing the exact changes unless very manually. </p>
<p>In TFS 2010, there is a new feature called 'Public Workspaces'. This allows multiple people to <strong>share the same workspace folders</strong> on a computer, but authenticating to TFS using their <strong>own</strong> logon.</p> <p>A TFS administrator can change a workspace to a 'Public Workspace' by running a command like the following:</p> <pre><code>tf workspace /collection:http://yourserver:8080/tfs/yourCollection WorkspaceName;domain\CurrentWorkspaceOwner /permission:Public </code></pre> <p><em>(This command can be run on any computer, it doesn't need to be run on the same computer as the workspace you are trying to change)</em></p> <p>If there is only one other user that needs to use the workspace, perhaps a simpler method is to just change the owner of the workspace. This can be done by a TFS administrator with the following command:</p> <pre><code>tf workspace /collection:http://yourserver:8080/tfs/yourCollection WorkspaceName;domain\CurrentWorkspaceOwner /newowner:domain\NewWorkspaceOwner </code></pre> <p>Once you have done either of these things, you can logon to that computer as the new owner and use the workspace as if it were your own.</p> <p>You can read more about this feature in this blog post <a href="http://blogs.msdn.com/b/granth/archive/2009/11/08/tfs2010-public-workspaces.aspx" rel="noreferrer">TFS2010: Public Workspaces</a>.</p>
<p>You could use some diff tool like beyond compare to visualise the actual differences.</p> <p>To manage others' workspaces and even checked out files it is hard to beat <a href="http://www.attrice.info/cm/tfs/" rel="nofollow noreferrer">Team Sidekicks</a>, which is free and provides brilliant interface for this and many other routine TFS work.</p>
32,739
<p>I'm attempting to find the best methodology for finding a specific pattern and then replace the ending portion of the pattern. Here is a quick example (in C#):</p> <p>//Find any year value starting with a bracket or underscore</p> <pre><code>string patternToFind = "[[_]2007"; Regex yearFind = new Regex(patternToFind); </code></pre> <p>//I want to change any of these values to x2008 where x is the bracket or underscore originally in the text. I was trying to use Regex.Replace(), but cannot figure out if it can be applied. </p> <p>If all else fails, I can find Matches using the MatchCollection and then switch out the 2007 value with 2008; however, I'm hoping for something more elegant</p> <pre><code>MatchCollections matches = yearFind.Matches(" 2007 [2007 _2007"); foreach (Match match in matches){ //use match to find and replace value } </code></pre>
<p>Your pattern does not work as described: as described you need to start with "<code>\[|_</code>" (the pipe means OR), and the solution to your actual problem is <em>regex grouping</em>. Surround the part of the pattern you are interested in in brackets "(" and ")" and you can access them in the replacer.</p> <p>You therefore need a pattern like this: <code>/^(\[|_)2007/</code></p> <p>edit: .NET code</p> <pre><code>string s = Regex.Replace(source, @"^(\[|_)2007", @"$12008"); </code></pre> <p>n.b. misunderstood the requirement, pattern amended</p>
<p>To show substitution (using vim in this case). if I have a file with the following contents:</p> <pre><code>aaa _2007 bbb , 2007 ccc [2007] </code></pre> <p>and I use the regular expression</p> <pre><code>:1,$ s/\([_[ ]\)\(2007\)/\12008/g </code></pre> <p>The first group (in the (, )) will match the character preceding the year and the second group will match the year 2007. The substitution substitutes in the first match and overwrites whatever was matched by the the second group with 2008, giving:</p> <pre><code>aaa _2008 bbb , 2008 ccc [2008] </code></pre> <p>Different regex libraries will have minor syntactic variations on this principle.</p>
43,820
<p>If I open a solution in Visual Studio 2008 and run a unit test then VS creates a new .vsmdi file in the Solution Items folder and gives it the next number available e.g. My Solution2.vsmdi.</p> <p>Any idea why VS is doing this and how I can get it to stop doing this?</p>
<p>It appears that the <a href="http://web.archive.org/web/20080302162715/http://blogs.vertigosoftware.com/teamsystem/archive/2006/06/23/Beware_the_Team_Test_VSMDI_file.aspx" rel="nofollow noreferrer">VSMDI problem is a known bug and has been around since VS2005 Team System</a> but it has no clear fix as yet. Another reason to NOT use MS Test.</p> <p>An MSDN blog details <a href="http://blogs.msdn.com/buckh/archive/2006/11/04/how-to-run-tests-without-test-metadata-files-and-test-lists-vsmdi-files.aspx" rel="nofollow noreferrer">how to run unit tests without VSMDI files</a>.</p>
<p>An <a href="http://blogs.vertigosoftware.com/teamsystem/archive/2006/06/23/Beware_the_Team_Test_VSMDI_file.aspx" rel="nofollow noreferrer">old post but</a> vsmdi is a meta data file created by the test system.</p>
4,782
<p>I've seen this done in a few sites, an example is <a href="http://www.artofadambetts.com/weblog/?p=169" rel="noreferrer">artofadambetts.com</a>. The scroll bar on the page scrolls only an element of the page, not the entire page. I looked at the source and havent't been able to figure it out yet. How is this done?</p>
<p>That's pretty nifty. He uses "position:fixed" on most of the divs, and the one that scrolls is the one that doesn't have it. </p>
<p>To put scroll bars on an element such as a div:</p> <p><code>&lt;div style="overflow-x: auto; overflow-y: auto;&gt;the content&lt;/div&gt;</code></p> <p>If you only want a horizontal or vertical scroll bar, only use whichever of overflow-x and overflow-y you need.</p>
10,891
<p>On Windows, is there any way to programatically approve a USB device after insertion, if it is of a certain type (say Removable Drive) allow its use, otherwise not? Also not to allow running of drivers, only allow usage of the device in an approved way?</p> <p>I.E. We want to allow the insertion of USB drives, but not have to worry about virus's being installed.</p> <p><strong>EDIT</strong> Sorry, I wasn't very clear on the posting of this question. Yes this is Windows, but I am not worried about auto-run programs, that is of course turned off. Users will not be able to access any executables, just data will be read off of the drive. They will not have access to any UI other than what we allow (it's a Kiosk). What I am concerned about is device drivers running and installing software (ala U3, and other USB software that installs itself when you insert a USB drive). There are a bunch of virus's in the wild that can be run just by inserting a USB drive into a system. We have restricted things with group-policy to the level that we can, but I can't find a way to not allow the installation of drivers without creating a base whitelist of USB drives that come pre-installed and nothing else would work (ie. Do not allow installation of drivers). </p>
<p>(Since you're worried about viruses I'll assume that we're talking about Windows.)</p> <p>There is no point in restricting the user like that. Make sure the user does not have Administrator privileges. And install an up-to-date virus scanner.</p> <p>Rationale: If you're not going to permit even reading files, then allowing a USB drive would be useless anyway. So you are going to permit reading files from a USB drive. But then someone could already install a virus by copying it to the local hard drive and run it from there.</p>
<p>No. You can restrict access to removable media using GPO, but you can't specify what kind of files are allowed on the removable media or if they can execute or not.</p> <p>EDIT: upvoting thomas. better answer than mine.</p>
11,515
<p>I am calling <code>SPWeb.GetSiteData(anSpCrossListQuery)</code>.</p> <p>It fails to bring back any results or any errors when I call it with an accidental space at the end of the CAML query <code>&lt;Where&gt;&lt;/Where&gt;</code> clause.</p> <p>Anyone have an idea why?</p>
<p>In C++, <strong>struct</strong>s and <strong>class</strong>es are identical except for the default public/privateness of their members. (This default is easily, and usually, overridden.)</p> <p>However, most programmers think of a struct as a "data object" and a class as an "interactive object". That's not a bad thing; and in fact should be taken advantage of. If something is just an inanimate lump of data (even maybe if it has a couple of inspector methods), use a struct for it; it'll save a bit of effort when a programmer is trying to see what it's for.</p>
<p>Structs are fine as long as they're kept small. As you probably know, they are allocated on the stack (not the heap) so you need to watch the size. They can come in handy for small data structures like Point, Size, etc. A class is usually the better choice though, being a reference type and all.</p>
31,383
<p>In JavaScript, using the Prototype library, the following functional construction is possible:</p> <pre><code>var words = ["aqueous", "strength", "hated", "sesquicentennial", "area"]; words.pluck('length'); //-&gt; [7, 8, 5, 16, 4] </code></pre> <p>Note that this example code is equivalent to</p> <pre><code>words.map( function(word) { return word.length; } ); </code></pre> <p>I wondered if something similar is possible in F#:</p> <pre><code>let words = ["aqueous"; "strength"; "hated";"sesquicentennial"; "area"] //val words: string list List.pluck 'Length' words //int list = [7; 8; 5; 16; 4] </code></pre> <p>without having to write:</p> <pre><code>List.map (fun (s:string) -&gt; s.Length) words </code></pre> <p>This would seem quite useful to me because then you don't have to write functions for every property to access them.</p>
<p>I saw your request on the F# mailing list. Hope I can help. </p> <p>You could use type extension and reflection to allow this. We simple extend the generic list type with the pluck function. Then we can use pluck() on any list. An unknown property will return a list with the error string as its only contents.</p> <pre><code>type Microsoft.FSharp.Collections.List&lt;'a&gt; with member list.pluck property = try let prop = typeof&lt;'a&gt;.GetProperty property [for elm in list -&gt; prop.GetValue(elm, [| |])] with e-&gt; [box &lt;| "Error: Property '" + property + "'" + " not found on type '" + typeof&lt;'a&gt;.Name + "'"] let a = ["aqueous"; "strength"; "hated"; "sesquicentennial"; "area"] a.pluck "Length" a.pluck "Unknown" </code></pre> <p>which produces the follow result in the interactive window:</p> <pre> > a.pluck "Length" ;; val it : obj list = [7; 8; 5; 16; 4] > a.pluck "Unknown";; val it : obj list = ["Error: Property 'Unknown' not found on type 'String'"] </pre> <p>warm regards,</p> <p>DannyAsher</p> <p>> > > > ></p> <p>NOTE: When using <code>&lt;pre</code>> the angle brackets around <pre>&lt;'a></pre> didn't show though in the preview window it looked fine. The backtick didn't work for me. Had to resort you the colorized version which is all wrong. I don't think I'll post here again until FSharp syntax is fully supported. </p>
<p>Prototype's <code>pluck</code> takes advantage of that in Javascript <code>object.method()</code> is the same as <code>object[method]</code>. </p> <p>Unfortunately you can't call <code>String.Length</code> either because it's not a static method. You can however use:</p> <pre><code>#r "FSharp.PowerPack.dll" open Microsoft.FSharp.Compatibility words |&gt; List.map String.length </code></pre> <p><a href="http://research.microsoft.com/fsharp/manual/FSharp.PowerPack/Microsoft.FSharp.Compatibility.String.html" rel="nofollow noreferrer">http://research.microsoft.com/fsharp/manual/FSharp.PowerPack/Microsoft.FSharp.Compatibility.String.html</a></p> <p>However, using <code>Compatibility</code> will probably make things more confusing to people looking at your code.</p>
10,220
<p>I have developed a web application using internationalization best practices such as putting all my displayable strings in property files, etc, etc.</p> <p>I would like to have the strings in the property files translated into 5 different languages.</p> <p>Does anyone have any experience using Mechanical Turk or another crowd sourcing service for language translation? </p> <p>The reason I don't want to just hire a translation company or service is because I want to eventually have ongoing content fed into the translation service via an API.</p> <p>My Google results for more information on this topic were surprisingly dismal. Any links or pointers are appreciated.</p>
<p>If your software is open source you can use <a href="http://launchpad.net" rel="nofollow noreferrer">Launchpad</a> for translating.</p>
<p>I don't have any experience crowd-sourcing translations, but my advice would be to find some dependable freelance translators in your target languages (check out Proz.com), and keep going back to them every time you have new content. Application UIs are notoriously difficult to localize because of lack of context in the resource files, and so you want someone who understands the application and is able/willing to test the localized version. Each of the localizations will undoubtedly reveal i18n bugs as well, so there is likely to be a bit of back and forth the first time around. I guess my point is that you don't want arms-length relationships with your translators; they should feel like an extension of your team. </p> <p>Anyway, bravo for internationalizing your application. Good luck!</p>
41,100
<p><a href="https://3dprinting.stackexchange.com/questions/12153/updating-marlin-firmware-step-by-step-guide">Updating Marlin Firmware - Step by Step Guide</a></p> <p>Page asks for step by step updates, but is locked for comments, answers, or edits. How does one help?</p>
<p>Users with a high enough reputation were able to edit the question and the answer, it has been locked for lower reputation users to prevent adding other answers while we were establishing a framework for the answer. Once the answer is visible the whole community will be able to add to the answer within the framework of the answer. Note that we possibly will lock the addition of new answers.</p>
<p>The question was locked when several of the vets [0scar and me mainly] were working on the infancy of the answer - it was 2 days of a hot mess as we went through the source code to find all the essential settings we usually forget after we have set them for our own machine distributions - if we even do our own distribution and not take one from another that was so kind to make it for the same machine.</p>
75
<p>If I'm rendering a regular view in asp.net mvc the only domain object properties that show up in my page the ones I specifically write out. For example:</p> <pre><code>&lt;div&gt;&lt;%= Customer.FirstName %&gt;&lt;/div&gt; </code></pre> <p>However, if I serialize a domain object for json it will include every property. Example:</p> <pre><code>public JsonResult Customer (int? id) { Customer customer = _serviceLayer.GetCustomer (id.Value); return Json (customer); } </code></pre> <p>Since I don't want every Customer property exposed what is the best way to filter the output properties for json in this case? Can you use an include/exclude list like UpdateModel()? Use a proxy class such as public class JsonCustomer? What would you recommend?</p>
<p>I use anonymous types for this:</p> <pre><code>var customer = from c in serviceLayer.GetCustomers() where c.Id == id.Value select new { FirstName = c.FirstName }; </code></pre> <p>This is not just a good idea. Rather, it's protection against the exception that you will get when calling Json() if your object graph contains a circular reference.</p>
<p>I ran into the same problem and THE ONE OF SOLUTION IS to</p> <p>Use [ScriptIgnore] atribute .. it will solve the problem.</p> <p>add system.web.extensions reference and add namespace:</p> <p>Using System.Web.Script.Serialization.</p> <p>If you still have questions..Read on..for some detailed explanation..</p> <p>i have a User class with..</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using Iesi.Collections.Generic; using System.Runtime.Serialization; namespace RAPortal.Core.Entities { public class User { private int _userId; private string _firstName; private string _lastName; private IList &lt; Application &gt; _applications; private IList &lt; Group &gt; _groups; private IList &lt; ApplicationRequest &gt; _applicationRequests; </code></pre> <p>....Properties..</p> <pre><code> public virtual int UserId { get { return _userId; } set { _userId = value; } } public virtual string Title { get { return _title; } set { _title = !String.IsNullOrEmpty(value) ? value.ToUpper().Trim() : null; } } public virtual IList &lt; Group &gt; Groups { get { return _groups; } set { _groups = value; } } public virtual IList &lt; UserPrivilege &gt; UserPrivileges { get { return _userPrivileges; } set { _userPrivileges = value; } } public virtual IList &lt; UserRole &gt; UserRoles { get { return _userRoles; } set { _userRoles = value;} } </code></pre> <p>...so on...</p> <p>and I have Groups class..</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization; using System.Runtime.Serialization; namespace RAPortal.Core.Entities { public class Group { private int _groupId; private string _name; private IList &lt; User &gt; _users; public virtual int GroupId { get { return _groupId; } set { _groupId = value; } } public virtual string Name { get { return _name; } set { _name = !String.IsNullOrEmpty(value) ? value.ToUpper().Trim() : null; } } [ScriptIgnore] public virtual IList &lt; User &gt; Users { get { return _users; } set { _users = value; } } } } </code></pre> <p>Since User is referenced in the groups.. the json think that it is Circular reference and It will throw an exception..so the fix is to add [ScriptIgnore] on top of the User. And add the reference and namespace to this class like it..</p> <p>It solved my problem .. I am sure there are better ways out there !!! Cheers...</p> <p>And remember you should add [scriptIgnore] only in the groups class and not in the Users class..</p>
48,762
<p><strong>Question:</strong> How can I process a form using jQuery and the $.ajax request so that the data is passed to a script which writes it to a database?</p> <p><strong>Problem:</strong> I have a simple email signup form that when processed, adds the email along with the current date to a table in a MySQL database. Processing the form without jQuery works as intended, adding the email and date. With jQuery, the form submits successfully and returns the success message. However, no data is added to the database.</p> <p>Any insight would be greatly appreciated! </p> <pre><code> &lt;!-- PROCESS.PHP --&gt; &lt;?php // DB info $dbhost = '#'; $dbuser = '#'; $dbpass = '#'; $dbname = '#'; // Open connection to db $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); mysql_select_db($dbname); // Form variables $email = $_POST['email']; $submitted = $_POST['submitted']; // Clean up function cleanData($str) { $str = trim($str); $str = strip_tags($str); $str = strtolower($str); return $str; } $email = cleanData($email); $error = ""; if(isset($submitted)) { if($email == '') { $error .= '&lt;p class="error"&gt;Please enter your email address.&lt;/p&gt;' . "\n"; } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", $email)) { $error .= '&lt;p class="error"&gt;Please enter a valid email address.&lt;/p&gt;' . "\n"; } if(!$error){ echo '&lt;p id="signup-success-nojs"&gt;You have successfully subscribed!&lt;/p&gt;'; // Add to database $add_email = "INSERT INTO subscribers (email,date) VALUES ('$email',CURDATE())"; mysql_query($add_email) or die(mysql_error()); }else{ echo $error; } } ?&gt; &lt;!-- SAMPLE.PHP --&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Sample&lt;/title&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ // Email Signup $("form#newsletter").submit(function() { var dataStr = $("#newsletter").serialize(); alert(dataStr); $.ajax({ type: "POST", url: "process.php", data: dataStr, success: function(del){ $('form#newsletter').hide(); $('#signup-success').fadeIn(); } }); return false; }); }); &lt;/script&gt; &lt;style type="text/css"&gt; #email { margin-right:2px; padding:5px; width:145px; border-top:1px solid #ccc; border-left:1px solid #ccc; border-right:1px solid #eee; border-bottom:1px solid #eee; font-size:14px; color:#9e9e9e; } #signup-success { margin-bottom:20px; padding-bottom:10px; background:url(../img/css/divider-dots.gif) repeat-x 0 100%; display:none; } #signup-success p, #signup-success-nojs { padding:5px; background:#fff; border:1px solid #dedede; text-align:center; font-weight:bold; color:#3d7da5; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;?php include('process.php'); ?&gt; &lt;form id="newsletter" class="divider" name="newsletter" method="post" action=""&gt; &lt;fieldset&gt; &lt;input id="email" type="text" name="email" /&gt; &lt;input id="submit-button" type="image" src="&lt;?php echo $base_url; ?&gt;/assets/img/css/signup.gif" alt=" SIGNUP " /&gt; &lt;input id="submitted" type="hidden" name="submitted" value="true" /&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;div id="signup-success"&gt;&lt;p&gt;You have successfully subscribed!&lt;/p&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>Instead if using data: dataStr, use:</p> <pre><code>data : {param: value, param2: value2} </code></pre> <p>This is the proper way to do it for POST requests.</p> <p>Also, I recommend using a form plug-in, like <a href="http://malsup.com/jquery/form/" rel="nofollow noreferrer">this</a>.</p>
<p>check the response coming from the process.php file.echo and die the post values and alert the response because everything seams to be written correctly just matter of sending the post values to process.php. the syntax of Serialize could also be </p> <pre><code>jQuery('#newsletter').formSerialize(); </code></pre>
47,462
<p>Can Ruby really be used as a functional language? What are some good tutorials to teach this facet of the language? Note: I really want to use and stick with Ruby as my primary language so I am not interested at this point in being converted to YAFL (yet another functional language). I am really interested in how well Ruby's functional facets perform against the standard functional language baseline. Thanks.</p>
<p>Yes...sort of. Ruby lacks a reasonable construct to enforce immutability. (<code>Object#freeze</code> doesn't count) Immutability is really the cornerstone of functional languages. Further, Ruby's core libraries are highly oriented toward imperative design. Its <code>Array</code> and <code>Hash</code> classes are both mutable by nature, even <code>String</code> has methods which make non-immutable (e.g. <code>gsub!</code>). Ironically, Java is more "functional" than Ruby in this respect.</p> <p>With that said, it is possible to do functional-like programming in Ruby. Any time you use a block/proc/lambda, you are using a feature that comes from functional programming. Likewise, collection methods like <code>map</code> and <code>zip</code> are also higher-order constructs which find their roots in languages like Lisp, ML and Haskell.</p> <p>If you really want to do functional programming, you will want to use a language which is more geared toward that genre. Some suggestions:</p> <ul> <li><a href="http://clojure.org" rel="nofollow noreferrer"><strong>Clojure</strong></a> - Since you phrased the question using Ruby, I'm guessing you're of the dynamically typed persuasion. Clojure is like a strictly-functional Lisp that runs on the JVM.</li> <li><a href="http://research.microsoft.com/fsharp/fsharp.aspx" rel="nofollow noreferrer"><strong>F#</strong></a> - Basically OCaml on the CLR. Very nice, very clean</li> <li><a href="http://www.scala-lang.org" rel="nofollow noreferrer"><strong>Scala</strong></a> - Not a <em>strictly</em> functional language, but much better for it than Ruby</li> <li><a href="http://www.haskell.org/" rel="nofollow noreferrer"><strong>Haskell</strong></a> - Everybody's favorite!</li> </ul> <p>You'll notice that three of these four languages are statically typed. In fact, in the case of Scala and Haskell, these are <em>very</em> statically typed languages (much stronger type systems than, say, Java). I'm not sure why this is a trend in functional languages, but there you have it.</p>
<p>Take a look at <a href="http://www.haskell.org/" rel="nofollow noreferrer">Haskell</a>. It's a functional language that syntactically is very similar to Ruby.</p>
26,221
<p>What's a good program to record videos or screencasts being played on screen?</p>
<p>I've had success with Camtasia / CamStudio. Check out <a href="http://showmedo.com" rel="nofollow noreferrer">http://showmedo.com</a> for tutorials. It's a little recursive though - it would be better to capture it from source.</p>
<p>If you're using Vista the latest version of <a href="http://www.fraps.com/" rel="nofollow noreferrer">Fraps</a> might also do what you need. I haven't tried it for that, though, just games</p>
8,415
<p>I want to test a connection to a machine in my local intranet. I know the IP address. </p> <p>What port number should I use? 555? BTW: I'm using .NET.</p>
<p>You can use any but avoid the 'well known' port numbers </p> <p>More details on such ports <a href="http://www.webopedia.com/quick_ref/portnumbers.asp" rel="nofollow noreferrer">here</a>.</p>
<p>Anything above 1024 is good. </p> <p>The reason for that is that all the ports below are reserved for specific protocols or future use. </p>
16,542
<p>I have a (Wordpress powered) website, and Google is indexing some of the sub-directories. How can I stop Apache from showing users the directory listing? I know I can edit .htaccess to password-protect a directory, but I would prefer a 403 / custom redirect if possible.</p>
<p>You need this entry in your <code>.htaccess</code> file:</p> <pre>Options -Indexes</pre>
<p>Don't know much about Apache but you should do a 404 instead of a 403 if you can because a 403 tells someone that they may have found something interesting.</p>
22,349
<p>I have a .NET application distributed through <code>ClickOnce</code>. Security within the application is implemented through the <code>WindowsPrincipal.IsInRole(GroupName)</code> method using a set of groups as resources. This structure works well for us for users within the same domain as the groups. Unfortunately we now have users that need to use the application working on machines and using user accounts in a different domain that is trusted by our domain but is not in the same forest. </p> <p>It seems that <code>IsInRole()</code> queries the AD ticket on the local machine for group membership. Unfortunately this ticket only contains domain-local groups for the domain of the machine and global and universal groups of other trusted domains, our groups are domain-local groups in the first domain. The catch-22 situation comes from the fact that AD does not allow foreign security principals in either global or universal groups and therefore while it can be queried by the users in the second domain they cannot be members of it (making it a little pointless!)</p> <p>To explain: There are two domains: DOM1 and DOM2 with a trust setup between them, but they are not in the same forest.</p> <pre><code>DOM1\User1 DOM2\User2 </code></pre> <p>are two users.</p> <p>I would like to put both <code>User1</code> and <code>User2</code> in one group that is visible to both users and can contain them both.</p> <p>The only way I can currently see around it is the following (where {} denotes the members of the groups, DL=Domain Local and GLO=GlobalGroup.)</p> <p>Make two global groups one in each domain: </p> <pre><code>DOM1\GLOGroup1 : {DOM1\User1} DOM2\GLOGroup1 : {DOM2\User2} </code></pre> <p>and two domain-local groups containing the two global groups: </p> <pre><code>DOM1\DLGroup1 : {DOM1\GLOGroup1, DOM2\GLOGroup1} DOM2\DLGroup1 : {DOM1\GLOGroup1, DOM2\GLOGroup1} </code></pre> <p>But this isn't really acceptable as we actually have more than two domains and about 70 groups to administer including a hierarchy of groups and we don't have much direct control over the administration of groups in the other domains.</p> <p>We haven't yet worked through any thinking on an approach using LDAP but from the little that I've read I believe it's not generally recommended for this purpose?</p>
<p>you might try using LDAP instead, but you'll have to know which LDAP server to query; see <a href="https://stackoverflow.com/questions/290548/c-validate-a-username-and-password-against-active-directory#290599">this answer</a> for sample code</p>
<p>shouldnt it be a universal group to allow users from multiple trusted domains?</p> <p>The user account you are checking the AD with also needs to be able to read each of the ad group ou's.</p> <p>Mauro</p>
37,877
<p>I'm using Lucene.net, but I am tagging this question for both .NET and Java versions because the API is the same and I'm hoping there are solutions on both platforms.</p> <p>I'm sure other people have addressed this issue, but I haven't been able to find any good discussions or examples. </p> <p>By default, Lucene is very picky about query syntax. For example, I just got the following error:</p> <pre><code>[ParseException: Cannot parse 'hi there!': Encountered "&lt;EOF&gt;" at line 1, column 9. Was expecting one of: "(" ... "*" ... &lt;QUOTED&gt; ... &lt;TERM&gt; ... &lt;PREFIXTERM&gt; ... &lt;WILDTERM&gt; ... "[" ... "{" ... &lt;NUMBER&gt; ... ] Lucene.Net.QueryParsers.QueryParser.Parse(String query) +239 </code></pre> <p>What is the best way to prevent ParseExceptions when processing queries from users? It seems to me that the most <em>usable</em> search interface is one that always executes a query, even if it might be the wrong query. </p> <p>It seems that there are a few possible, and complementary, strategies:</p> <ul> <li>"Clean" the query prior to sending it to the QueryProcessor</li> <li>Handle exceptions gracefully <ul> <li>Show an intelligent error message to the user</li> <li>Perhaps execute a simpler query, leaving off the erroneous bit</li> </ul></li> </ul> <p>I don't really have any great ideas about how to do any of those strategies. Has anyone else addressed this issue? Are there any "simple" or "graceful" parsers that I don't know about?</p>
<p>Yo can make Lucene ignore the special characters by sanitizing the query with something like</p> <pre><code>query = QueryParser.Escape(query) </code></pre> <p>If you do not want your users to ever use advanced syntax in their queries, you can do this always. </p> <p>If you want your users to use advanced syntax but you also want to be more forgiving with the mistakes you should only sanitize after a ParseException has occured.</p>
<p>I'm in the same situation as you.</p> <p>Here's what I do. I do catch the exception, but only so that I can make the error look prettier. I don't change the text.</p> <p>I also provide a link to an explanation of the Lucene syntax which I have simplified a little bit:<br> <a href="http://ifdefined.com/btnet/lucene_syntax.html" rel="nofollow noreferrer">http://ifdefined.com/btnet/lucene_syntax.html</a></p>
32,931
<p>What is the Reuse/Release Equivalence Principle and why is it important?</p>
<p>The Reuse/Release Equivalence Principle (REP) says:</p> <blockquote> <p>The unit of reuse is the unit of release. Effective reuse requires tracking of releases from a change control system. The package is the effective unit of reuse and release.</p> </blockquote> <p><b>The unit of reuse is the unit of release</b></p> <p>Code should not be reused by copying it from one class and pasting it into another. If the original author fixes any bugs in the code, or adds any features, you will not automatically get the benefit. You will have to find out what's changed, then alter your copy. Your code and the original code will gradually diverge.</p> <p>Instead, code should be reused by including a released library in your code. The original author retains responsibility for maintaining it; you should not even need to see the source code.</p> <p><b>Effective reuse requires tracking of releases from a change control system</b></p> <p>The author of a library needs to identify releases with numbers or names of some sort. This allows users of the library to identify different versions. This requires the use of some kind of release tracking system.</p> <p><b>The package is the effective unit of reuse and release</b></p> <p>It might be possible to use a class as the unit of reuse and release, however there are so many classes in a typical application, it would be burdensome for the release tracking system to keep track of them all. A larger-scale entity is required, and the package fits this need well.</p> <p>See also Robert Martin's article on <a href="https://web.archive.org/web/20030614000424/http://objectmentor.com/resources/articles/granularity.pdf" rel="nofollow noreferrer">Granularity</a>.</p>
<p>From Clean Architecture, by Robert Martin.</p> <blockquote> <p>The Reuse/Release Equivalence Principle (REP) is a principle that seems obvious, at least in hindsight. People who want to reuse software components cannot, and will not, do so unless those components are tracked through a release process and are given release numbers.</p> <p>This is not simply because, without release numbers, there would be no way to ensure that all the reused components are compatible with each other. Rather, it also reflects the fact that software developers need to know when new releases are coming, and which changes those new releases will bring.</p> <p>It is not uncommon for developers to be alerted about a new release and decide, based on the changes made in that release, to continue to use the old release instead. Therefore the release process must produce the appropriate notifications and release documentation so that users can make informed decisions about when and whether to integrate the new release.</p> </blockquote>
8,869
<p>I recently got an Ender 3 Pro for my birthday, and I am having some problems with elephant's foot (as the title suggests). I have tried several fixes; lowering the print speed, changing the print micron size (quality) in my slicer, and I have also tried the masking tape trick (it definitely does not work). I want to know if there are any other ways to prevent elephant's foot on my prints. I first noticed it on a game-cartridge holder. It was four and a half millimeters thick on the bottom. I think that it could be an issue with the design, but I'm not entirely sure. I can send the specs for the design if you want to look at them.</p>
<p>Elephant's foot can be caused by different causes.</p> <ul> <li>Incorrect leveling or incorrect nozzle to bed distance<br><a href="https://3dprinting.stackexchange.com/a/15993/">This answer</a> describes that it can be caused by a too low nozzle to bed distance.</li> <li>Bed temperature<br>A too high bed temperature and weight of the print can cause bulging out of the bottom layers. This also frequently occurs as the result of an uncooled/too less cooled first layer.</li> </ul> <p>Improved cooling, lowering bed temperature or adjusting nozzle to bed distance and proper leveling are the most obvious solutions to fight this problem. Other solution can be found in using chamfers on the bottom of the print (requires modifying the model) or printing on a raft, this latter solution does lead to losing the nice bottom layer finish.</p>
<p>Elephant foot on an FDM machine is typically caused by more material (filament) being present in that layer than it has space for.</p> <p>The most common cause of this is your z-zero is too low, so for the first layer the nozzle starts too close to the bed and the filament gets &quot;squeezed&quot; laterally. You can try adjusting your z-zero or z-stop to allow slightly more space, fractions of a millimeter, between the nozzle and bed for your first layer.</p> <p>If you don't want to try that, or you'd like to try a different solution first, consider printing the part on a raft so that it starts raised up off the bed and away from that elephant-footing.</p> <p>There are a handful of other potential causes and factors which can make this better or worse, things like having a large footprint on the bed, but I hope the above is a quick and easy place to start.</p>
1,908
<p>I have a hidden DIV which contains a toolbar-like menu.</p> <p>I have a number of DIVs which are enabled to show the menu DIV when the mouse hovers over them.</p> <p>Is there a built-in function which will move the menu DIV to the top right of the active (mouse hover) DIV? I'm looking for something like <code>$(menu).position("topright", targetEl);</code></p>
<p><strong>tl;dr:</strong> (try it <a href="http://jsfiddle.net/wjbuys/QrrpB/" rel="noreferrer">here</a>)</p> <p>If you have the following HTML:</p> <pre><code>&lt;div id="menu" style="display: none;"&gt; &lt;!-- menu stuff in here --&gt; &lt;ul&gt;&lt;li&gt;Menu item&lt;/li&gt;&lt;/ul&gt; &lt;/div&gt; &lt;div class="parent"&gt;Hover over me to show the menu here&lt;/div&gt; </code></pre> <p>then you can use the following JavaScript code:</p> <pre><code>$(".parent").mouseover(function() { // .position() uses position relative to the offset parent, var pos = $(this).position(); // .outerWidth() takes into account border and padding. var width = $(this).outerWidth(); //show the menu directly over the placeholder $("#menu").css({ position: "absolute", top: pos.top + "px", left: (pos.left + width) + "px" }).show(); }); </code></pre> <p><strong>But it doesn't work!</strong></p> <p>This will work as long as the menu and the placeholder have the same offset parent. If they don't, and you don't have nested CSS rules that care where in the DOM the <code>#menu</code> element is, use:</p> <pre><code>$(this).append($("#menu")); </code></pre> <p>just before the line that positions the <code>#menu</code> element.</p> <p><strong>But it still doesn't work!</strong></p> <p>You might have some weird layout that doesn't work with this approach. In that case, just use <a href="http://jqueryui.com/demos/position/" rel="noreferrer">jQuery.ui's position plugin</a> (as mentioned in an <a href="https://stackoverflow.com/a/2781557/22107">answer</a> below), which handles every conceivable eventuality. Note that you'll have to <code>show()</code> the menu element before calling <code>position({...})</code>; the plugin can't position hidden elements.</p> <p><strong>Update notes 3 years later in 2012:</strong></p> <p>(The original solution is archived <a href="http://jsfiddle.net/wjbuys/LCt7z/" rel="noreferrer">here</a> for posterity)</p> <p>So, it turns out that the original method I had here was far from ideal. In particular, it would fail if:</p> <ul> <li>the menu's offset parent is not the placeholder's offset parent</li> <li>the placeholder has a border/padding</li> </ul> <p>Luckily, jQuery introduced methods (<code>position()</code> and <code>outerWidth()</code>) way back in 1.2.6 that make finding the right values in the latter case here a lot easier. For the former case, <code>append</code>ing the menu element to the placeholder works (but will break CSS rules based on nesting).</p>
<p>Something like this?</p> <pre><code>$(menu).css("top", targetE1.y + "px"); $(menu).css("left", targetE1.x - widthOfMenu + "px"); </code></pre>
19,108
<p><a href="https://stackoverflow.com/questions/32230/tracking-down-where-disk-space-has-gone-on-linux">In this question</a> someone asked for ways to display disk usage in Linux. I'd like to take this one step further down the cli-path... how about a shell script that takes the output from something like a reasonable answer to the previous question and generates a graph/chart from it (output in a png file or something)? This may be a bit too much code to ask for in a regular question, but my guess is that someone already has a oneliner laying around somewhere...</p>
<p>I would recommend <a href="http://munin.projects.linpro.no/" rel="nofollow noreferrer">munin</a>. It is designed for exactly this sort of thing - graphing CPU usage, memory usage, disc-usage and such. sort of like MRTG (but MRTG is primarily aimed at graphing router's traffic, graphing anything but bandwidth with it is very hackish)</p> <p>Writing Munin plugins is very easy (it was one of the projects goals). They can be written in almost anything (shell script, perl/python/ruby/etc, C, anything that can be execute and produce an output). The plugin output format is basically <code>disc1usage.value 1234</code>. And debugging the plugins is very easy (compared to MRTG)</p> <p>I've set it up on my laptop to monitor disc-usage, bandwidth usage (by pulling data from my ISP's control panel, it graphs my two download "bins", uploads and newsgroup usage), load average and number of processes. Once I got it installed (currently slightly difficult on OS X, but it's trivial on Linux/FreeBSD), I had written a plugin in a few minutes, and it worked, first time!</p> <p>I would describe how it's setup, but the munin site will do that far better than I could!</p> <p>There's an example installation <a href="http://munin.ping.uio.no/" rel="nofollow noreferrer">here</a></p> <p>Some alternatives are nagios and cacti. You could also write something similar using rrdtool. Munin, MRTG and Cacti are basically all far-nicer-to-use systems based around this graphing tool.</p> <p>If you want something really, really simple, you could do..</p> <pre><code>import os import time while True: disc_usage = os.system("df -h / | awk '{print $3}'") log = open("mylog.txt") log.write(disc_usage + "\n") log.close() time.sleep(60*5) </code></pre> <p>Then..</p> <pre><code>f = open("mylog.txt") lines = f.readlines() # Convert each line to a float number lines = [float(cur_line) for cur_line in lines] # Get the biggest and smallest biggest = max(lines) smallest = min(lines) for cur_line in lines: base = (cur_line - smallest) + 1 # make lowest value 1 normalised = base / (biggest - smallest) # normalise value between 0 and 1 line_length = int(round(normalised * 28)) # make a graph between 0 and 28 characters wide print "#" * line_length </code></pre> <p>That'll make a simple ascii graph of the disc usage. I <em>really really</em> don't recommend you use something like this. Why? The log file will get bigger, and bigger, and bigger. The graph will get progressively slower to graph. RRDTool uses a rolling-database system to store it's data, so the file will never get bigger than about 50-100KB, and it's consistently quick to graph as the file is a fixed length.</p> <p>In short. If you want something to easily graph almost anything, use <a href="http://munin.projects.linpro.no/" rel="nofollow noreferrer">munin</a>. If you want something smaller and self-contained, write something with RRDTool.</p>
<p>I guess there are a couple of options:</p> <ol> <li><p>For a pure CLI solution, use something like gnuplot. See <a href="http://t16web.lanl.gov/Kawano/gnuplot/intro/working-e.html" rel="nofollow noreferrer">here</a> for example usage. I haven't used gnuplot since my student days :-)</p></li> <li><p>Not really a pure CLI solution, but download something like <a href="http://www.jfree.org/jfreechart/" rel="nofollow noreferrer">JFreeChart</a> and write a simple Java app that reads stdin and creates your chart.</p></li> </ol> <p>Hope this helps.</p>
6,202
<p>I'm using jQuery to wire up some mouseover effects on elements that are inside an UpdatePanel. The events are bound in <code>$(document).ready</code> . For example:</p> <pre><code>$(function() { $('div._Foo').bind("mouseover", function(e) { // Do something exciting }); }); </code></pre> <p>Of course, this works fine the first time the page is loaded, but when the UpdatePanel does a partial page update, it's not run and the mouseover effects don't work any more inside the UpdatePanel. </p> <p>What's the recommended approach for wiring stuff up in jQuery not only on the first page load, but every time an UpdatePanel fires a partial page update? Should I be using the ASP.NET ajax lifecycle instead of <code>$(document).ready</code>?</p>
<p>An UpdatePanel completely replaces the contents of the update panel on an update. This means that those events you subscribed to are no longer subscribed because there are new elements in that update panel.</p> <p>What I've done to work around this is re-subscribe to the events I need after every update. I use <code>$(document).ready()</code> for the initial load, then use Microsoft's <a href="https://learn.microsoft.com/en-us/previous-versions/bb311028%28v%3dvs.140%29" rel="noreferrer"><code>PageRequestManager</code></a> (available if you have an update panel on your page) to re-subscribe every update. </p> <pre><code>$(document).ready(function() { // bind your jQuery events here initially }); var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(function() { // re-bind your jQuery events here }); </code></pre> <p>The <code>PageRequestManager</code> is a javascript object which is automatically available if an update panel is on the page. You shouldn't need to do anything other than the code above in order to use it as long as the UpdatePanel is on the page.</p> <p>If you need more detailed control, this event passes arguments similar to how .NET events are passed arguments <code>(sender, eventArgs)</code> so you can see what raised the event and only re-bind if needed.</p> <p>Here is the latest version of the documentation from Microsoft: <a href="http://msdn.microsoft.com/en-us/library/bb383810.aspx" rel="noreferrer">msdn.microsoft.com/.../bb383810.aspx</a></p> <hr> <p>A better option you may have, depending on your needs, is to use jQuery's <a href="http://api.jquery.com/on/" rel="noreferrer"><code>.on()</code></a>. These method are more efficient than re-subscribing to DOM elements on every update. Read all of the documentation before you use this approach however, since it may or may not meet your needs. There are a lot of jQuery plugins that would be unreasonable to refactor to use <code>.delegate()</code> or <code>.on()</code>, so in those cases, you're better off re-subscribing.</p>
<p>In response to Brian MacKay's answer:</p> <p>I inject the JavaScript into my page via the ScriptManager instead of putting it directly into the HTML of the UserControl. In my case, I need to scroll to a form that is made visible after the UpdatePanel has finished and returned. This goes in the code behind file. In my sample, I've already created the <strong>prm</strong> variable on the main content page.</p> <pre><code>private void ShowForm(bool pShowForm) { //other code here... if (pShowForm) { FocusOnControl(GetFocusOnFormScript(yourControl.ClientID), yourControl.ClientID); } } private void FocusOnControl(string pScript, string pControlId) { ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "focusControl_" + pControlId, pScript, true); } /// &lt;summary&gt; /// Scrolls to the form that is made visible /// &lt;/summary&gt; /// &lt;param name="pControlId"&gt;The ClientID of the control to focus on after the form is made visible&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; private string GetFocusOnFormScript(string pControlId) { string script = @" function FocusOnForm() { var scrollToForm = $('#" + pControlId + @"').offset().top; $('html, body').animate({ scrollTop: scrollToForm}, 'slow' ); /* This removes the event from the PageRequestManager immediately after the desired functionality is completed so that multiple events are not added */ prm.remove_endRequest(ScrollFocusToFormCaller); } prm.add_endRequest(ScrollFocusToFormCaller); function ScrollFocusToFormCaller(sender, args) { if (args.get_error() == undefined) { FocusOnForm(); } }"; return script; } </code></pre>
31,967
<p>We have a makefile that is built last in our build process using Visual Studio to launch our unit tests. Unfortunately if the build fails the makefile is still processed and we have extra (annoying) errors. Any way to prevent that?</p> <p>Example Project A : build dummy.exe Project B (makefile) : build command is : run dummy.exe /unittest</p> <p>We want Project B to skip its build command when Project A has build errors. Thanks!</p>
<p>Set Project B (your makefile project) to be dependant on Project A. This way Project B will always try to build Project A before it builds.</p>
<p>Go to Project Properties. I assume you already have something in the "Post-Build event command line" box? There is a "Run the post-build event" combobox, set it to "On successful build".</p> <p>Is that what you're looking for?</p>
20,213
<p>There's a web services I want to call in my application, I can use it with importing the WSDL or by just use "HTTP GET" with the URL and parameters, so I prefer the later because it's simple thing.</p> <p>I know I can use indy idhttp.get, to do the job, but this is very simple thing and I don't want to add complex indy code to my application.</p> <p><strong>UPDATE</strong>: sorry if I was not clear, I meant by "not to add complex indy code", that I don't want add indy components for just this simple task, and prefer more lighter way for that.</p>
<p>You could use the <a href="http://msdn.microsoft.com/en-us/library/aa383630(VS.85).aspx" rel="noreferrer">WinINet API</a> like this:</p> <pre><code>uses WinInet; function GetUrlContent(const Url: string): string; var NetHandle: HINTERNET; UrlHandle: HINTERNET; Buffer: array[0..1024] of Char; BytesRead: dWord; begin Result := ''; NetHandle := InternetOpen('Delphi 5.x', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0); if Assigned(NetHandle) then begin UrlHandle := InternetOpenUrl(NetHandle, PChar(Url), nil, 0, INTERNET_FLAG_RELOAD, 0); if Assigned(UrlHandle) then { UrlHandle valid? Proceed with download } begin FillChar(Buffer, SizeOf(Buffer), 0); repeat Result := Result + Buffer; FillChar(Buffer, SizeOf(Buffer), 0); InternetReadFile(UrlHandle, @Buffer, SizeOf(Buffer), BytesRead); until BytesRead = 0; InternetCloseHandle(UrlHandle); end else { UrlHandle is not valid. Raise an exception. } raise Exception.CreateFmt('Cannot open URL %s', [Url]); InternetCloseHandle(NetHandle); end else { NetHandle is not valid. Raise an exception } raise Exception.Create('Unable to initialize Wininet'); end; </code></pre> <p>source: <a href="http://www.scalabium.com/faq/dct0080.htm" rel="noreferrer">http://www.scalabium.com/faq/dct0080.htm</a></p> <p>The WinINet API uses the same stuff InternetExplorer is using so you also get any connection and proxy settings set by InternetExplorer for free.</p>
<p>If your application is Windows-only, I would suggest using WinSock. It's simple enough, allows to execute any HTTP request, can work both synchronously and asynchronously (using non-blocking WSASend/WSARecv with callbacks or good old send/recv in a dedicated thread).</p>
38,695
<p>I am trying to print a model that requires support material to be on the first layer, what is the best way to accomplish this? I am currently using Cura. It seems that the support material is too flaky. I have the infill for the support at around 8%</p>
<p>I had the same problem printing a miniature just recently. As always, settings are somewhat dependent from the object you want to print, but here are some suggestions:</p> <ul> <li>Increase the support density: 15% (8% is very low!)</li> <li>Support pattern: zig-zag with "connect zig-zag" option enabled (add stiffness to the "column" of support)</li> <li>Enable support interface (increase adhesion to the plate, and provide a more "beefy" base for the support material)</li> </ul> <p>For reference, here's a screenshot of my settings as I tweaked them for that miniature (printed a 0.1mm layer height).</p> <p><a href="https://i.stack.imgur.com/WNjki.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WNjki.png" alt="complete support settings"></a></p> <p>("Support line distance 1mm" is the same as "Support density 15%", or at least it is the same with my nozzle size)</p> <p>If your problem was not only with the "flakiness" of the material, but also with it adhesion to the bed, then prepping your printing bed somehow (with a bit of painter tape, glue, etc... can help. Alternatively using a brim or a raft (as also suggested by another responder) could also help.</p> <p><strong>EDIT</strong>: all the above still standing true, it turns out the OP had a hardware problem as well, his timing belt being loose (see comments).</p>
<p>I cannot comment on your infill percentage for supports, since I never use them. In any case, increasing the infill may well have little or no effect.</p> <p>However, you could try two things: If your slicer includes supports when generating brims, then use brims. Otherwise, use a raft.</p>
796
<p>At work we have an application to play 2K (2048*1556px) OpenEXR film sequences. It works well.. apart from when sequences that are over 3GB (quite common), then it has to unload old frames from memory, despite the fact all machines have 8-16GB of memory (which is addressable via the linux BIGMEM stuff).</p> <p>The frames have to he cached into memory to play back in realtime. The OS is a several-year old 32-bit Fedora Distro (not possible to upgradable to 64bit, for the foreseeable future). The per-process limitation is 3GB per process.</p> <p>Basically, is it possible to cache more than 3GB of data in memory, somehow? My initial idea was to spread the data between multiple processes, but I've no idea if this is possible..</p>
<p>How about creating a RAM drive and loading the file into that ... assuming the RAM drive supports the BIGMEM stuff for you.</p> <p>You could use multiple processes: each process loads a view of the file as a shared memory segment, and the player process then maps the segments in turn as needed.</p>
<p>@dbr said:</p> <blockquote> <p>There is a review machine with an absurd fiber-channel-RAID-array that can play 2K files direct from the array easily. The issue is with the artist-workstations, so it wouldn't be one $4000 RAID array, it'd be hundreds..</p> </blockquote> <p>Well, if you can accept a limit of ~30GB, then maybe a single 36GB SSD drive would be enough? Those go for ~US$1k each I think, and the data rates might be enough. That very well maybe cheaper than a pure RAM approach. There are smaller sizes available, too. If ~60GB is enough you could probably get away with a JBOD array of 2 for double the cost, and skip the RAID controller. Be sure only to look at the higher end SSD options--the low end is filled with glorified memory sticks. :P</p>
6,298
<p>I've installed Subversion on Ubuntu following the guide <em><a href="http://alephzarro.com/blog/2007/01/07/installation-of-subversion-on-ubuntu-with-apache-ssl-and-basicauth" rel="nofollow noreferrer">Installation of Subversion on Ubuntu, with Apache, SSL, and BasicAuth.</a></em>.</p> <p>It works, and I was able commit and create different repositories, but somehow, from time to time (sometimes minutes), when trying to do a commit, I'm forced to reset or recreate my user and password with the following command.</p> <pre><code>htpasswd2 -c -m /etc/apache2/dav_svn.passwd $AUTH_USER </code></pre> <p>Because SVN does not recognize my user/password anymore. </p> <p>I'm using TortoiseSVN as SVN Client. I would like to know why this is happening. Maybe it's a configuration issue, or maybe TortoiseSVN is sending invalid credentials, causing a locked account. Since I'm far from being an SVN expert/administrator. Are there some pointers in order to attack the problem.</p>
<p>Check if your password-file actually has changed. Do a</p> <p><code>md5 /etc/apache2/dav_svn.passwd</code> or <code>cat /etc/apache2/dav_svn.passwd</code></p> <p>when it works, and after it stops working. If it changes, you've gotta figure out why (automatic update from a cronjob? some website/admin tool changing it for you?)</p> <p>Note that subversion + apache does <em>not</em> change this file in any way if you're using any form of default setup.</p> <p>I also hope that you replace $AUTH_USER with your proper username ;-) (or at least have exported the variable).</p> <p>If the file hasn't changed, then it's something else. See if there's anything in the apache error log.</p> <p>A few other possibilities:</p> <ul> <li>Try disabling https (for testing - since you probably don't have a valid certificate).</li> <li>Check your .subversion/auth folder; I'm not sure about tortoisesvn, but I believe it stores credential information there (just like vanilla svn).</li> <li>Not likely, but instead of recreating your user see if <code>touch /etc/apache2/dav_svn.passwd</code> will do the trick.</li> <li>Is the file writable by anyone but root? If so, <code>chmod 644 /etc/apache2/dav_svn.passwd</code></li> </ul>
<p>I'm using TortoiseSVN as well, but on Windows users' passwords are managed by <a href="http://en.wikipedia.org/wiki/Active_Directory" rel="nofollow noreferrer">Active Directory</a> on the network domain. So usernames are in the format <code>&lt;domain&gt;\&lt;user&gt;</code>. And from time to time (weeks), I need to reset the password; it seems like the password is changed. I just do not know why. </p>
36,343
<p>I'm looking for a way to set the default language for visitors comming to a site built in EPiServer for the first time. Not just administrators/editors in the backend, people comming to the public site.</p>
<p>Depends on your setup.</p> <p>If the site languages is to change under different domains you can do this. Add to configuration -> configSections nodes in web.config:</p> <pre><code>&lt;sectionGroup name="episerver"&gt; &lt;section name="domainLanguageMappings" allowDefinition="MachineToApplication" allowLocation="false" type="EPiServer.Util.DomainLanguageConfigurationHandler,EPiServer" /&gt; </code></pre> <p>..and add this to episerver node in web.config:</p> <pre><code> &lt;domainLanguageMappings&gt; &lt;map domain="site.com" language="EN" /&gt; &lt;map domain="site.se" language="SV" /&gt; &lt;/domainLanguageMappings&gt; </code></pre> <p>Otherwhise you can do something like this. Add to appSettings in web.config:</p> <pre><code>&lt;add name="EPsDefaultLanguageBranch" key="EN"/&gt; </code></pre>
<p>I have this on EPiServer CMS5:</p> <pre><code>&lt;globalization culture="sv-SE" uiCulture="sv" requestEncoding="utf-8" responseEncoding="utf-8" resourceProviderFactoryType="EPiServer.Resources.XmlResourceProviderFactory, EPiServer" /&gt; </code></pre>
15,292
<p>I wrote small Python+Ajax programs (listed at the end) with socket module to study the COMET concept of asynchronous communications.<br/></p> <p>The idea is to allow browsers to send messages real time each others via my python program.<br/></p> <p>The trick is to let the "GET messages/..." connection opened waiting for a message to answer back.<br/></p> <p>My problem is mainly on the reliability of what I have via socket.recv...<br/></p> <p>When I POST from Firefox, it is working well.<br/></p> <p>When I POST from Chrome or IE, the "data" I get in Python is empty.</p> <p>Does anybody know about this problem between browsers?<br/></p> <p>Are some browsers injecting some EOF or else characters killing the receiving of "recv"?<br/></p> <p>Is there any solution known to this problem?</p> <p>The server.py in Python:</p> <pre><code> import socket connected={} def inRequest(text): content='' if text[0:3]=='GET': method='GET' else: method='POST' k=len(text)-1 while k&gt;0 and text[k]!='\n' and text[k]!='\r': k=k-1 content=text[k+1:] text=text[text.index(' ')+1:] url=text[:text.index(' ')] return {"method":method,"url":url,"content":content} mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.bind ( ( '', 80 ) ) mySocket.listen ( 10 ) while True: channel, details = mySocket.accept() data=channel.recv(4096) req=inRequest(data) url=req["url"] if url=="/client.html" or url=="/clientIE.html": f=open('C:\\async\\'+url) channel.send ('HTTP/1.1 200 OK\n\n'+f.read()) f.close() channel.close() elif '/messages' in url: if req["method"]=='POST': target=url[10:] if target in connected: connected[target].send("HTTP/1.1 200 OK\n\n"+req["content"]) print req["content"]+" sent to "+target connected[target].close() channel.close() elif req["method"]=='GET': user=url[10:] connected[user]=channel print user+' is connected' </code></pre> <p>The client.html in HTML+Javascript:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; var user='' function post(el) { if (window.XMLHttpRequest) { var text=el.value; var req=new XMLHttpRequest(); el.value=''; var target=document.getElementById('to').value } else if (window.ActiveXObject) { var text=el.content; var req=new ActiveXObject("Microsoft.XMLHTTP"); el.content=''; } else return; req.open('POST','messages/'+target,true) req.send(text); } function get(u) { if (user=='') user=u.value var req=new XMLHttpRequest() req.open('GET','messages/'+user,true) req.onload=function() { var message=document.createElement('p'); message.innerHTML=req.responseText; document.getElementById('messages').appendChild(message); get(user); } req.send(null) } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;span&gt;From&lt;/span&gt; &lt;input id="user"/&gt; &lt;input type="button" value="sign in" onclick="get(document.getElementById('user'))"/&gt; &lt;span&gt;To&lt;/span&gt; &lt;input id="to"/&gt; &lt;span&gt;:&lt;/span&gt; &lt;input id="message"/&gt; &lt;input type="button" value="post" onclick="post(document.getElementById('message'))"/&gt; &lt;div id="messages"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>The problem you have is that</p> <ul> <li>your tcp socket handling isn't reading as much as it should</li> <li>your http handling is not complete</li> </ul> <p>I recommend the following lectures:</p> <ul> <li><a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html" rel="nofollow noreferrer">rfc2616</a></li> <li><a href="http://www.kohala.com/start/unpv12e.html" rel="nofollow noreferrer">The sockets Networking API</a> by Stevens</li> </ul> <p>See the example below for a working http server that can process posts</p> <pre><code>index = ''' &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="/" method="POST"&gt; &lt;textarea name="foo"&gt;&lt;/textarea&gt; &lt;button type="submit"&gt;post&lt;/button&gt; &lt;/form&gt; &lt;h3&gt;data posted&lt;/h3&gt; &lt;div&gt; %s &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; ''' bufsize = 4048 import socket import re from urlparse import urlparse class Headers(object): def __init__(self, headers): self.__dict__.update(headers) def __getitem__(self, name): return getattr(self, name) def get(self, name, default=None): return getattr(self, name, default) class Request(object): header_re = re.compile(r'([a-zA-Z-]+):? ([^\r]+)', re.M) def __init__(self, sock): header_off = -1 data = '' while header_off == -1: data += sock.recv(bufsize) header_off = data.find('\r\n\r\n') header_string = data[:header_off] self.content = data[header_off+4:] lines = self.header_re.findall(header_string) self.method, path = lines.pop(0) path, protocol = path.split(' ') self.headers = Headers( (name.lower().replace('-', '_'), value) for name, value in lines ) if self.method in ['POST', 'PUT']: content_length = int(self.headers.get('content_length', 0)) while len(self.content) &lt; content_length: self.content += sock.recv(bufsize) self.query = urlparse(path)[4] acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM) acceptor.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1, ) acceptor.bind(('', 2501 )) acceptor.listen(10) if __name__ == '__main__': while True: sock, info = acceptor.accept() request = Request(sock) sock.send('HTTP/1.1 200 OK\n\n' + (index % request.content) ) sock.close() </code></pre>
<p>I would recommend using a JS/Ajax library on the client-side just to eliminate the possibility of cross-browser issues with your code. For the same reason I would recommend using a python http server library like <a href="http://docs.python.org/library/simplehttpserver.html" rel="nofollow noreferrer">SimpleHTTPServer</a> or something from <a href="http://twistedmatrix.com/trac/wiki/Documentation" rel="nofollow noreferrer">Twisted</a> if the former does not allow low-level control.</p> <p>Another idea - use something like Wireshark to check what's been sent by the browsers.</p>
20,220
<p>I have a web application that is able to open an excel template, push data into a worksheet and send the file to a user. When the file is opened a VBA Macro will refresh a pivot table based on the data that was pushed into the template.</p> <p>The user receives the standard File Open / Save dialog. </p> <p>In Internet Explorer (version 6), if the user chooses to save the file, when the file is opened the VBA code runs as expected, however if the user chooses 'Open' then the VBA fails with:</p> <p>Run-Time error 1004: Cannot open Pivot Table source file.</p> <p>In all other browsers both open and save work as expected.</p> <p>It is not in my power to upgrade to a newer version of IE (corporate bureaucracy); Is there anything Ican do to allow the users to open without first saving? </p>
<p>Newer versions of Excel really don't like running macros automatically. If you really want to generate an Excel file and send that to your users, build the full file on the server using the COM interface to Excel, or some libraries that can read/write XLS files, and then send the completed file.</p>
<p>The option to open or save is a browser selection item, as far as I know it is not possible to override this behavior.</p>
11,131
<p>I'm /relatively/ new to 3d printing (I'm getting pretty good prints from my Wanhao di3 plus, but haven't done any DIY kits or anything) and materials engineering is probably the furthest thing from my area of expertise so I thought I would pose this to more experienced makers:</p> <p>If I'm building a large scale printer (probably a similar size to substation33 - sub33D's 1200x1200 printer) that I'm only going to print in PLA and MAYBE ABS occasionally, can I substitute the heated bed for simply heating the entire enclosure? The idea would be to have a thermistor measuring the ambient air temp inside the enclosure with a heat gun or two to hear the entire enclosure as necessary. I want to do this to try and reduce the cost (significantly as far as I can tell) as it seems 400*400 silicone heat pads tend to go for about 80 bucks a pop. An alternate idea I had was to use two or three heat pads and space them evenly under a glass bed, although I feel that this won't work as well because the heating won't be homogenous...</p> <p>Any input is appreciated :)</p>
<p>With a well-insulated and well distributed (or perhaps well-mixed is a better term - even heating) enclosure you should have a veritable heated bed by dint of heating the enclosure (with the bed in it), unless the bed needs to be hotter than the enclosure. I think that would be bit more elaborate than "a couple of heat guns" and involve several fans to distribute and mix air continuously.</p> <p>But - heated enclosures are not a freebie - everything inside the heated enclosure needs to be happy running at the sort of temperatures the enclosure is running at, and that can be hard on some electronic parts, shortening their lifetimes at least. Likewise, your calibration needs to be done on the hot enclosure - mechanical parts (particularly on a large scale printer) will change size due to the temperature.</p> <p>Insulation will both reduce your running cost (the more heat you keep, the less you have to add) and help keep the temperatures even, by slowing the cooling at the edges of the enclosure.</p>
<p>If it is yours first DIY 3D printer try building smaller version first with just one silicone heat pad. 400^2 mm^2 is good enough.</p> <p>From my experience:</p> <ol> <li><p>I used 500W silicon heater with SSR (AC mains) and it heats as fast as hotend (on DC 12V).</p></li> <li><p>I also recommend tooling plate (CNC machined Aluminum plate), it is better for heat transmission (Al) and it is more flat (machined to +-50um).</p></li> <li><p>You might consider thermal insulation under the silicone heater and also some foil on build plate itself - to minimize thermal losses. Cork might be useful for bottom. For top I use blue foil (in which it was originally wrapped).</p></li> </ol> <p>Enclosure I think it is also necessary, combined with heater, but then you must also have tubes for cooling of printed part, motors, fridge on hot end, etc.</p> <p>Word of caution: You must realize that you will be probably using 1.0mm nozzle or even more, since on 1200x1200mm you will just wait for weeks for part to complete. For reference: I print on 340mm diameter (delta) with 0.3mm nozzle and works just fine. But if I use just 0.1mm instead of 0.2mm layers it takes more time, but at the end it looks fantastic. So in your case even layer height must be big to reduce printing time. So you can increase speed, but then there could emerge some artifacts on printed object and also consider heater on hot end, which might be lagging behind.</p> <p>There are a lot of problems when you go this big and all are not even closely to be considered solved, but if you have time..</p>
672
<p>I ran into the problem that my primary key sequence is not in sync with my table rows. </p> <p>That is, when I insert a new row I get a duplicate key error because the sequence implied in the serial datatype returns a number that already exists.</p> <p>It seems to be caused by import/restores not maintaining the sequence properly.</p>
<pre><code>-- Login to psql and run the following -- What is the result? SELECT MAX(id) FROM your_table; -- Then run... -- This should be higher than the last result. SELECT nextval('your_table_id_seq'); -- If it's not higher... run this set the sequence last to your highest id. -- (wise to run a quick pg_dump first...) BEGIN; -- protect against concurrent inserts while you update the counter LOCK TABLE your_table IN EXCLUSIVE MODE; -- Update the sequence SELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false); COMMIT; </code></pre> <p><a href="http://www.ruby-forum.com/topic/64428#72333" rel="noreferrer">Source - Ruby Forum</a></p>
<p><code>SELECT setval...</code> makes JDBC bork, so here's a Java-compatible way of doing this:</p> <pre><code>-- work around JDBC 'A result was returned when none was expected.' -- fix broken nextval due to poorly written 20140320100000_CreateAdminUserRoleTables.sql DO 'BEGIN PERFORM setval(pg_get_serial_sequence(''admin_user_role_groups'', ''id''), 1 + COALESCE(MAX(id), 0), FALSE) FROM admin_user_role_groups; END;'; </code></pre>
30,281
<p>We have a requirement to display an editable list in a web page.</p> <p>What would be the easiest way to do that? <a href="http://www.fpoint.com/products/spread/spread.aspx" rel="nofollow noreferrer">Farpoint Spread</a> was something I have used to achieve this earlier but it was quite slow when a large number of records were involved and it needed to be coded in VBScript. Besides it wasn't free.</p> <p>I would be looking for a JavaScript solution and I can't afford to buy one. Also is there anything else you can think of other than a spread?</p>
<p>I like <a href="http://os.arandomurl.com/jqueryspreadsheet/" rel="nofollow noreferrer">JQuery.Spreadsheet UI</a>, try <a href="http://os.arandomurl.com/jqueryspreadsheet/fullscreen.html" rel="nofollow noreferrer">this demo</a>, very nice...</p>
<p>Also found at: <a href="http://code.google.com/p/completeui" rel="nofollow noreferrer">http://code.google.com/p/completeui</a></p>
34,112
<p>I'm looking to implement a "Contact Us" form with Cherrypy and was wondering: Is there a good recipe (or a BSD licensed set of code) that I could use instead of reinventing the wheel?</p> <p>Ideally, this would be Cherrpy 3.1 compatible.</p>
<p>RexExprs are good for: </p> <ul> <li>Text Format Validations (email, url, numbers)</li> <li>Text searchs/substitution.</li> <li>Mappings (e.g. url pattern to function call)</li> <li>Filtering some texts (related to substitution)</li> <li>Lexical analysis during parsing.</li> </ul>
<p>Regular expressions are a great way to parse text that doesn't already have a parser (i.e. XML) I have used it to create a parser for the mod_rewrite syntax in the .htaccess file or in my URL Rewriter project <a href="http://www.codeplex.com/urlrewriter" rel="nofollow noreferrer">http://www.codeplex.com/urlrewriter</a> for example</p>
28,512
<p>So I've got some C code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; /* putting one of the "char*"s here causes a segfault */ void main() { char* path = "/temp"; char* temp; strcpy(temp, path); } </code></pre> <p>This compiles, runs, and behaves as it looks. However, if one or both of the character pointers is declared as global variable, strcpy results in a segmentation fault. Why does this happen? Evidently there's an error in my understanding of scope.</p>
<p>As other posters mentioned, the root of the problem is that temp is uninitialized. When declared as an automatic variable on the stack it will contain whatever garbage happens to be in that memory location. Apparently for the compiler+CPU+OS you are running, the garbage at that location is a valid pointer. The strcpy "succeeds" in that it does not segfault, but really it copied a string to some arbitrary location elsewhere in memory. This kind of memory corruption problem strikes fear into the hearts of C programmers everywhere as it is extraordinarily difficult to debug.</p> <p>When you move the temp variable declaration to global scope, it is placed in the BSS section and automatically zeroed. Attempts to dereference *temp then result in a segfault.</p> <p>When you move *path to global scope, then *temp moves up one location on the stack. The garbage at that location is apparently not a valid pointer, and so dereferencing *temp results in a segfault.</p>
<p>The important part to note:<br> <b>destination string dest must be large enough to receive the copy.</b><br> In your situation temp has no memory allocated to copy into.</p> <p>Copied from the man page of strcpy:</p> <pre><code>DESCRIPTION The strcpy() function copies the string pointed to by src (including the terminating '\0' character) to the array pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. </code></pre>
14,954
<p>How would I go about replacing Windows Explorer with a third party tool such as TotalCommander, explorer++, etc?</p> <p>I would like to have one of those load instead of win explorer when I type "C:\directoryName" into the run window. Is this possible?</p>
<p>From a comment on the first LifeHacker link,</p> <h3>How to make x² your default folder application</h3> <p>As part of the installation process, x² adds "open with xplorer2" in the context menu for filesystem folders.</p> <p>If you want to have this the default action (so that folders always open in x2 when you click on them) then make sure this is the default verb, either using Folder Options ("file folder" type) or editing the registry:</p> <pre><code>[HKEY_CLASSES_ROOT\Directory\shell] @="open_x2" </code></pre> <p>If you want some slightly different command line options, you can add any of the supported options by editing the following registry key:</p> <pre><code>[HKEY_CLASSES_ROOT\Directory\shell\open\command] @="C:\Program files\zabkat\xplorer2\xplorer2_UC.exe" /T /1 "%1" </code></pre> <p>Notes:</p> <ol> <li><p>Please check your installation folder first: Your installation path may be different. Secondly, your executable may be called <code>xplorer2.exe</code>, if it is the non-Unicode version.</p></li> <li><p>Note that <code>"%1"</code> is required (including the quotation marks), and is replaced by the folder path you are trying to open.</p></li> <li><p>The <code>/T</code> switch causes no tabs to be restored and the <code>/1</code> switch puts x² in single pane mode. (You do not have to use these switches, but they make sense).</p></li> </ol> <p><em>(The above are from xplorer2 user manual)</em></p>
<p>If you go to Control Panel -> Folder Options And go to the File Types tab. You can go to the "Folder" file type (with "(NONE)" as the extension). Go to Advanced, create a new action that uses your program (I tried it with FreeCommander). Make sure you set it as default.</p> <p>That should do it.</p>
7,864
<p>I have a couple of dropdown boxes on a normal ASP.Net page.</p> <p>I would like the user to be able to change these and to have the page Pseudo-post back to the server and store these changes without the user having to hit a save button.</p> <p>I don't really need to display anything additional as the dropdown itself will reflect the new value, but I would like to post this change back without having the entire page flash due to postback </p> <p>I have heard that this is possible using AJAX.Net... </p> <p>Can someone point me in the right direction?</p>
<p>Add a reference to System.Web.Extensions and System.Web.Extensions.Design to your website. Then put a scriptmanager on your page and wrap your ddl in an updatepanel. Do whatever you want on the back-end. For example...</p> <pre><code>&lt;asp:ScriptManager ID="ScriptManager1" runat="server" /&gt; &lt;asp:UpdatePanel ID="UpdatePanel1" runat="server"&gt; &lt;ContentTemplate&gt; &lt;asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="yourDDL_SelectedIndexChanged"&gt; &lt;/asp:DropDownList&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; protected void yourDDL_SelectedIndexChanged(object sender, EventArgs e) { // do whatever you want } </code></pre>
<p>Depends upon your Ajax Framework, Ra-Ajax have a sample of that <a href="http://ra-ajax.org/samples/Ajax-DropDownList.aspx" rel="nofollow noreferrer">here</a>...</p>
33,674
<p>How do I go about making an image or section of the page full screen on the iPhone?</p> <p>I have an image that is 480 x 320 and I want to pull that up full screen on the iPhone but it has to be within a webpage so that I can make the image a link back to the previous page.</p> <p>Currently if I drop the image on a blank page and I open it up on the iPhone it just shows up in the top left corner.</p>
<p>I'd say set the viewport meta tag in your blank page so Safari knows to render the page at the right size. For more information, see this link:</p> <p><a href="http://developer.apple.com/DOCUMENTATION/AppleApplications/Reference/SafariWebContent/UsingtheViewport/chapter_4_section_5.html" rel="nofollow noreferrer">Apple iPhone Safari Documentation</a></p>
<p>nice links which may help you further:</p> <p>How to optimize your website for mobile devices: <a href="http://solutions.treypiepmeier.com/2008/12/01/optimizing-a-website-for-iphone/" rel="nofollow noreferrer">http://solutions.treypiepmeier.com/2008/12/01/optimizing-a-website-for-iphone/</a></p>
14,723