instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>A custom HTTP header is being passed to a Servlet application for authentication purposes. The header value must be able to contain accents and other non-ASCII characters, so must be in a certain encoding (ideally UTF-8).</p> <p>I am provided with this piece of Java code by the developers who control the authentication environment:</p> <pre><code>String firstName = request.getHeader("my-custom-header"); String decodedFirstName = new String(firstName.getBytes(),"UTF-8"); </code></pre> <p>But this code doesn't look right to me: it presupposes the encoding of the header value, when it seemed to me that there was a proper way of specifying an encoding for header values (from MIME I believe).</p> <p>Here is my question: what is the right way (tm) of dealing with custom header values that need to support a UTF-8 encoding:</p> <ul> <li>on the wire (how the header looks like over the wire)</li> <li>from the decoding point of view (how to decode it using the Java Servlet API, and can we assume that request.getHeader() already properly does the decoding)</li> </ul> <p>Here is an environment independent code sample to treat headers as UTF-8 in case you can't change your service:</p> <pre><code>String valueAsISO = request.getHeader("my-custom-header"); String valueAsUTF8 = new String(firstName.getBytes("ISO8859-1"),"UTF-8"); </code></pre>
<p>As mentioned already the first look should always go to the <a href="http://www.greenbytes.de/tech/webdav/rfc2616.html" rel="nofollow noreferrer">HTTP 1.1 spec</a> (RFC 2616). <a href="http://www.greenbytes.de/tech/webdav/rfc2616.html#basic.rules" rel="nofollow noreferrer">It says</a> that text in header values must use the MIME encoding as defined <a href="https://www.rfc-editor.org/rfc/rfc2047" rel="nofollow noreferrer">RFC 2047</a> if it contains characters from character sets other than ISO-8859-1.</p> <p>So here's a plus for you. If your requirements are covered by the ISO-8859-1 charset then you just put your characters into your request/response messages. Otherwise MIME encoding is the only alternative.</p> <p>As long as the user agent sends the values to your custom headers according to these rules you wont have to worry about decoding them. That's what the Servlet API should do.</p> <hr /> <p>However, there's a more basic reason why your code sniplet doesn't do what it's supposed to. The first line fetches the header value as a Java string. As we know it's represented as UTF8 internally so at this point the HTTP request message parsing is already done and finished.</p> <p>The next line fetches the byte array of this string. Since no encoding was specified (IMHO this method with no argument should have been deprecated long ago), the current system default encoding is used, which is usually not UTF8 and then the array is again converted as being UTF8 encoded. Outch.</p>
<p>See the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2" rel="nofollow noreferrer">HTTP spec</a> for the rules, which says in section 2.2 </p> <blockquote> <p>The TEXT rule is only used for descriptive field contents and values that are not intended to be interpreted by the message parser. Words of *TEXT MAY contain characters from character sets other than ISO- 8859-1 [22] only when encoded according to the rules of RFC 2047 [14].</p> </blockquote> <p>The above code will not correctly decode an RFC2047 encoding string, leading me to believe that the service doesn't correctly follow the spec, and they just embeding raw utf-8 data in the header.</p>
42,017
<p>I am new to 3D printing which we all are/were at some point. I have <strong>no</strong> clue how to address the issue which likely is reason why I haven't found the solution yet. So if you see that this question has been posted elsewhere, please link it! Thanks!</p> <p>I have had this issue for a while, however right now, one minute ago, it worked kind of. The text below is a description of the problem that very often occurs!</p> <p>So the issue is basically the extruder. I have a Flashforge Adventurer 3. In it's software you have a <em>&quot;Load&quot;</em> and <em>&quot;Change&quot;</em> option which you change and load filament with. When I load filament it goes through the tube but it never exits the extruder. The common answer is that the nozzle is clogged. I have honestly checked this, it isn't the problem. I have cleaned it as Flashforge says and I have also been using really small metallic pins to push out <strong>all</strong> the filament. So that isn't the issue.</p> <p>Sometimes the filament also gets stuck inside the tube. Or the Bowden tube I think it is called.</p> <p>I did a test 10 minutes ago, it went through the tube smoothly. No filament came out at the other end however. I then changed the filament, which means I pulled it back. I then saw that a part of the filament had gotten stuck at the end of the tube. It didn't pull all the filament back, a very small bit of the filament had somehow gotten stuck?</p> <p>As it doesn't extrude filament when I load the filament it has nothing with the calibration to do what I know. So my own conclusion would be that something between the tube and extruder is going crazy. And I know, that isn't a good conclusion. However I don't know how to address it as I said before.</p> <p>I know that it's hard to troubleshoot a text, so I will upload a video for you guys reading this. I really just want my 3D printer working again as the company said it probably isn't anything wrong with the machine..</p> <p>When the machine starts working again it prints, but not good. Here is a video of how hit prints a big &quot;F&quot;. <a href="https://youtu.be/kis_jNTRgI0" rel="nofollow noreferrer">Link</a>. Sometimes it stops extruding filament for a while then it starts to extrude again..</p> <p>There is also an image of the print below![<img src="https://i.stack.imgur.com/UeGmj.jpg" alt="Image" /></p> <p>The machine is printing at 195 °C! I appreciate all the help I can get, I just want my machine fully working again.</p> <hr /> <p>Here is a video of the Bowden tube: <a href="https://youtu.be/lFGUK6hUmkA" rel="nofollow noreferrer">Link</a></p> <p>Here is a video of the extruder issue: <a href="https://youtu.be/Y6u2Pi2xINk" rel="nofollow noreferrer">Link</a></p> <p>Here are two videos regarding the cold pull, I &quot;try&quot; to speak English so you get more information this time! <a href="https://youtu.be/ZfnNGwdTufI" rel="nofollow noreferrer">Link</a> <a href="https://youtu.be/IQmYHiYgoEo" rel="nofollow noreferrer">Link 2</a></p>
<p>This is opinion-based, but the volcano has drawbacks that affect print quality, mine is oozier and sloppier than a V6 with the shorter, more precise melt zone. It isn’t a slam dunk upgrade, more of a special applications part. I think there is no point to using a Volcano unless you’re running big nozzles fast, like .8 mm.</p> <p>Your 5 mm<sup>3</sup>/s throughput is low, the V6 is generally known as a ~13 mm<sup>3</sup>/s volumetric throughput, vs the Volcano at 25 mm<sup>3</sup>/s. This is due to the low temperature you favor, possibly something not ideal with your extruder. I could see...</p> <ul> <li><p>just living with the slow speed. I realize I vastly prefer print quality over print speed because one takes no human interaction and the other does.</p> </li> <li><p>do what everyone else does. go hotter, plastic viscosity goes way down even with a 5-10 degree increase</p> </li> <li><p>increase extruder torque. If you can increase stepper current safely (know the limit for your driver and motor!) with a trim pot on the stepper driver, you may be able to get more torque before the motor skips steps. This can increase motor temperature. If you get more torque, at some point the filament will slip and get carved up by the extruder’s hobbed gear. Double geared extruder designs like Bondtech can grip the filament from both sides and get more traction on the filament if you want to get diabolical shoving the filament.</p> </li> <li><p>use a larger nozzle for faster printing at your preferred temp. I’m loving the .6 mm nozzle for bigger prints. It has most of the detail of the .4 mm but double the plastic comes out. A larger nozzle hole means less pressure in the nozzle at a given temp and extruder feed rate</p> </li> </ul> <p>If you think the extruder might not be all it can be, try heating up the nozzle hotter than usual, and get the extruder going slow and steady, and pull a little on the filament by hand, see if it skips steps easily with a little resistance. It should pull pretty strong. I had a failing wire to my extruder that manifested in wimpy extrusion.</p>
<p>Yes, the Volcano or the Super Volcano allow for larger flow rate (typically when using larger nozzles), that is where they were designed for. Just the nozzle will not help you, you need this larger nozzle shaft to be inside a Volcano heater block, else you cannot transfer the heat.</p> <p>According to measurements from Metaform, the volumetric flow of a Volcano hotend is larger than the regular E3D V6 hotend.</p> <p><a href="https://i.stack.imgur.com/5p6Le.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5p6Le.png" alt="enter image description here" /></a></p>
1,653
<p>How do I Deserialize this XML document:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Cars&gt; &lt;Car&gt; &lt;StockNumber&gt;1020&lt;/StockNumber&gt; &lt;Make&gt;Nissan&lt;/Make&gt; &lt;Model&gt;Sentra&lt;/Model&gt; &lt;/Car&gt; &lt;Car&gt; &lt;StockNumber&gt;1010&lt;/StockNumber&gt; &lt;Make&gt;Toyota&lt;/Make&gt; &lt;Model&gt;Corolla&lt;/Model&gt; &lt;/Car&gt; &lt;Car&gt; &lt;StockNumber&gt;1111&lt;/StockNumber&gt; &lt;Make&gt;Honda&lt;/Make&gt; &lt;Model&gt;Accord&lt;/Model&gt; &lt;/Car&gt; &lt;/Cars&gt; </code></pre> <p>I have this:</p> <pre><code>[Serializable()] public class Car { [System.Xml.Serialization.XmlElementAttribute("StockNumber")] public string StockNumber{ get; set; } [System.Xml.Serialization.XmlElementAttribute("Make")] public string Make{ get; set; } [System.Xml.Serialization.XmlElementAttribute("Model")] public string Model{ get; set; } } </code></pre> <p>.</p> <pre><code>[System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)] public class Cars { [XmlArrayItem(typeof(Car))] public Car[] Car { get; set; } } </code></pre> <p>.</p> <pre><code>public class CarSerializer { public Cars Deserialize() { Cars[] cars = null; string path = HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data/") + "cars.xml"; XmlSerializer serializer = new XmlSerializer(typeof(Cars[])); StreamReader reader = new StreamReader(path); reader.ReadToEnd(); cars = (Cars[])serializer.Deserialize(reader); reader.Close(); return cars; } } </code></pre> <p>that don't seem to work :-(</p>
<p>Here's a working version. I changed the <code>XmlElementAttribute</code> labels to <code>XmlElement</code> because in the xml the StockNumber, Make and Model values are elements, not attributes. Also I removed the <code>reader.ReadToEnd();</code> (that <a href="http://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoend.aspx" rel="noreferrer">function</a> reads the whole stream and returns a string, so the <code>Deserialize()</code> function couldn't use the reader anymore...the position was at the end of the stream). I also took a few liberties with the naming :).</p> <p>Here are the classes:</p> <pre><code>[Serializable()] public class Car { [System.Xml.Serialization.XmlElement("StockNumber")] public string StockNumber { get; set; } [System.Xml.Serialization.XmlElement("Make")] public string Make { get; set; } [System.Xml.Serialization.XmlElement("Model")] public string Model { get; set; } } [Serializable()] [System.Xml.Serialization.XmlRoot("CarCollection")] public class CarCollection { [XmlArray("Cars")] [XmlArrayItem("Car", typeof(Car))] public Car[] Car { get; set; } } </code></pre> <p>The Deserialize function:</p> <pre><code>CarCollection cars = null; string path = "cars.xml"; XmlSerializer serializer = new XmlSerializer(typeof(CarCollection)); StreamReader reader = new StreamReader(path); cars = (CarCollection)serializer.Deserialize(reader); reader.Close(); </code></pre> <p>And the slightly tweaked xml (I needed to add a new element to wrap &lt;Cars&gt;...Net is picky about deserializing arrays):</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;CarCollection&gt; &lt;Cars&gt; &lt;Car&gt; &lt;StockNumber&gt;1020&lt;/StockNumber&gt; &lt;Make&gt;Nissan&lt;/Make&gt; &lt;Model&gt;Sentra&lt;/Model&gt; &lt;/Car&gt; &lt;Car&gt; &lt;StockNumber&gt;1010&lt;/StockNumber&gt; &lt;Make&gt;Toyota&lt;/Make&gt; &lt;Model&gt;Corolla&lt;/Model&gt; &lt;/Car&gt; &lt;Car&gt; &lt;StockNumber&gt;1111&lt;/StockNumber&gt; &lt;Make&gt;Honda&lt;/Make&gt; &lt;Model&gt;Accord&lt;/Model&gt; &lt;/Car&gt; &lt;/Cars&gt; &lt;/CarCollection&gt; </code></pre>
<p>If you're getting errors using xsd.exe to create your xsd file, then use the XmlSchemaInference class as mentioned <a href="http://msdn.microsoft.com/en-us/library/system.xml.schema.xmlschemainference.aspx" rel="nofollow">on msdn</a>. Here's a unit test to demonstrate:</p> <pre><code>using System.Xml; using System.Xml.Schema; [TestMethod] public void GenerateXsdFromXmlTest() { string folder = @"C:\mydir\mydata\xmlToCSharp"; XmlReader reader = XmlReader.Create(folder + "\some_xml.xml"); XmlSchemaSet schemaSet = new XmlSchemaSet(); XmlSchemaInference schema = new XmlSchemaInference(); schemaSet = schema.InferSchema(reader); foreach (XmlSchema s in schemaSet.Schemas()) { XmlWriter xsdFile = new XmlTextWriter(folder + "\some_xsd.xsd", System.Text.Encoding.UTF8); s.Write(xsdFile); xsdFile.Close(); } } // now from the visual studio command line type: xsd some_xsd.xsd /classes </code></pre>
47,555
<p>I have a multilingual ASP.NET site; one of the languages is Arabic (ar-SA). To switch between cultures, I use this code: </p> <pre><code>Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Name) Thread.CurrentThread.CurrentUICulture = New CultureInfo(Name) </code></pre> <p>When displaying the date of an article, for example, I just do this, and the localization API takes care of everything:</p> <pre><code>&lt;%#Eval("DatelineDate","{0:d MMMM yyyy}")%&gt; </code></pre> <p>The problem is that this displays dates using the Hijiri (Islamic) calendar (e.g. the year 2008 is rendered as 1429). The client wants to display the dates using the Gregorian calendar (still rendering the month names and everything else in Arabic, of course). How can I do this?</p>
<h2>Answer:</h2> <p>Turns out the ar-SA culture is the only one to use the Hijiri calendar; all the other Arabic cultures use Gregorian. Here are the different date formats in Arabic (a bit messed up because WMD doesn't support seem to support RTL text).</p> <pre><code>ar-AE 11 ديسمبر 2008 ar-BH 11 ديسمبر 2008 ar-DZ 11 ديسمبر 2008 ar-EG 11 ديسمبر 2008 ar-IQ 11 كانون الأول 2008 ar-JO 11 كانون الأول 2008 ar-KW 11 ديسمبر 2008 ar-LB 11 كانون الأول 2008 ar-LY 11 ديسمبر 2008 ar-MA 11 دجنبر 2008 ar-OM 11 ديسمبر 2008 ar-QA 11 ديسمبر 2008 ar-SA 13 ذو الحجة 1429 ar-SY 11 كانون الأول 2008 ar-TN 11 ديسمبر 2008 ar-YE 11 ديسمبر 2008 </code></pre> <p>And for what it's worth here's the quick &amp; dirty code I used to generate this list:</p> <pre><code> Response.Write(&quot;&lt;table width=300px&gt;&quot;) For Each ci As CultureInfo In (From c As CultureInfo In CultureInfo.GetCultures(CultureTypes.AllCultures) Order By c.Name Where c.Name.StartsWith(&quot;ar-&quot;)) Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(ci.Name) Thread.CurrentThread.CurrentUICulture = New CultureInfo(ci.Name) Response.Write(String.Format(&quot;&lt;tr&gt;&lt;td&gt;{0}&lt;/td&gt; &lt;td style='direction:rtl;font-size:20px;'&gt;{1:d MMMM yyyy}&lt;/td&gt;&lt;/tr&gt;&quot;, ci.Name, Today)) Next Response.Write(&quot;&lt;/table&gt;&quot;) Response.End() </code></pre> <p>More cultures at <a href="http://www.massimilianobianchi.info/max/articles/22/UI-culture-list-and-codes.aspx" rel="nofollow noreferrer">http://www.massimilianobianchi.info/max/articles/22/UI-culture-list-and-codes.aspx</a></p>
<p>You can just use another Arabic locale, The only difference between them is the Date format...</p>
46,977
<p>For a project I am doing I need to manually create a .net project. I am currently using a <code>StreamWriter</code> to create the .sln, .csproj and base (empty for now) class. I am also generating the AssemblyInfo.cs class. I have copied exactly the files and folder structure VS.Net creates when you create an empty windows class library project.</p> <p>For some reason when I try to open the .sln file nothing at all happens. I can open the .csproj file fine, but the project will not compile. I don't get any error messages, just nothing happens. I have checked all of the files I am creating against the ones created by Visual Studio using Beyond Compare and they are exactly the same except for the project name and GUID. </p> <p>Does anyone know if Visual Studio is doing something behind the scenes when it creates a project? Is there something else I could be missing?</p>
<p>Yes, an output parameter is all it took. I couldn't find the right calling syntax in the manual or google though.</p> <p>You create the procedure like this:</p> <pre><code>CREATE PROCEDURE myschema.add(IN a INT, IN b INT, OUT c INT) BEGIN SET c = a + b; END </code></pre> <p>And then call it like this (this is what I couldn't figure out):</p> <pre><code>DECLARE result INT DEFAULT 0; CALL myschema.add(10, 20, result); -- result == 30 </code></pre> <p>And then the output ends up in the supplied <code>result</code> variable. You can also have multiple <code>OUT</code> params as well as <code>INOUT</code> params.</p> <p>Sure it seems obvious now. :)</p>
<p>How about an output parameter in the proc you call from within your original proc? Calling a proc is done through the CALL command. It's in the manual ;)</p>
48,836
<p>I need an up to date and easy to use .net wrapper for google maps. </p>
<p><a href="http://www.codeplex.com/googlemap" rel="nofollow noreferrer">Googlemap Control</a> Wraps Google Maps API as ASP.NET custom control. Offers extremely easy and fast way of adding Google Maps API support on your ASP.NET pages.</p>
<p>.NET wrapper libraries for the Google Maps API (API wrapper, but NOT controls for displaying maps):</p> <ol> <li><a href="https://github.com/vivet/GoogleApi" rel="nofollow noreferrer">GoogleApi</a></li> <li><a href="https://github.com/maximn/google-maps" rel="nofollow noreferrer">google-maps</a></li> </ol> <p><a href="https://stackoverflow.com/a/61531795">https://stackoverflow.com/a/61531795</a></p>
43,251
<p>I have a class which looks something like this:</p> <pre><code>public class Test { private static final Object someObject = new Object(); public void doSomething() { synchronized (someObject) { System.out.println(someObject.toString()); } } } </code></pre> <p>Can I consider the object to be synchronized, or is there a problem since it is a static member?</p> <p><strong>Edit:</strong> note that different threads might be accessing doSomething() and the object <strong>must</strong> be accessed in a thread-safe manner in that case.</p>
<p>By using a static object as your monitor object, only one thread using ANY instance of the Test class can get into the sync block. If the monitor object was not a static object, other threads holding different instances of the Test class could get into the sync block.</p>
<p>What happens if Test class is loaded using different classloaders? </p>
40,603
<p>What is the best way to test my webforms applications?</p> <p>Looks like people are loving Watin, and selenium.</p>
<p><strong>UPDATE</strong>: <em>Given WatiN has been stagnant for over a year now, I would direct anyone that needs web ui tests towards <a href="http://seleniumhq.org" rel="nofollow noreferrer">selenium</a>, it is in continuous use &amp; development by many contributors, and is actively used by Google.</em> </p> <p><a href="http://watin.sourceforge.net/" rel="nofollow noreferrer">WatiN</a> is the best that I've found. It integrates into Visual Studio unit testing or nunit &amp; you can do pretty much anything you need in the browser (click links, submit forms, look for text/images, etc.)</p> <p>See the following questions for similar answers:</p> <ul> <li><a href="https://stackoverflow.com/questions/4363/what-is-the-best-way-to-do-unit-testing-for-asp-web-pages-c#4386">What is the best way to do unit testing for ASP web pages (C#)?</a></li> <li><a href="https://stackoverflow.com/questions/15015/web-application-testing-for-net-watin-test-recorder">Web Application Testing for .Net (watin Test Recorder)</a></li> <li><a href="https://stackoverflow.com/questions/26857/how-do-you-programmatically-fill-in-a-form-and-post-a-web-page#26864">How do you programmatically fill in a form and ‘POST’ a web page?</a></li> </ul>
<p>I would use a tool like WaitIn:</p> <p>" WatiN is Web Application Testing in .NET, and this Test Recorder will generate chunks of source for you by recording your clicks in an embedded IE browser" (from <a href="http://www.hanselman.com/blog/ScottHanselmans2007UltimateDeveloperAndPowerUsersToolListForWindows.aspx" rel="nofollow noreferrer">Scott Hanselman's blog</a> - which I found thanks to another post on StackOverflow</p> <p><a href="http://watintestrecord.sourceforge.net/" rel="nofollow noreferrer">WaitIn website</a></p>
14,429
<p>Can you recommend any resources for learning about Windows Installer?</p> <p>The best book I've found is "The Definitive Guide to Windows Installer" by Phil Wilson, but it's not very beginner friendly.</p> <p>I've been asked to make recommendations for those wishing to 'get up to speed' quickly and don't know what to recommend beyond that book and a few Microsoft sites:</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa367449.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa367449.aspx</a></p> <p><a href="http://blogs.msdn.com/Windows_Installer_Team/" rel="noreferrer">http://blogs.msdn.com/Windows_Installer_Team/</a></p> <p>Is there anything else you've found useful for learning about Windows Installer?</p>
<p>There are very little difference between 2005 and 2008 from native C++ developer point of view. However, if coming from 2003, it makes sense to upgrade directly to 2008 - the conversion process should be almost the same, and you will end up with a slightly better platform. Some new features which are available for 2008 only:</p> <ul> <li>/MP option for multicore compilation (a huge timesaver if you have a mutlicore computer)</li> <li>some improved debugging options for multithreaded applications</li> </ul> <p>There are also some additional downloadable feature packs for 2008 only:</p> <ul> <li>TR1 libraries</li> <li>new MFC</li> </ul>
<p>Visual C++ 2008 have dropped support for single threaded runtime library. I don't think it really matters though.</p>
36,454
<p>For a file containing the given class, SomeCoolClass, what would be the proper or standard filename?</p> <pre> 1. somecoolclass.rb 2. some_cool_class.rb 3. some-cool-class.rb 4. SomeCoolClass.rb </pre> <p>or some other variation?</p> <p>I noticed in the Ruby stdlib, versions 1, 2 and 3 are used.</p>
<p>With just <a href="http://www.ruby-lang.org" rel="noreferrer">Ruby</a> (i.e. not Rails), naming is only a convention. In <a href="http://rubyonrails.org" rel="noreferrer">Rails</a> the <a href="http://itsignals.cascadia.com.au/?p=7" rel="noreferrer">convention</a> of using underscores is necessary (almost).</p> <p>I think convention #2 <code>lowercase_and_underscore.rb</code> is more common and looks pretty good, though an article <a href="http://rails.learnhub.com/lesson/page/5028-ruby-coding-convention" rel="noreferrer">Here</a> says <code>lowercasenounderscore.rb</code> is the Ruby convention.</p> <p><strong>Pick either</strong> which ever convention is more common or which ever one you like more. The most important thing is to <strong>be consistent within a project</strong>.</p>
<p>I would recommend lower case characters with underscores (number 2 in your question). It's true that this naming scheme is the convention in Rails and not necessary in non-Rails projects. However, I would still stick to the Rails convention because most Ruby programmers are probably using Ruby exclusively for Rails anyway.</p>
27,271
<p>I'm trying to parse an INI file using C++. Any tips on what is the best way to achieve this? Should I use the Windows API tools for INI file processing (with which I am totally unfamiliar), an open-source solution or attempt to parse it manually?</p>
<p>You can use the Windows API functions, such as <a href="https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getprivateprofilestring" rel="noreferrer">GetPrivateProfileString()</a> and <a href="https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getprivateprofileint" rel="noreferrer">GetPrivateProfileInt()</a>.</p>
<p>Maybe a late answer..But, worth knowing options..If you need a cross-platform solution , definitely you can try GLIB,, its interesting.. (<a href="https://developer.gnome.org/glib/stable/glib-Key-value-file-parser.html" rel="nofollow">https://developer.gnome.org/glib/stable/glib-Key-value-file-parser.html</a>)</p>
3,370
<p>I'm using VS 2008 to create a C++ DLL (not managed) project and I need convert a char* to a long long type. Is there an easy way to do it?</p> <p>Thanks in advance :)</p>
<p>Try <code>_atoi64.</code> This takes <code>char*</code> and returns <code>__int64</code>.</p>
<p>Another option is using stoll() found within the string library. Takes a C++ string.</p> <pre><code>long long ll = std::stoll(mystr); </code></pre> <p><a href="http://www.cplusplus.com/reference/string/stoll/" rel="nofollow">Docs</a></p>
39,025
<p>Seems like a simple problem:</p> <ul> <li>I have an SVN repo inside our firewall. </li> <li>I have an SVN repo outside our firewall.</li> <li>I have users inside, and outside, the firewall. (no VPN isn't an option :( that'd be too easy)</li> <li>machines inside the firewall CAN talk to the outside SVN server. But not the other way.</li> <li>the outside SVN is a temporary thing - the main repo will always be inside.</li> </ul> <p>I want to somehow (from inside, most likely) take all the changes in one, and apply them to the other. And vice versa. Sounds simple, and I assume that the likes GIT can do this, but we are using SVN.</p> <p>Anyone done this? I don't mind it being a manual process - there are only a couple of external people, and they don't need updates to-the-minute, two or three times a day would do.</p> <p>I believe apache.org does this, but I can't find docs on HOW they do this. There are a couple of products out there which do it (well, one), but I'd love to know if anyone has a nice, clean way to do it without them. svnsync does this, just only in one direction (master-slave)</p> <p>Happy to have it run on windows, Linux or Mac, as we have all of them. Windows and Mac preferred though.</p> <p>Help! :) :)</p> <p>[update] after 12 months of messing around (and not needing this in the end), the correct answer is, in my opinion, correct. Use git - have one repo which pulls from SVN-A, then push to a new git repo, then push from there to SVN-B. Should work :)</p>
<p>I'd recommend <a href="http://svk.bestpractical.com/view/HomePage" rel="noreferrer">SVK</a> or <a href="http://git-scm.com/docs/git-svn" rel="noreferrer">git-svn</a>.</p> <p>Both of these let you create an external mirror of your svn repository, and allow the external devs to make commits directly to the external mirror. You can then pull and push changes from this external mirror to your internal master repo.</p> <p>git-svn would (I think) require the external developers to use git. I prefer it, but I'd be reluctant to push this on others.</p> <p>SVK, however, allows the external developers to continue using svn. Since the internal repo is only accessible internally, an internal account or user would have to handle the periodic syncronization (a cron job would probably work).</p> <p>Here's an extended howto on the SVK wiki: <a href="http://svk.bestpractical.com/view/UsingSVKAsARepositoryMirroringSystem" rel="noreferrer">UsingSVKAsARepositoryMirroringSystem</a></p>
<p>One thing you could try is to replicate the repo at file level. I am using FolderShare (<a href="http://www.foldershare.com" rel="nofollow noreferrer">http://www.foldershare.com</a> - runs on Windows and Mac) for a similar scenario, though I am replicating it only for backup purposes and have not tried to connect using SVN to the replica.</p>
17,903
<p>How can I AutoIncrement the assembly (build) number in Visual Studio?</p> <h3>Duplicate:</h3> <p><a href="https://stackoverflow.com/questions/650/">/questions/650/automatically-update-version-number</a></p>
<p>You can just use a wildcard in the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.assemblyversionattribute.aspx" rel="noreferrer">AssemblyVersionAttribute</a>:</p> <pre><code>[assembly: AssemblyVersion("1.0.*")] </code></pre> <p>This will cause build to be equal to the number of days since January 1, 2000 local time.</p>
<p>Setting it as such should do so:</p> <pre><code>[assembly: AssemblyVersion("1.0.*.*")] </code></pre>
24,733
<p>MessageBox.Show has forms like MessageBox.Show( ownerWindow, .... ).</p> <p>What do I gain by assigning a owner window?</p>
<p>A message box is a modal form, which means that its parent window is disabled until the message box is dismissed.</p> <p>If a Show() overload is called that does not take an owner identifier, then a parent form is usually chosen automatically. I can't find anything in the documentation that describes how that form is chosen, but my experience is that if the message box is displayed inside the GUI thread (i.e., the main thread, or message pump thread), then the active window for that thread is chosen as the parent.</p> <p>Other threads may create message boxes with no parent form. This could be a bad situation, because it could sit behind the active window, and the user will not even know it is there until they close the program. To avoid this, you could pass the handle of the application's main window to the Show method, which will disable that window for the duration of the message box.</p> <hr> <p><strong>ADDED:</strong> I've been thinking about this and now I'm not so sure. The snippet from reflector that you gave below makes me think that maybe the thread doesn't matter. (I did say that I couldn't find anything in the documentation!)</p> <p>I'd have to go back and look at the code to make sure, but I think the message boxes that I used to lose behind the main form may have actually been custom message box forms, in which case my experience is faulty, and you never ever have to supply a parent form parameter.</p> <p>Sorry for the confusion.</p> <p>My recommendation now is to never supply this parameter unless you need something other than the active window to be the main form.</p>
<p>if i'm not wrong this prevents to owner window to Focus() until the messagebox is closed.</p>
23,764
<p>Seems to me most of developers completely ignore this features. People prefer handling security exceptions as generic ones relying on standard windows roles and rights instead of learning to use CAS ways of enhancing security - probably because CAS is quite confusing in its logic and naming.</p> <p>Can anyone suggest any general rule-of-thumb/best practices for using CAS at his best in a clean way? </p>
<p>Yes and no.</p> <p>Unfortunately, you're right - developers rarely use CAS at all, let alone utilize it to it's fullest. In very few situations do I see them actually doing this (okay, its not really the programmers but the organization forcing them....) </p> <p>Besides being used to allow users to limit assemblies downloaded from the Internet (for example) - though this is rarely deployed outside of Silverlight - I have seen two main uses of CAS.<br> First is general policy limitations, generally the easiest way to get your feet wet with CAS (esp. since VS can auto-generate the policy file for you). I have seen this in use (rarely) when a sensitive enterprise (e.g. banks) have a third-party custom development of a system that must be secure. This can benefit them by adding additional limitations on what they dont know their programmers are doing.<br> Second is very specific link demands, in the (again rare) situation that you have a module running at relatively high privileges, and want only specific assemblies calling into your module. For instance, just last week I had a client with a module writing to ActiveDirectory, and wanted to limit access to this function only from a specific system. </p> <p>Of course, CAS is much bigger than this, but those are really the two best places to start from. As a general rule, and this is of course true for everything, dont decide to use it just because its there, unless it answers a need you have. Policy is the simplest, and makes the most sense to put in place ahead of time.</p>
<p>See also <a href="https://stackoverflow.com/questions/169951/using-the-net-framework-security-system">this discussion</a>.</p> <p>The problem is exacibated because a lot of code (perhaps too much) runs at full trust. And then the only checks that get done are things like PrincipalPermissionAttribute checks - most of the rest are simply bypassed. So in many cases there isn't much point! Unless you are loading in external (untrusted) files [and so need CAS], it simply doesn't add a lot in many cases (and yes, there are plenty of exceptions).</p> <p>CAS is much more useful for clients running in the sandbox (for example downloaded from the internet). Sliverlight takes this to the extreme, with stricter rules (especially around reflection) than regular .NET.</p>
20,606
<p>My colleague has found himself in an "interesting" situation. He is working on a Silverlight (2.0) prototype that needs to call existing web services in the enterprise and bind the returned data to data-display controls. The thing is, the web services return .NET DataSets (they are not about to change existing implementations) and Silverlight does not natively support DataSets.</p> <p>What would a good workaround be? I was thinking an adapter pattern but do not know if middle-man web services to carry out transformations would be a very good idea. Could be tedious if there are many existing web services.</p>
<p>AFAIK, when a .NET web service returns a DataSet, it returns its XML representation (which is pretty friendly). The fact that a .NET client can consume the DataSet directly only abstracts the fact that an Xml Serialization-Deserialization is taking place. </p> <p>So I would manually query the web services you require, observe the generated XML, and then parse it in the client side.</p> <p>Another possibility is to take advantage of the fact that Web Services use the standard XML Serializer, so you could create the C# classes from the returned schema and then let the XmlSerializer automatically handle it. I'm not sure if the code generated by the XSD.exe tool will be Silverlight friendly, but it is worth giving it a shot.</p>
<p>The dangers and general nastyness of Datasets eh. I would use a generic proxy that is responsible for consuming the webmethod and transforming the dataset into xml/json</p>
11,773
<p>I have a program that needs to run as a separate NT user to connect to a SQL Server databases. For running a program itself, this isn't a big deal as I can just right click on it in windows explorer and select run as. Is there any way to run my tests as a different user as well? (it would be nice if I could do so in Visual Studio)</p> <p><strong>Update</strong>: As of right now, I'm just unit testing using the integrated unit testing framework in Visual Studio 2008 Pro. I'm running them just using the "run all tests in current solution" menu option.</p>
<p>The generic information is lost in runtime. There is no runtime equivalent of a Creator&lt;String>.class. You could create a type between Creator and StringCreator which fixes the generic type:</p> <pre><code>public interface Creator&lt;T&gt; { T create(); } public interface StringCreator extends Creator&lt;String&gt; { } public class StringCreatorImpl implements StringCreator { public String create() { return new String(); } } public class FancyStringCreator implements StringCreator { public String create() { return new StringBuffer().toString(); } } public static void main(String[] args) throws Exception { Class&lt;?&gt; someClass = Class.forName(args[0]); Class&lt;? extends StringCreator&gt; creatorClass = someClass.asSubclass(StringCreator.class); Constructor&lt;? extends StringCreator&gt; creatorCtor = creatorClass.getConstructor((Class&lt;?&gt;[]) null); Creator&lt;String&gt; creator = creatorCtor.newInstance((Object[]) null); } </code></pre> <p>But of course you lose a bit of flexibility, because you cannot use the following creator class:</p> <pre><code>public class AnotherCreator implements Creator&lt;String&gt; { public String create() { return ""; } } </code></pre>
<p>Not quite sure why you're using generics here.</p> <p>The instantiation of the object using reflection would suggest a general use but presumably you're going to call <code>create</code> at some point and assign the result to a <code>String</code>, otherwise why use the generics to control the return type.</p> <p>But if you wrote the following implementation of Creator:</p> <pre><code>public class IntegerCreator implements Creator&lt;Integer&gt; { public Integer create() { ... } } </code></pre> <p>And passed it in as a argument you'd get a ClassCastException when calling <code>create</code> and assigning the result.</p>
46,494
<p>Consider a database table holding names, with three rows:</p> <pre><code>Peter Paul Mary </code></pre> <p>Is there an easy way to turn this into a single string of <code>Peter, Paul, Mary</code>?</p>
<p>If you are on SQL Server 2017 or Azure, see <a href="https://stackoverflow.com/a/42778050/1178676">Mathieu Renda answer</a>.</p> <p>I had a similar issue when I was trying to join two tables with one-to-many relationships. In SQL 2005 I found that <code>XML PATH</code> method can handle the concatenation of the rows very easily.</p> <p>If there is a table called <code>STUDENTS</code></p> <pre><code>SubjectID StudentName ---------- ------------- 1 Mary 1 John 1 Sam 2 Alaina 2 Edward </code></pre> <p>Result I expected was:</p> <pre><code>SubjectID StudentName ---------- ------------- 1 Mary, John, Sam 2 Alaina, Edward </code></pre> <p>I used the following <code>T-SQL</code>:</p> <pre><code>SELECT Main.SubjectID, LEFT(Main.Students,Len(Main.Students)-1) As &quot;Students&quot; FROM ( SELECT DISTINCT ST2.SubjectID, ( SELECT ST1.StudentName + ',' AS [text()] FROM dbo.Students ST1 WHERE ST1.SubjectID = ST2.SubjectID ORDER BY ST1.SubjectID FOR XML PATH (''), TYPE ).value('text()[1]','nvarchar(max)') [Students] FROM dbo.Students ST2 ) [Main] </code></pre> <p>You can do the same thing in a more compact way if you can concat the commas at the beginning and use <code>substring</code> to skip the first one so you don't need to do a sub-query:</p> <pre><code>SELECT DISTINCT ST2.SubjectID, SUBSTRING( ( SELECT ','+ST1.StudentName AS [text()] FROM dbo.Students ST1 WHERE ST1.SubjectID = ST2.SubjectID ORDER BY ST1.SubjectID FOR XML PATH (''), TYPE ).value('text()[1]','nvarchar(max)'), 2, 1000) [Students] FROM dbo.Students ST2 </code></pre>
<pre><code> declare @phone varchar(max)='' select @phone=@phone + mobileno +',' from members select @phone </code></pre>
23,677
<p>I have a support environment where we connect to many of our customers' systems using VPN and Remote Desktop. Right now, support personnel have to manually set up the VPN connection on their workstation. Is there a way to programmatically create the VPN connection?</p>
<p>Check out the DotRas project on CodePlex, the RasPhoneBook component has full support over managing phone books used by Windows.</p> <p><a href="http://www.codeplex.com/DotRas" rel="noreferrer">http://www.codeplex.com/DotRas</a></p> <p>It'll be a lot easier than working with the APIs directly, that much I can guarantee. :)</p>
<p>You need a batch script to connect to a VPN that is set up on the base machine. I had a similar problem to deal with a while ago and I found <a href="http://www.msfn.org/board/Connect-VPN-cmdexe-vi-t113128.html" rel="nofollow noreferrer">this</a> and <a href="http://technet.microsoft.com/en-us/library/cc779544.aspx" rel="nofollow noreferrer">this</a> link to be helpful. I have used this solution (first link) in the past so it works but I don't have the batch script anymore.</p> <p>1.) Include rasphone.pbk in your script (under C:\Documents and Settings\All Users\Application Data\Microsoft\Network\Connections\Pbk\ in XP. under C:\Users\USERNAME\AppData\Roaming\Microsoft\Network\Connections\Pbk in Vista)</p> <p>2.) Set working directory to a variable name so you can return to it</p> <p>3.) Move to the directory where the phonebook is stored using variable names based on the user profile</p> <p>4.) Test that the phone book is there, if it is, rename it to rasphone.pbk.bk, then xcopy from the script location (as saved in variable) the new phone book to the new place.</p> <p>5.) Connect.</p> <p>6.) When ready, disconnect and overwrite the phone book with your settings in with the original file if it is there, else simply delete the phone book.</p>
41,123
<p>I have an application with my object types that inherit from a base class that contains the majority of properties for the application objects. All the object types are stored in one table in the database. The "ClassType" column determines what object type I cast the SqlDataReader row to. </p> <p>Here is my current implementation:</p> <pre><code>SqlDataReader dr = SqlServerHelper.ExecuteReader("MyStoreProc", MySqlParmas); if(dr.HasRows) { while(dr.Read()) { switch(dr["ClassType"].ToString()) { case "ClassA": //cast sqldatareader a ClassA object ClassA a = new ClassFactory.CreateClassA(object p1, object p2); case "ClassB": //cast sqldatareader a ClassB object ClassB b = new ClassFactory.CreateClassB(object p1, object p2); //it continues for all objects with app.... } } } dr.Close() </code></pre> <p>My question is is their a better implementation for this type of processing?</p>
<p>I guess I would lean towards an Object-Relational Mapper for this. <a href="http://www.hibernate.org/343.html" rel="noreferrer">NHibernate</a> is an example of an existing, free, mature ORM solution for the .NET platform.</p>
<p>LINQ to SQL might be a legitimate option. However, It does not play very well with databases that are not properly constrained with Primary and Foreign keys. It will generate the class based on the tables.</p>
38,535
<p>I've started with ASP.NET MVC recently, reading blogs, tutorials, trying some routes, etc. Now, i've stumbled on a issue where i need some help.</p> <p>Basically, i have an URL like /products.aspx?categoryid=foo&amp;productid=bar</p> <p>Most tutorials/examples propose to map this to something like: /products/category/foo/bar where "products" is the controller, "category" is the action, etc.</p> <p>But i need to map it to /products/foo/bar. (without "category")</p> <p>Is it possible? Am i missing something? Help will be highly appreciated. Thank you advance :)</p> <p>P.S. Sorry for my bad English.</p>
<p><em>(your English is just fine, no need to apologize!)</em></p> <p>You can define a route like this:</p> <pre><code>routes.MapRoute("productsByCategory", "products/{category}/{productid}", new { controller="products", action="findByCategory" }) </code></pre> <p>This will match</p> <p><code>products/foo/bar</code> and call an action looking like this:</p> <pre><code>public class ProductsController : Controller { ... public ActionResult FindByCategory(string category, string productid) { .... } } </code></pre> <p>does this help?</p>
<p>You also might consider making a Controller to test out your custom routes...</p> <p>Check out <a href="http://weblogs.asp.net/stephenwalther/archive/2008/08/03/asp-net-mvc-tip-29-build-a-controller-to-debug-your-custom-routes.aspx" rel="nofollow noreferrer">Stephen Walther's blog entry</a> about it.</p>
16,929
<p>We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS.</p> <p>The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property. Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name? In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT.</p>
<p>I would suggest to work with <a href="http://ant.apache.org/manual/Tasks/macrodef.html" rel="nofollow noreferrer">macros</a> over subant/antcall because the main advantage I found with macros is that you're in complete control over the properties that are passed to the macro (especially if you want to add new properties).</p> <p>You simply refactor your Ant script starting with your target:</p> <pre><code>&lt;target name="vss.check"&gt; &lt;vssadd localpath="D:\build\build.00012.zip" comment="Added by automatic build"/&gt; &lt;/target&gt; </code></pre> <p>creating a macro (notice the copy/paste and replacement with the @{file}):</p> <pre><code>&lt;macrodef name="private-vssadd"&gt; &lt;attribute name="file"/&gt; &lt;sequential&gt; &lt;vssadd localpath="@{file}" comment="Added by automatic build"/&gt; &lt;/sequential&gt; &lt;/macrodef&gt; </code></pre> <p>and invoke the macros with your files:</p> <pre><code>&lt;target name="vss.check"&gt; &lt;private-vssadd file="D:\build\File1.zip"/&gt; &lt;private-vssadd file="D:\build\File2.zip"/&gt; &lt;/target&gt; </code></pre> <p>Refactoring, "the Ant way"</p>
<p>You can use <a href="http://gant.codehaus.org/" rel="nofollow noreferrer">Gant</a> to script your build with <a href="http://groovy.codehaus.org" rel="nofollow noreferrer">groovy</a> to do what you want or have a look at the <a href="http://groovy.codehaus.org/The+groovy+Ant+Task" rel="nofollow noreferrer">groovy ant task</a>.</p>
7,249
<p>Which cryptography algorithm is the most secure that ships with .net?</p>
<p>You cannot directly compare all types of cryptographic algorithms. That would be like comparing a sorting algorithm with a multiplication algorithm: they have different purposes. That being said, I would answer:</p> <ul> <li>Symmetric cipher: <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.aspx" rel="noreferrer">AES-256</a></li> <li>Asymmetric cipher: <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx" rel="noreferrer">RSA</a> with 4096 bit key (I believe that is the maximum in .NET) or <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.ecdsa.aspx" rel="noreferrer">ECDSA</a> with 571 bit key (but that is only supported in .NET 3.5)</li> <li>Hash: <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx" rel="noreferrer">SHA-512</a></li> <li>Message Authentication Code: <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha512.aspx" rel="noreferrer">HMAC with SHA-512</a></li> </ul> <p>That being said, those are overkill for most applications, and you should do fine using AES-128, RSA with 2048 bit key, SHA-256 and HMAC with SHA-256.</p>
<p>I'm somewhat partial to <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx" rel="nofollow noreferrer">SHA-512</a>. If 512 is a little excessive, the other members of the SHA-2 family might be helpful - <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha256.aspx" rel="nofollow noreferrer">SHA-256</a> and <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha384.aspx" rel="nofollow noreferrer">SHA-384</a> are both in the SHA-2 family. But AviewAnew's suggestion of <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.aspx" rel="nofollow noreferrer">AES 256</a> is good as well.</p>
32,295
<p><a href="http://www.w3.org/TR/xhtml1/#C_2" rel="noreferrer">W3C recommends putting a space before the closing tag in XHTML</a>, because this would give a better backwards compability with some browsers, e.g. write <code>&lt;br /&gt;</code> instead of <code>&lt;br/&gt;</code>. But are there still browsers out there, that would not tolerate that you omitted the space? (W3C do not mention which browsers cause problems.)</p> <p>I know it doesn't make much of a diffence. I just prefer the shorter version. So unless there is a good reason I will now start coding my XHTML without spaces before closing empty tags.</p>
<p>It's for Netscape 4.</p> <p>I still include it out of habit, and my templating library will put them in for me anyway, but it's questionable whether it's really that important today.</p>
<p>If there are still browsers that rely on the space use it. </p> <p>The amount of bytes saved does not justify the possible problems.</p>
39,279
<p>Is it possible to determine whether a particular youtube video is encoded with H.264 or FLV through the YouTube data API? If so, how? </p> <p>I can start a file download and check how the video stream was encoded (programmatically, of course), but I'd like to use the YouTube data API to avoid all that overhead.</p>
<p>2000 and 365 are Integer values. In VBA, Integers are 16-bit signed types, when you perform arithmetic on 2 integers the arithmetic is carried out in 16-bits. Since the result of multiplying these two numbers exceeds the value that can be represented with 16 bits you get an exception. The second example works because the first number is first converted to a 32-bit type and the arithmetic is then carried out using 32-bit numbers. In your example, the arithmetic is being performed with 16-bit integers and the result is then being converted to long but at that point it is too late, the overflow has already occurred. The solution is to convert one of the operands in the multiplication to long first:</p> <pre><code>Dim Price as Long Price = CLng(AnnualCost) * Months / 12 </code></pre>
<p>In VBA, literals are integer by default (as mentioned). If you need to force a larger datatype on them you can recast them as in the example above or just append a type declaration character. (The list is here: <a href="http://support.microsoft.com/kb/191713" rel="nofollow noreferrer">http://support.microsoft.com/kb/191713</a>) The type for Long is "&amp;" so you could just do:</p> <pre><code>Price = CLng(AnnualCost * Months / 12&amp;) </code></pre> <p>And the 12 would be recast as a long. However it is generally good practice to avoid literals and use constants. In which case you can type the constant in it's declaration.</p> <pre><code>Const lngMonths12_c as Long = 12 Price = CLng(AnnualCost * Months / lngMonths12_c) </code></pre>
40,841
<p>I can currently to the following:</p> <pre><code>class SubClass extends SuperClass { function __construct() { parent::__construct(); } } class SuperClass { function __construct() { // this echoes "I'm SubClass and I'm extending SuperClass" echo 'I\'m '.get_class($this).' and I\'m extending '.__CLASS__; } } </code></pre> <p>I would like to do something similar with the filenames (<code>__FILE__</code>, but dynamically evaluated); I would like to know what file the subclass resides in, from the superclass. Is it possible in any elegant way?</p> <p>I know you could do something with <a href="http://fi.php.net/get_included_files" rel="nofollow noreferrer"><code>get_included_files()</code></a>, but that's not very efficient, especially if I have numerous instances.</p>
<p>You can use Reflection.</p> <pre><code>$ref = new ReflectionObject($this); $ref-&gt;getFileName(); // return the file where the object's class was declared </code></pre>
<p>Uh, not really, that I can think of. Each subclass would need to have an explicitly implemented method that returned <code>__FILE__</code>, which completely defeats the point of inheritance in the first place.</p> <p>I'm also really curious as to why something like this would be useful. </p>
24,726
<p>I am looking to use Java to get the MD5 checksum of a file. I was really surprised but I haven't been able to find anything that shows how to get the MD5 checksum of a file.</p> <p>How is it done?</p>
<p>There's an input stream decorator, <code>java.security.DigestInputStream</code>, so that you can compute the digest while using the input stream as you normally would, instead of having to make an extra pass over the data.</p> <pre><code>MessageDigest md = MessageDigest.getInstance("MD5"); try (InputStream is = Files.newInputStream(Paths.get("file.txt")); DigestInputStream dis = new DigestInputStream(is, md)) { /* Read decorated stream (dis) to EOF as normal... */ } byte[] digest = md.digest(); </code></pre>
<p>If you're using ANT to build, this is dead-simple. Add the following to your build.xml:</p> <pre><code>&lt;checksum file="${jarFile}" todir="${toDir}"/&gt; </code></pre> <p>Where jarFile is the JAR you want to generate the MD5 against, and toDir is the directory you want to place the MD5 file.</p> <p><a href="http://ant.apache.org/manual/Tasks/checksum.html" rel="nofollow noreferrer">More info here.</a></p>
39,092
<p>I have a long form that the user has to fill out. </p> <p>So I broke the form into logical units and created another user control for some elements (they will be reused elsewhere).</p> <p>So say the form has these fields:</p> <p>UserControl3.ascx</p> <p>Username password email -- usercontrol2.ascx address -- usercontrol2.ascx city -- usercontrol2.ascx state -- usercontrol2.ascx</p> <p>So now in the codebehidn of usercontrol3.ascx, how will I access the usercontrol2.ascx's fields so I can write to the db?</p>
<p>do as Java: pack it all in a zip, and use an filesystem-like API to read directly from there.</p>
<p>Short answer: yes.</p> <p>In Mac OS 6,7,8 there was a substantial API devoted to this exact task. Lookup the "Resource Manager" if you are interested. Edit: So does the <A href="http://root.cern.ch/" rel="nofollow noreferrer">ROOT</A> physics analysis package.</p> <p>Not that I know of a good tool right now. What platform(s) do you want it to work on?</p> <hr> <p>Edited to add: All of the two-or-three tools of this sort that I am away of share a similar struture:</p> <ul> <li>The file starts with a header and index</li> <li>There are a series of blocks some of which may have there own headers and indicies, some of which are leaves</li> <li>Each leaf is a simple serialization of the data to be stored.</li> <li>The whole file (or sometimes individual blocks) may be compressed.</li> </ul> <p>Not terribly hard to implement your own, but I'd look for a good existing one that meets your needs first.</p>
25,225
<p>How do I know what nozzle to get for my Anet A6 printer? I want to get some hardened nozzles because I would love to print with some glow in the dark filament, but I know that eats up brass nozzles fast. But there is so many thread differences so I don't know which one to get, or even what thread the Anet A6 is. Could I have some help finding the thread type and what hardened nozzles would be recommended?</p>
<p>The <a href="https://www.creaform3d.com/en/customer-support/legacy-products/exascan-scanner" rel="nofollow noreferrer">Creaform EXAscan</a> is according to the manufacturer a laser based machine. This means that it determines data points and their positions by some triangonometry done with a laser, 32.000 times a second, resulting in very high density point clouds. This demands a powerful program to work with.</p> <p>At some point, your company used <a href="http://www.directdimensions.com/port_featuredprojects.php?fileName=fp_rapidform" rel="nofollow noreferrer">Rapidform</a>, which costs a wooping 10 to 30 grand for a license. Other software in this niece are - <a href="https://forum.solidworks.com/thread/41681" rel="nofollow noreferrer">according to a solidworks thread</a> - <a href="https://de.3dsystems.com/software" rel="nofollow noreferrer">Geomagic</a> and <a href="https://www.innovmetric.com/en/products/polyworks-inspector" rel="nofollow noreferrer">PolyWorks</a>. The gist of the thread seems to be that these "big 3" were the best ones at the market in 2011. However I have no idea if they work together with the given hardware or what the later two cost.</p>
<p>So if the original manufacturer still exists, <a href="https://www.creaform3d.com/en/customer-support/legacy-products/exascan-scanner" rel="nofollow noreferrer">(which they appear to, and even list your scanner under 'legacy' products)</a> your best chance of getting it working is going to be to contact them directly. Using proprietary hardware WITHOUT the associated proprietary software can range from merely tedious but possible, to outright impossible, depending on the specific company. Oftentimes with tech products like this, the business model isn't about the product itself, but about the license fees for the software to use it. That they can charge yearly for. It's possible that the raw data is just a stereo camera file with extensions renamed, and equally possible that the firmware in the scanner will do some sort of check for valid license before it will even start scanning, they don't really have much info on their legacy products on their page</p>
869
<p>I have an x64 server which, since my libraries are compiled to AnyCPU, run under x64. We are needing to access a COM component which is registered under x86. I don't know enough about COM and my google searches are leading me nowhere.</p> <p>Question: Can I use a symbolic registry link from x64 back to x86 for the COM component? Do I need to register the COM component under x64 as well? Can I (any statement here...) ?</p> <p>Thanks.</p>
<p>If a component is running x64-native, it can't load a 32-bit COM server in-process, because it's the wrong sort of process. There are a couple of solutions possible:</p> <ol> <li><p>If you can, build a 64-bit version of the COM code (which would of course register itself in the 64-bit registry). This is the cleanest solution, but may not be possible if you don't have the code for the COM server.</p></li> <li><p>Run your .NET component as 32-bit x86, instead of x64. I assume you've already considered and rejected this one for some reason.</p></li> <li><p>Host the COM component out-of-process using the <a href="http://msdn.microsoft.com/en-us/library/ms684044(VS.85).aspx" rel="noreferrer">COM surrogate</a> DLLhost.exe. This will make calls to the COM server much, much slower (they will now be interprocess Windows messages instead of native function calls), but is otherwise transparent (you don't have to do anything special). </p> <p>This probably won't be an option if the server requires a custom proxy-stub instead of using the normal oleaut32 one (very rare, though), since there won't be a 64-bit version of the proxy available. As long as it can use the ordinary OLE marshalling, you can just <a href="http://msdn.microsoft.com/en-us/library/ms686606(VS.85).aspx" rel="noreferrer">register it for surrogate activation</a>.</p></li> </ol>
<p>It's your COM component is housed in a COM server (ie a seperate process) then you won't need to do anything special as the COM subsystem will remote your calls from your x64 app to the X86 app and back again.</p> <p>If your component is an in-process COM component then you'll have to rethink things as a 64 bit process can't use 32 bit in process COM components. You could force your server to run under x86 so that you can access the components (they'll both be 32 bit processes). If you don't want to do this then you'll have to see if there a x64 bit version of the COM components you're using.</p>
46,867
<p>I've been trying with limited success to export a crosstab query result set to Excel using Access 2003. Occasionally, the export works correctly, and Excel shows with no errors. Other times, using the exact same query parameters, I get a 3190 error - too many fields. I am using the TransferSpreadsheet option in a macro that is called from VB code.</p> <p>The macro has the following parameters: Transfer type: Export Spreadsheet type: Microsoft Excel 8-10 Table Name: (this is my query name) File Name: (Excel output file, which exists in the directory) Has Field Names: Yes</p> <p>The query should not produce any more than 14 columns worth of information, so the Excel 255 col limit should not be a problem. Also,the data in the database is not changing during the time I am querying, so the same query will produce the same result set.</p> <p>One of the only solutions I have read on the net thus far is to close the recordset before running the macro, but this is hit or miss.</p> <p>Your thoughts/help are greatly appreciated!</p>
<p>I've got one working as an MS Access Macro. It uses an OutputTo Action with:</p> <ul> <li>Object Type=Query</li> <li>Object Name=[WhateverQueryName]</li> <li>Output Format=MicrosoftExcel(*.xls)</li> <li>Auto Start=No</li> <li>(all the rest blank)</li> </ul> <p>I hate using Macros in MS Access (it feels unclean), but perhaps give that a try.</p>
<p>A workaround would be to append the query to a table first and then export that. </p> <pre><code>DoCmd.SetWarnings False DoCmd.OpenQuery "TempTable-Make" DoCmd.RunSQL "DROP TABLE TempTable" ExportToExcel() DoCmd.SetWarnings True </code></pre> <p>TempTable-Make is a make-table query based on the crosstab.</p> <p><a href="http://www.excelguru.ca/node/23" rel="nofollow noreferrer">Here</a> is an appropriate ExportToExcel function you can use.</p>
45,337
<p>I'm investigating the following <code>java.lang.VerifyError</code></p> <pre><code>java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMonthData signature: (IILjava/util/Collection;Ljava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageRe˜̴MtÌ´MÚw€mçw€mp:”MŒŒ at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357) at java.lang.Class.getConstructor0(Class.java:2671) </code></pre> <p>It occurs when the jboss server in which the servlet is deployed is started. It is compiled with jdk-1.5.0_11 and I tried to recompile it with jdk-1.5.0_15 without succes. That is the compilation runs fine but when deployed, the java.lang.VerifyError occurs.</p> <p>When I changed the method name and got the following error:</p> <pre><code>java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMD signature: (IILjava/util/Collection;Lj ava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageResources┬á├ÿ├àN|├ÿ├àN├Üw┬Çm├ºw┬ÇmX#├ûM|X├öM at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357 at java.lang.Class.getConstructor0(Class.java:2671) at java.lang.Class.newInstance0(Class.java:321) at java.lang.Class.newInstance(Class.java:303) </code></pre> <p>You can see that more of the method signature is shown.</p> <p>The actual method signature is</p> <pre><code> private PgasePdfTable getMonthData(int month, int year, Collection dayTypes, Collection calendarDays, HashMap bcSpecialDays, Collection activityPeriods, Locale locale, MessageResources resources) throws Exception { </code></pre> <p>I already tried looking at it with <code>javap</code> and that gives the method signature as it should be.</p> <p>When my other colleagues check out the code, compile it and deploy it, they have the same problem. When the build server picks up the code and deploys it on development or testing environments (HPUX), the same error occurs. Also an automated testing machine running Ubuntu shows the same error during server startup.</p> <p>The rest of the application runs okay, only that one servlet is out of order. Any ideas where to look would be helpful.</p>
<p><code>java.lang.VerifyError</code> can be the result when you have compiled against a different library than you are using at runtime.</p> <p>For example, this happened to me when trying to run a program that was compiled against Xerces 1, but Xerces 2 was found on the classpath. The required classes (in <code>org.apache.*</code> namespace) were found at runtime, so <code>ClassNotFoundException</code> was <strong><em>not</em></strong> the result. There had been changes to the classes and methods, so that the method signatures found at runtime did not match what was there at compile-time.</p> <p>Normally, the compiler will flag problems where method signatures do not match. The JVM will verify the bytecode again when the class is loaded, and throws <code>VerifyError</code> when the bytecode is trying to do something that should not be allowed -- e.g. calling a method that returns <code>String</code> and then stores that return value in a field that holds a <code>List</code>.</p>
<p>In my case, I was getting verify error with below stack trace</p> <pre><code>jasperreports-server-cp-6.4.0-bin\buildomatic\build.xml:61: The following error occurred while executing this line: TIB_js-jrs-cp_6.4.0_bin\jasperreports-server-cp-6.4.0-bin\buildomatic\bin\setup.xml:320: java.lang.VerifyError: (class: org/apache/commons/codec/binary/Base64OutputStream, method: &lt;init&gt; signature: (Ljava/io/OutputStream;ZI[B)V) Incompatible argument to function at com.jaspersoft.jasperserver.crypto.KeystoreManager.createKeystore(KeystoreManager.java:257) at com.jaspersoft.jasperserver.crypto.KeystoreManager.init(KeystoreManager.java:224) at com.jaspersoft.buildomatic.crypto.KeystoreTask.execute(KeystoreTask.java:64) at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) at org.apache.tools.ant.Task.perform(Task.java:348) at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:68) at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) at org.apache.tools.ant.Task.perform(Task.java:348) at org.apache.tools.ant.Target.execute(Target.java:435) at org.apache.tools.ant.helper.ProjectHelper2.parse(ProjectHelper2.java:169) at org.apache.tools.ant.taskdefs.ImportTask.importResource(ImportTask.java:222) at org.apache.tools.ant.taskdefs.ImportTask.execute(ImportTask.java:163) at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) at org.apache.tools.ant.Task.perform(Task.java:348) at org.apache.tools.ant.Target.execute(Target.java:435) at org.apache.tools.ant.helper.ProjectHelper2.parse(ProjectHelper2.java:180) at org.apache.tools.ant.ProjectHelper.configureProject(ProjectHelper.java:93) at org.apache.tools.ant.Main.runBuild(Main.java:826) at org.apache.tools.ant.Main.startAnt(Main.java:235) at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280) at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109) </code></pre> <p>I got it resolved by removing classpath entry for commons-codec-1.3.jar, there was a mismatch in version of this jar with the one comes with Jasper.</p>
12,533
<p>I wanted to see if folks were using decimal for financial applications instead of double. I have seen lots of folks using double all over the place with unintended consequences . .</p> <p>Do you see others making this mistake . . .</p>
<p>We did unfortunately and we regret it. We had to change all doubles to decimals. Decimals are good for financial applications. You can look at this article <a href="http://www.codeproject.com/KB/recipes/MoneyTypeForCLR.aspx" rel="nofollow noreferrer">A Money type for the CLR</a>:</p> <blockquote> <p>A convenient, high-performance money structure for the CLR which handles arithmetic operations, currency types, formatting, and careful distribution and rounding without loss.</p> </blockquote>
<p>I have always used Decimal. At least when I had a language that supports it. Otherwise, rounding errors will kill you.</p>
28,764
<p>I have MAMP set up on my iMac and on my Macbook. I want to keep both installs synced using <a href="http://www.getdropbox.com" rel="noreferrer">dropbox</a>. When upgrading MAMP the only 2 folders you need to transfer are 'db' &amp; 'htdocs'. My theory is then that these are the only 2 folders I need to keep in sync. Sound right to you so far?</p> <p>Syncing the 'htdocs' folder is easy as you can put it in your dropbox and point the MAMP preferences to the dropbox folder, but the 'db' folder has no such option.</p> <p>Any suggestions on how I could keep the 'db' folder synced? Thanks.</p>
<p>What I ended up doing was putting my hotdocs folder into my dropbox and changing the path in MAMP to the dropbox version. I than asked a friend to set up a few mysql remote databases for me. This combination has been working great. I have to use Sequel Pro to access the database which is a nice app. I was originally hoping to use phpmyadmin or learn the terminal but those features were not available on my mates server. Hope this helps someone else.</p> <p>Dropbox has such a small lag too that I have even found myself coding on one comp and refreshing on another comp. Dropbox is worth finding uses for.</p>
<p>Ok, so I am thinking that my solution is going to have to be a combination of chronosync <a href="http://www.econtechnologies.com/site/Pages/ChronoSync/chrono_overview.html" rel="nofollow noreferrer">http://www.econtechnologies.com/site/Pages/ChronoSync/chrono_overview.html</a> &amp; dropbox.</p> <p>Have a copy of cronosync on both the macbook and the iMac then before starting work on either machine manually run chronosync to sync the MAMP 'db' folder with the dropbox 'db' folder.</p> <p>Unless someone out there has a better idea. Thanks.</p>
41,462
<p>What tips and "standards" do you use in your Redmine project management process?</p> <p>Do you have a standard wiki insert template you could share or a standard way to work a project using bugs features tasks and support issues?</p> <p>Do you let issues and updates get emailed into Redmine? Do you use the forums? Do you use SVN repository? Do you use Mylyn in eclipse to work the task lists?</p> <p>I'm trying to drag our dept. into some web based PM instead of emailed Word docs of vague requirements followed by Word docs explaining how to QA and Deploy that all get lost in a pile of competing updates and projects so that by the time I have to fix something, no one can find any documentation on how it works.</p>
<p>I'm a freelance Ruby and Redmine web developer who runs a development business of one (me). So my Redmine is setup to be pretty lightweight and customer focused. My Redmine also serves double duty for hosting my Open Source projects.</p> <p>I do allow new issues and updates to be emailed and it works great for email connected users (or those who are always on their iPhones).</p> <p>I've been using the repository view with git repositories and it's working great. With every checkin I reference the issue with #nnn so the actual issue page will show all the commits to implement the feature.</p> <p>I found the forums are underused. I think if there was some email integration, they would be more useful.</p>
<p>We are using the Roadmap section as a clear way to display:</p> <ul> <li>bugs</li> <li>features (that would be references to your word document, or link to html requirement pages)</li> <li>reconciliations (differences between production values and test values)</li> <li>and so on...</li> </ul> <p>That is the main point of consolidation for us. The rest is used in relation with that (for instance, the 'announce' section is used to define the main milestone/release dates used in the roadmap)</p>
28,770
<p>Here's the problem:</p> <p>In C# I'm getting information from a legacy ACCESS database. .NET converts the content of the database (in the case of this problem a string) to Unicode before handing the content to me.</p> <p>How do I convert this Unicode string back to it's ASCII equivalent?</p> <p><hr> <strong>Edit</strong><br> Unicode char 710 is indeed MODIFIER LETTER CIRCUMFLEX ACCENT. Here's the problem a bit more precise: </p> <pre> -> (Extended) ASCII character ê (Extended ASCII 136) was inserted in the database. -> Either Access or the reading component in .NET converted this to U+02C6 U+0065 (MODIFIER LETTER CIRCUMFLEX ACCENT + LATIN SMALL LETTER E) -> I need the (Extended) ASCII character 136 back. </pre> <p><hr> Here's what I've tried (I see now why this did not work...):</p> <pre><code>string myInput = Convert.ToString(Convert.ToChar(710)); byte[] asBytes = Encoding.ASCII.GetBytes(myInput); </code></pre> <p>But this does not result in 94 but a byte with value 63...<br> Here's a new try but it still does not work:</p> <pre><code>byte[] bytes = Encoding.ASCII.GetBytes("ê"); </code></pre> <p><hr> <strong>Soltution</strong><br> Thanks to both <a href="https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138579">csgero</a> and <a href="https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138583">bzlm</a> for pointing in the right direction I solved the problem <a href="https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-ascii-equivalent#141816">here</a>.</p>
<p>Okay, let's elaborate. Both <a href="https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138579">csgero</a> and <a href="https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138583">bzlm</a> pointed in the right direction.</p> <p>Because of blzm's reply I looked up the Windows-1252 page on wiki and found that it's called a codepage. The wikipedia article for <a href="http://en.wikipedia.org/wiki/Codepage" rel="nofollow noreferrer">Code page</a> which stated the following: </p> <blockquote> <p>No formal standard existed for these ‘<a href="http://en.wikipedia.org/wiki/Extended_ASCII" rel="nofollow noreferrer">extended character sets</a>’; IBM merely referred to the variants as code pages, as it had always done for variants of EBCDIC encodings.</p> </blockquote> <p>This led me to codepage 437:</p> <blockquote> <p>n ASCII-compatible code pages, the lower 128 characters maintained their standard US-ASCII values, and different pages (or sets of characters) could be made available in the upper 128 characters. DOS computers built for the North American market, for example, used <a href="http://en.wikipedia.org/wiki/Code_page_437" rel="nofollow noreferrer">code page 437</a>, which included accented characters needed for French, German, and a few other European languages, as well as some graphical line-drawing characters.</p> </blockquote> <p>So, codepage 437 was the codepage I was calling 'extended ASCII', it had the ê as character 136 so I looked up some other chars as well and they seem right.</p> <p>csgero came with the Encoding.GetEncoding() hint, I used it to create the following statement which solves my problem:</p> <pre><code>byte[] bytes = Encoding.GetEncoding(437).GetBytes("ê"); </code></pre>
<p>Hmm … I'm not sure which character you mean. The caret (“^”, CIRCUMFLEX ACCENT) has the same code in ASCII and Unicode (U+005E).</p> <p>/EDIT: Damn, my fault. 710 (U+02C6) is actually the MODIFIER LETTER CIRCUMFLEX ACCENT. Unfortunately, this character isn't part of ASCII at all. It might look like the normal caret but it's a different character. Simple conversion won't help here. I'm not sure if .NET supports mapping of similar characters when converting from Unicode. Worth investigating, though.</p>
16,764
<p>I have two tables:</p> <p>Table 1: ID, PersonCode, Name, </p> <p>Table 2: ID, Table1ID, Location, ServiceDate</p> <p>I've got a query joining table 1 to table 2 on table1.ID = table2.Table1ID where PersonCode = 'XYZ'</p> <p>What I want to do is return Table1.PersonCode,Table1.Name, Table2.Location, Table2.ServiceDate, I don't want all rows, In table 2 I'm only interested in the row with the most recent ServiceDate for each location. How would I go about doing this?</p>
<p>Something like this:</p> <pre><code>SELECT Table1.PersonCode, Table1.Name, Table2.Location, MAX(Table2.ServiceDate) FROM Table1 INNER JOIN Table2 on Table1.ID = Table2.Table1ID WHERE TABLE1.PersonCode = 'XYZ' GROUP BY Table1.PersonCode,Table1.Name, Table2.Location </code></pre>
<p>Use MAX(ServiceDate)</p>
31,694
<p>In python is it possible to get or set a logical directory (as opposed to an absolute one).</p> <p>For example if I have:</p> <pre><code>/real/path/to/dir </code></pre> <p>and I have</p> <pre><code>/linked/path/to/dir </code></pre> <p>linked to the same directory.</p> <p>using os.getcwd and os.chdir will always use the absolute path</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.chdir('/linked/path/to/dir') &gt;&gt;&gt; print os.getcwd() /real/path/to/dir </code></pre> <p>The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. However, this only works until you call os.chdir for the first time.</p>
<p>The underlying operational system / shell reports real paths to python. </p> <p>So, there really is no way around it, since <code>os.getcwd()</code> is a wrapped call to C Library <code>getcwd()</code> function.</p> <p>There are some workarounds in the spirit of the one that you already know which is launching <code>pwd</code>.</p> <p>Another one would involve using <code>os.environ['PWD']</code>. If that environmnent variable is set you can make some <code>getcwd</code> function that respects it.</p> <p>The solution below combines both:</p> <pre><code>import os from subprocess import Popen, PIPE class CwdKeeper(object): def __init__(self): self._cwd = os.environ.get("PWD") if self._cwd is None: # no environment. fall back to calling pwd on shell self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip() self._os_getcwd = os.getcwd self._os_chdir = os.chdir def chdir(self, path): if not self._cwd: return self._os_chdir(path) p = os.path.normpath(os.path.join(self._cwd, path)) result = self._os_chdir(p) self._cwd = p os.environ["PWD"] = p return result def getcwd(self): if not self._cwd: return self._os_getcwd() return self._cwd cwd = CwdKeeper() print cwd.getcwd() # use only cwd.chdir and cwd.getcwd from now on. # monkeypatch os if you want: os.chdir = cwd.chdir os.getcwd = cwd.getcwd # now you can use os.chdir and os.getcwd as normal. </code></pre>
<p>This also does the trick for me:</p> <pre><code>import os os.popen('pwd').read().strip('\n') </code></pre> <p>Here is a demonstration in python shell:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.popen('pwd').read() '/home/projteam/staging/site/proj\n' &gt;&gt;&gt; os.popen('pwd').read().strip('\n') '/home/projteam/staging/site/proj' &gt;&gt;&gt; # Also works if PWD env var is set &gt;&gt;&gt; os.getenv('PWD') '/home/projteam/staging/site/proj' &gt;&gt;&gt; # This gets actual path, not symlinked path &gt;&gt;&gt; import subprocess &gt;&gt;&gt; p = subprocess.Popen('pwd', stdout=subprocess.PIPE) &gt;&gt;&gt; p.communicate()[0] # returns non-symlink path '/home/projteam/staging/deploys/20150114-141114/site/proj\n' </code></pre> <p>Getting the environment variable PWD didn't always work for me so I use the popen method. Cheers!</p>
15,077
<p>Is it possible to run a batch file as a menu item in studio 2008?</p>
<p>Yes, go to <strong>Tools | External Tools</strong> in the menus and add your batch file as the Command. You can also pass in any arguments that you want such as the build target, project directories, etc.</p> <p>Once you do this, your batch file will appear as one of the items on your tools menu. If you want, you can then add a toolbar button for it by going <strong>Tools | Customize | Tools</strong> and dragging the <em>External Command #</em> that matches your tool to the toolbar. You will then want to change it to an icon and select an image for it.</p> <p>The tools are numbered 1 based in the order they appear in the menu.</p>
<p>Use "Tools"/"External Tools..." menu item and add your bat-file to "Tools" menu</p>
44,921
<p>I've got a table with a header, a row with input fields, rows with data. <a href="http://brow.hu/sitegen/stackoverflow_table_example.png" rel="nofollow noreferrer">Like this. http://brow.hu/sitegen/stackoverflow_table_example.png</a></p> <p>If somebody enters something into an input field I want to filter the data with an ajax query. After receiving the new table I change the content of the old one: <code>div.innerHTML = req.responseText;</code> and it blinks. How to avoid that?</p>
<p>One way to avoid flicker is called double-buffering. In Ajax, this can be done simply with 2 divs occupying the same space, one of them with the style 'display: none', the other 'display: inline'. Always write to the invisible one, and then swap display styles. If the divs have absolute positioning and size, there is absolutely no chance for flicker, and even if they don't, you can hardly do better.</p>
<p>It blinks because you're completely replacing the table ... if you add rows to or delete rows from the existing table and then load your AJAX data into the resulting table it won't blink.</p>
23,840
<p>I have an intel assembly assignment. I need to write a calculator which uses 2 stacks. For example, i have an expression like 23+4/2^4$ .So that $ indicates the end of expression. What I will do is to have two stacks, one for numbers, one for operators and push and pop them according to the operator precedence.</p> <p>What I need is how can I use 2 stacks for two different purpose at the same time. As long as I know esp register indicates the place for variables in the stack to pop the last or to push a new one. But if I only have one esp register, how can I have two stacks?</p> <p>Thanks in advance... </p>
<p>I think what you're looking for is Dijkstra's shunting algorithm.</p> <p>I have solved it without using stacks during interpretation, only during execution as described <a href="http://www.guge.net/?p=3#more-3" rel="nofollow noreferrer">in my blog.</a></p> <p>As for making extra stacks, it is quite easy. All a stack is, is really just an area of memory with a pointer to the top and bottom. Every time you push, you increment the top pointer, every time you pop you decrement the top pointer.</p>
<p>So, am I right to create two stacks like this:</p> <pre><code>mov ecx,256 L1: call ReadInt push eax ;push the integer to where esp=1 points add esp,ecx ;esp=1+256=257, now esp points to 257. call ReadChar ;read operand cmp al,endChar ;compare with end sign=$ je next push al ;push operand to where esp=257 points sub esp,ecx ;esp=257-256=1, now esp is in the original position loop L1 next: ... </code></pre> <p>Of course the comments are for the first loop.</p> <p>BTW, I got an "1>..\main.asm(46) : error A2149:byte register cannot be first operand" error for (push al)? what's the matter?</p> <p>thanks...</p>
47,750
<p>I'm on a beginner level course in prolog, doing a map colouring problem. Here's my code.</p> <pre><code>col(Colors,Map,Coloring) :- checkMap(Colors,Map,Coloring). checkMap(Colors,[Country1:Country2],Coloring) :- goodColor(Country1:Country2,Coloring,Colors). checkMap(Colors,[Country1:Country2|Rest],Coloring) :- goodColor(Country1:Country2,Coloring,Colors), checkMap(Colors,Rest,Coloring). goodColor(Country1:Country2,Coloring,Colors) :- mem(Country1:Color1,Coloring),!, mem(Country2:Color2,Coloring),!, mem(Color1,Colors), mem(Color2,Colors), not(Color1=Color2). mem(Var,[Var|_]). mem(Var,[_|Rest]) :- mem(Var,Rest). </code></pre> <p>My output looks like this:</p> <pre><code>?- col([a,b,c],[1:2,1:3,2:3],X). X = [1:a, 2:b, 3:c|_G332] ; X = [1:a, 2:c, 3:b|_G332] ; X = [1:b, 2:a, 3:c|_G332] ; X = [1:b, 2:c, 3:a|_G332] ; X = [1:c, 2:a, 3:b|_G332] ; X = [1:c, 2:b, 3:a|_G332] ; fail. </code></pre> <p>Anyone know how I can get rid of the trailing variable? I know it's mostly cosmetic, but I don't see why it's there.</p>
<p>Using an incomplete data structure is a valid Prolog programming technique. If your intention is to use an incomplete data structure then one solution is:</p> <pre><code>ground_terms([H|T1],[H|T2]) :- ground(H), !, ground_terms(T1,T2). ground_terms(_,[]). </code></pre> <p>and change col as follows:</p> <pre><code>col(Colors,Map,Coloring) :- checkMap(Colors,Map,Coloring1), ground_terms(Coloring1,Coloring). </code></pre>
<p>The trailing variable is there because <code>mem(Var,[Var|_])</code> binds the unbound <code>Coloring</code> variable to <code>[Var|_]</code>.</p> <p>One way to avoid it is to accumulate the map coloring e.g (very quick and extremely dirty):</p> <pre><code>col(Colors,Map,Coloring) :- check(Colors,Map,[],Coloring). check(Colors,[],Coloring,Coloring). check(Colors,[Country1:Country2 | T],[],L) :- member(Color1,Colors), member(Color2,Colors), Color1 \== Color2, check(Colors,T,[Country1:Color1,Country2:Color2],L). check(Colors,[Country1:Country2 | T],Coloring,L) :- member(Country1:Color1,Coloring), member(Country2:Color2,Coloring),!, check(Colors,T,Coloring,L). check(Colors,[Country1:Country2 | T],Coloring,L) :- member(Country1:Color1,Coloring),!, member(Color2,Colors), not(member(_:Color2,Coloring)), check(Colors,T,[Country2:Color2|Coloring],L). check(Colors,[Country1:Country2 | T],Coloring,L) :- member(Country2:Color2,Coloring),!, member(Color1,Colors), not(member(_:Color1,Coloring)), check(Colors,T,[Country1:Color1|Coloring],L). </code></pre> <p>Its a much more 'procedural' approach than yours though :-(. There's probably a more elegant way...</p>
36,145
<p>I am trying to use MinGW to compile a C program under Windows XP. The gcc.exe gives the following error:</p> <p><strong>stdio.h : No such file or directory</strong></p> <p>The code (hello.c) looks like this:</p> <pre><code>#include &lt; stdio.h &gt; void main() { printf("\nHello World\n"); } </code></pre> <p>I use a batch file to call gcc. The batch file looks like this:</p> <pre><code>@echo off set OLDPATH=%PATH% set path=C:\devtools\MinGW\bin;%PATH% set LIBRARY_PATH=C:\devtools\MinGW\lib set C_INCLUDE_PATH=C:\devtools\MinGW\include gcc.exe hello.c set path=%OLDPATH% </code></pre> <p>I have tried the option <strong>-I</strong> without effect. What do I do wrong?</p>
<p>Try changing the first line to:</p> <pre><code>#include &lt;stdio.h&gt; </code></pre> <p>without the spaces. It is trying to look for a file called " stdio.h " with a space at the beginning and end.</p>
<p>You can use</p> <p>$ sudo apt-get install build-essential</p> <p>to solve this problem</p>
10,745
<p>Using Microsoft Visual Studio 98, Microsoft Visual C++ 6.0 SP6</p> <p>When running under the debugger, there's only one problem. If I pause the program and resume, everything's fine.</p> <p>The problem? When I hit a breakpoint, my program stops. But not in a good way; execution halts, I'm thrown out of debug mode into edit mode. All's fine until a breakpoint is hit. And I know it's hitting the breakpoint - I see a flash of the little yellow arrow pointing at the right line of code, local variables in the inspect window and the call stack in that window. And then I'm staring at the editor.</p> <p>This happens in all projects.</p> <p>I've uninstalled and re-installed MSVC6. It didn't help.</p> <p>I'm about to start over on a new PC; before I go that far, anyone know what I've done to this one?</p> <hr> <p>Note: MSVC6 is not my choice, but there are reasons. It's the tool I work with. And, we get to target NT4, so given 2008 can't target NT4 and 2005 has issues with MFC and NT4, MSVC6 it is.</p>
<p>Stop beating on VC6. It's old. The STL was updated in 1996 from HP code written in 1994. C++ was ratified in 1998.</p> <p>What is the code doing when you are breaking? Can you reduce the situation into a simple test. When I try that I usually find the cause. If you can do that so it still happens then I'll take a look at it for you. I too am unfortunate enough to use VC6 for my day to day work.</p> <p>Visual C++ Express 2008 can't be used in certain situations.</p>
<p>I haven't used MSVC6 in years, but I remember the debugger basically being a flaky piece of crap. Things like this would regularly happen for no apparent reason because it just didn't like your code that day.</p> <p>In addition to the debugger being a flaky piece of crap, the rest of it was too.</p> <p>It's STL implementation isn't threadsafe, it doesn't support very much of the C++ standard, and the IDE is sorely lacking in niceties. </p> <p>I'm pretty sure you also just simply can't use any versions of the Platform SDK from the last 5 years because it's too old to grok them. Not a good thing.</p> <p>You'd be mad to keep using it when there is <a href="http://www.microsoft.com/express/vc/" rel="nofollow noreferrer">Visual C++ Express 2008</a> which you can download for free.</p>
2,986
<p>What is the best jQuery status message plugin?</p> <p>I like <a href="http://plugins.jquery.com/project/jgrowl" rel="noreferrer">jGrowl</a> and <a href="http://plugins.jquery.com/project/purr" rel="noreferrer">Purr</a>, but jGrowl doesn't have the feature to remain sticky (not close automatially) and Purr doesn't seem to work right in IE 6.</p> <p>I would like to show messages like... the site is about to go down for maintenance, your such and such job has completed, and stuff like that.</p>
<p>jGrowl does look to have sticky - see sample 2 in the demo page:</p> <p><a href="https://github.com/stanlemon/jGrowl" rel="nofollow noreferrer">https://github.com/stanlemon/jGrowl</a></p> <p>...ah - or did you mean after the page has reloaded?</p> <p>I would then handle this on the server side - i.e. include a sitedown.js that triggers the growl notice each time any page is visited.</p>
<p>There is a pretty nice humanized message one here: <a href="http://www.websanova.com/plugins/humanmsg/jquery#websanova" rel="nofollow">http://www.websanova.com/plugins/humanmsg/jquery#websanova</a></p>
24,633
<p>I know that I can share files using Shared Folders in Virtual PC, but this method seems to have pretty poor performance. Is there another method to share files that provides better performance? (Besides using something other than Virtual PC)</p>
<p>The best way to do it is probably set up proper bridge network connection between host machine and VM.</p>
<p>Using VirtualBox, I had problems setting up shared folders (I tried setting it up, and it wasn't working intuitively right away, so I got fed up with it). Thus, I just ftp'ed to the host OS (which I already had set up since I was on Linux), and transfered the file that way.</p> <p>I would suggest timing transferring a reasonably sized file via shared folders, and then time it again using FTP... if it's faster, that's your solution :-)</p> <p>Sorry I can't give actual performance metrics on that!</p>
18,239
<p>Can anyone recommend a good repository viewer for Git, similar to gitk, that works on Mac OS X Leopard? (I'm not saying gitk doesn't work)</p> <p>Of course I would like a native Mac application, but as I haven't found any, what are the best options to gitk?</p> <p>I know about gitview, but I'm looking forward to evaluate as many alternatives as possible.</p> <p><a href="http://sourceforge.net/projects/gitview" rel="noreferrer">http://sourceforge.net/projects/gitview</a></p>
<p>There's also <a href="http://www.gitx.org" rel="noreferrer">gitx</a>, it's progressing well and under active development (multiple commits per day).</p>
<p>You should checkout Sprout (formerly GitMac). <a href="http://sproutmacapp.com" rel="nofollow">http://sproutmacapp.com</a> it focuses on making Git easy, and browsing and committing changes in your projects</p> <p><a href="http://sproutmacapp.com" rel="nofollow">http://sproutmacapp.com</a> </p>
4,954
<p>So, I'd like to be able to set the max log file size to 64M, but after doing so with <code>innodb_log_file_size=64M</code> MySQL starts OK, but nothing seems to work properly. </p> <p><strong>EDIT:</strong> and by properly I mean not at all. Setting other InnoDB variables aren't causing any problems.</p> <p>How should I go about troubleshooting this one?</p>
<p>Make sure MySQL shuts down cleanly, and delete (or move elsewhere) all <code>ib_logfile*</code> files from MySQL data directory (<code>/var/lib/mysql/</code> usually).</p> <p>I've tested it and worked for me. Here's <a href="http://mysqldatabaseadministration.blogspot.com/2007/04/innodb-performance-optimization.html" rel="nofollow noreferrer">source of this hint</a>.</p> <p>InnoDB reports some errors in <code>show table status</code> comment field. You'll find other problems in MySQL error log (<code>hostname.err</code> in MySQL data directory).</p>
<p>Before changing the <a href="http://dev.mysql.com/doc/refman/5.6/en/innodb-parameters.html#sysvar_innodb_log_file_size" rel="nofollow"><strong>innodb_log_file_size</strong></a>, you must flush all remaining transactional data out of it. You simply set <a href="http://dev.mysql.com/doc/refman/5.6/en/innodb-parameters.html#sysvar_innodb_fast_shutdown" rel="nofollow"><strong>innodb_fast_shutdown</strong></a> to 0 or 2.</p> <ul> <li>innodb_fast_shutdown = 0 : InnoDB does a slow shutdown, a full purge and an insert buffer merge before shutting down</li> <li>innodb_fast_shutdown = 2 : InnoDB flushes its logs and shuts down cold, as if MySQL had crashed; no committed transactions are lost, but the crash recovery operation makes the next startup take longer.</li> </ul> <p>In light of this, this is how you handle it</p> <pre><code>mysql -ANe"SET GLOBAL innodb_fast_shutdown = 2" vi /etc/my.cnf # Change innodb_log_file_size = 64M service mysql stop # Stop MySQL rm /var/lib/mysql/ib_logfile0 # Delete log file 1 rm /var/lib/mysql/ib_logfile1 # Delete log file 2 service mysql start # Start MySQL </code></pre>
40,630
<p>I am a firm believer in the idea that one of the most important things you get from learning a new language is not how to use a new language, but the knowledge of concepts that you get from it. I am not asking how important or useful you think Assembly is, nor do I care if I never use it in any of my real projects. </p> <p>What I want to know is what concepts of Assembly do you think are most important for any general programmer to know? It doesn't have to be directly related to Assembly - it can also be something that you feel the typical programmer who spends all their time in higher-level languages would not understand or takes for granted, such as the CPU cache.</p>
<p>I think assembly language can teach you lots of little things, as well as a few big concepts.</p> <p>I'll list a few things I can think of here, but there is no substitute for going and learning and using both x86 and a RISC instruction set.</p> <p>You probably think that integer operations are fastest. If you want to find an integer square root of an integer (i.e. floor(sqrt(i))) it's best to use an integer-only approximation routine, right?</p> <p>Nah. The math coprocessor (on x86 that is) has a <strong>fsqrt</strong> instruction. Converting to float, taking the square root, and converting to int again is faster than an all-integers algorithm.</p> <p>Then there are things like accessing memory that you can follow, but not properly apprecatiate, until you've delved into assembly. Say you had a linked list, and the first element in the list contains a variable that you will need to access frequently. The list is reordered rarely. Well, each time you need to access that variable, you need to load the pointer to the first element in the list, then using that, load the variable (assuming you can't keep the address of the variable in a register between uses). If you instead stored the variable outside of the list, you only need a single load operation.</p> <p>Of course saving a couple of cycles here and there is usually not important these days. But if you plan on writing code that needs to be fast, this kind of knowledge can be applied both with inline assembly and generally in other languages.</p> <p>How about calling conventions? (Some assemblers take care of this for you - Real Programmers don't use those.) Does the caller or callee clean up the stack? Do you even use the stack? You can pass values in registers - but due to the funny x86 instruction set, it's better to pass certain things in certain registers. And which registers will be preserved? One thing C compilers can't really optimise by themselves is calls.</p> <p>There are little tricks like PUSHing a return address and then JMPing into a procedure; when the procedure returns it will go to the PUSHed address. This departure from the usual way of thinking about function calls is another one of those "states of enlightenment". If you were ever to design a programming language with innovative features, you ought to know about funny things that the hardware is capable of.</p> <p>A knowledge of assembly language teaches you architecture-specific things about computer security. How you might exploit buffer overflows, or break into kernel mode, and how to prevent such attacks.</p> <p>Then there's the ubercoolness of self-modifying code, and as a related issue, mechanisms for things such as relocations and applying patches to code (this needs investigation of machine code as well).</p> <p>But all these things need the right sort of mind. If you're the sort of person who can put</p> <pre><code>while(x--) { ... } </code></pre> <p>to good use once you learn what it does, but would find it difficult to work out what it does by yourself, then assembly language is probably a waste of your time.</p>
<p>Nowadays, x86 asm is not a direct line to the guts of the CPU, but more of an API. The assembler opcodes you write are themselves are compiled into a completely different instruction-set, rearranged, rewritten, fixed-up and generally mangled beyond recognition.</p> <p>So it's not like learning assembler gives you a fundamental insight into what's going on inside the CPU. IMHO, more important than learning assembler is to get a good understanding of how the target CPU and the memory hierarchy works.</p> <p><a href="http://lwn.net/Articles/250967/" rel="nofollow noreferrer">This</a> series of articles covers the latter topic pretty thoroughly.</p>
17,682
<p>I have a template in word (.docx) format and want to replace some placeholders in this template with my own data, do you know where I can find the right classes for this project? It would be nice for me to know the namespace. Are there any newer classes for handling word documents in the docx format (xml) than the com classes? Thank you for all your answers, I hope someone can help me with my problem.</p> <p>greets </p> <p>Sebastian</p>
<p>The new office formats (docx, xlsx, etc) are zip files that contain a collection of xml files. With that in mind you have a couple of approaches.</p> <ol> <li><p>You can use the Open XML SDK located at <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=AD0B72FB-4A1D-4C52-BDB5-7DD7E816D046&amp;displaylang=en" rel="noreferrer">http://www.microsoft.com/downloads/details.aspx?FamilyId=AD0B72FB-4A1D-4C52-BDB5-7DD7E816D046&amp;displaylang=en</a></p></li> <li><p>You can unzip the docx file, do a search and replace for your tokens, and zip it back up.</p></li> </ol> <p>There is a website at <a href="http://openxmldeveloper.org" rel="noreferrer">openxmldeveloper.org</a> that is just for this kind of thing. Also, bear in mind that they are already shipping a beta version 2 of the SDK.</p>
<p>By the way using xml I found this solution that finds ALL sdt-nodes</p> <pre><code> NameTable nt = new NameTable(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); nsManager.AddNamespace("w", wordmlNamespace); XmlDocument xDoc = new XmlDocument(); xDoc.Load(doc.MainDocumentPart.GetStream()); XmlNodeList nodeList = xDoc.SelectNodes(@"./w:document/w:body//w:sdt", nsManager); </code></pre> <p>It works but doesn't the Open XML Format SDK 2.0 give me any chance for this?</p>
22,029
<p>I would like to replicate a MSSQL 2005 db (hosting through a shared hosting provider) directly on an integration server for development purposes. MSSQL server provides quite a few ways of performing data replication, but I am not sure that any of them is compatible with a typical shared hosting environment.</p> <p>The idea would be to update the database once a day or so, much better if it can be done incrementally. Any idea how to proceed?</p>
<p>There are couple of ways of doing it.</p> <ol> <li><p>Use SQL Server 2005 copy function, but it would fail if SQL Agent is not ruining or there is any permission restriction - mostly like to happen with shared hosting.</p></li> <li><p>Use SQL Server backup/restore: the problem is usually you don't have access to the Database server file system with shared hosting.</p></li> <li><p>Replicate database schema on development server, then do a DTS to transfer data, you can save the DTS package ( even manually edit it if needed ) and set up a scheduled task in the development machine, it would automatically synchronize the database everyday, it may not be incrementally, depends on your database design/schema.</p></li> </ol> <p>option 3 seems to require more work but actually it is easy to set up and would save you a lot time in a long run.</p> <p>any other suggestions I would like to hear too.</p>
<p>Try the SQL Server Publishing Wizard 1.2, which is included with VS 2008. Or download the 1.1 version here:</p> <p><a href="http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A&amp;displaylang=en" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A&amp;displaylang=en</a></p>
46,147
<p>Suppose I have the following C code.</p> <pre><code>unsigned int u = 1234; int i = -5678; unsigned int result = u + i; </code></pre> <p>What implicit conversions are going on here, and is this code safe for all values of <code>u</code> and <code>i</code>? (Safe, in the sense that even though <em>result</em> in this example will overflow to some huge positive number, I could cast it back to an <em>int</em> and get the real result.)</p>
<p><strong>Short Answer</strong></p> <p>Your <code>i</code> will be <em>converted</em> to an unsigned integer by adding <code>UINT_MAX + 1</code>, then the addition will be carried out with the unsigned values, resulting in a large <code>result</code> (depending on the values of <code>u</code> and <code>i</code>).</p> <p><strong>Long Answer</strong></p> <p>According to the C99 Standard:</p> <blockquote> <p>6.3.1.8 Usual arithmetic conversions</p> <ol> <li>If both operands have the same type, then no further conversion is needed.</li> <li>Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.</li> <li>Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.</li> <li>Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.</li> <li>Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.</li> </ol> </blockquote> <p>In your case, we have one unsigned int (<code>u</code>) and signed int (<code>i</code>). Referring to (3) above, since both operands have the same rank, your <code>i</code> will need to be <em>converted</em> to an unsigned integer.</p> <blockquote> <p>6.3.1.3 Signed and unsigned integers</p> <ol> <li>When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.</li> <li>Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.</li> <li>Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.</li> </ol> </blockquote> <p>Now we need to refer to (2) above. Your <code>i</code> will be converted to an unsigned value by adding <code>UINT_MAX + 1</code>. So the result will depend on how <code>UINT_MAX</code> is defined on your implementation. It will be large, but it will not overflow, because:</p> <blockquote> <p>6.2.5 (9)</p> <p>A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.</p> </blockquote> <p><strong>Bonus: Arithmetic Conversion Semi-WTF</strong></p> <pre><code>#include &lt;stdio.h&gt; int main(void) { unsigned int plus_one = 1; int minus_one = -1; if(plus_one &lt; minus_one) printf("1 &lt; -1"); else printf("boring"); return 0; } </code></pre> <p>You can use this link to try this online: <a href="http://codepad.org/yPhYCMFO" rel="noreferrer">https://repl.it/repls/QuickWhimsicalBytes</a></p> <p><strong>Bonus: Arithmetic Conversion Side Effect</strong></p> <p>Arithmetic conversion rules can be used to get the value of <code>UINT_MAX</code> by initializing an unsigned value to <code>-1</code>, ie:</p> <pre><code>unsigned int umax = -1; // umax set to UINT_MAX </code></pre> <p>This is guaranteed to be portable regardless of the signed number representation of the system because of the conversion rules described above. See this SO question for more information: <a href="https://stackoverflow.com/questions/809227/is-it-safe-to-use-1-to-set-all-bits-to-true">Is it safe to use -1 to set all bits to true?</a></p>
<p><strong>Horrible Answers Galore</strong></p> <p><em>Ozgur Ozcitak</em></p> <blockquote> <p>When you cast from signed to unsigned (and vice versa) the internal representation of the number does not change. What changes is how the compiler interprets the sign bit.</p> </blockquote> <p>This is completely wrong.</p> <p><em>Mats Fredriksson</em></p> <blockquote> <p>When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.</p> </blockquote> <p>This is also wrong. Unsigned ints may be promoted to ints should they have equal precision due to padding bits in the unsigned type.</p> <p><em>smh</em></p> <blockquote> <p>Your addition operation causes the int to be converted to an unsigned int.</p> </blockquote> <p>Wrong. Maybe it does and maybe it doesn't.</p> <blockquote> <p>Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)</p> </blockquote> <p>Wrong. It is either undefined behavior if it causes overflow or the value is preserved.</p> <p><em>Anonymous</em></p> <blockquote> <p>The value of i is converted to unsigned int ...</p> </blockquote> <p>Wrong. Depends on the precision of an int relative to an unsigned int.</p> <p><em>Taylor Price</em></p> <blockquote> <p>As was previously answered, you can cast back and forth between signed and unsigned without a problem.</p> </blockquote> <p>Wrong. Trying to store a value outside the range of a signed integer results in undefined behavior.</p> <p><strong>Now I can finally answer the question.</strong></p> <p>Should the precision of int be equal to unsigned int, u will be promoted to a signed int and you will get the value -4444 from the expression (u+i). Now, should u and i have other values, you may get overflow and undefined behavior but with those exact numbers you will get -4444 <strong>[1]</strong>. This value will have type int. But you are trying to store that value into an unsigned int so that will then be cast to an unsigned int and the value that result will end up having would be (UINT_MAX+1) - 4444.</p> <p>Should the precision of unsigned int be greater than that of an int, the signed int will be promoted to an unsigned int yielding the value (UINT_MAX+1) - 5678 which will be added to the other unsigned int 1234. Should u and i have other values, which make the expression fall outside the range {0..UINT_MAX} the value (UINT_MAX+1) will either be added or subtracted until the result DOES fall inside the range {0..UINT_MAX) and no undefined behavior will occur.</p> <p><strong>What is precision?</strong></p> <p>Integers have padding bits, sign bits, and value bits. Unsigned integers do not have a sign bit obviously. Unsigned char is further guaranteed to not have padding bits. The number of values bits an integer has is how much precision it has.</p> <p>[Gotchas]</p> <p>The macro sizeof macro alone cannot be used to determine precision of an integer if padding bits are present. And the size of a byte does not have to be an octet (eight bits) as defined by C99.</p> <p><strong>[1]</strong> The overflow may occur at one of two points. Either before the addition (during promotion) - when you have an unsigned int which is too large to fit inside an int. The overflow may also occur after the addition even if the unsigned int was within the range of an int, after the addition the result may still overflow.</p>
7,342
<p>Just received my new Ender 3 v2. When using the Auto Home feature, the Y-axis motor drives the bed as far back as possible then the motor grinds for about 10-15 seconds. The Y-axis limit switch is not being depressed and the limit stop is about .5 inches away from the switch. The control unit locks at this point and must be power cycled to regain control. If I manually depress the limit switch then it appears to act normally.</p> <p>Clearly either the limit switch is way out of adjustment or the bed is not positioned properly. Can this be fixed or should I send it back as defective?</p>
<p>You could still get heat creep with a Bowden tube. It has different characteristics. Instead of jamming up in the direct drive, the filament can melt too far upwards into the heat break where it can refreeze and jam. The characteristic, if you can pull out the filament, is widened filament extending into the heat break.</p> <p>See <a href="https://3dprinting.stackexchange.com/questions/15732/air-printing-jamming-midway-through-raft-creation/15738#15738">Air printing/jamming midway through raft creation</a></p> <p>and</p> <p><a href="https://3dprinting.stackexchange.com/questions/15629/understanding-all-the-ways-to-avoid-heat-creep">What are ways to avoid heat creep?</a></p> <p>Adding fans to an enclosure improves the temperature control in the enclosure.</p>
<p><em>Answer created from octopus8's comments. If octopus8 wants to post their own answer, this wiki answer can be deleted.</em></p> <hr /> <p>185 °C is quite ok for several PLAs I have when printing slow.</p> <p>Honestly, I couldn't believe that the heat can go up the heatsink and Bowden tube to make extruder frame hot. So maybe your extruder's stepper motor is just getting hot heats up all metal elements (or a combination of both)? Did you replace only frame or also the stepper motor? Maybe the voltage is too high? I think voltages might be not calibrated well in factory, because my Z stepper in Ender 3 V2 also is getting really hot since I bought the printer (so far I added radiator, but I plan to regulate this voltage).</p> <blockquote> <p>The new tension arm is a bit tighter than I had it set on my old, but I can't imagine it's making enough resistance to overwork the motor without seeing other issues first.</p> </blockquote> <p>I agree with your judgement. Regarding the voltage: first I am not sure if my copy of v4.2.2 mainboard <a href="https://www.reddit.com/r/ender3/comments/ibqo8s/" rel="nofollow noreferrer">has TMC2208 stepper drivers, or some older HR4988</a>. I would need to determine that first, then find a valid formula for Vref. Actual voltage is tuned using potentiometer next to corner of stepper's small radiator. You can <a href="https://marlin.crc.id.au/faq/Ender%203%20V2/#vref" rel="nofollow noreferrer">see here an example of this process</a>. One problem is that Ender 3 V2 has the mainboard accessible from the bottom, so I would need something like garage pit to operate...</p> <p>As you can see, it is important to not touch the screwdriver's metal bar, and anyhow include your body's capacity to this circuit, or you may break things. There are also ceramic screwdrivers - but I already bought two and still my best option is sculpted from 3mm filament. Plastic or ceramic tool will need you to measure voltage separately from turning potentiometer. So the idea of connecting voltmeter to small metal screwdriver is very handy, but you have to be careful to touch only plastic parts.</p>
1,888
<p>I have (simplified for the example) a table with the following data</p> <pre><code>Row Start Finish ID Amount --- --------- ---------- -- ------ 1 2008-10-01 2008-10-02 01 10 2 2008-10-02 2008-10-03 02 20 3 2008-10-03 2008-10-04 01 38 4 2008-10-04 2008-10-05 01 23 5 2008-10-05 2008-10-06 03 14 6 2008-10-06 2008-10-07 02 3 7 2008-10-07 2008-10-08 02 8 8 2008-10-08 2008-11-08 03 19 </code></pre> <p>The dates represent a period in time, the ID is the state a system was in during that period and the amount is a value related to that state.</p> <p>What I want to do is to aggregate the Amounts for <em>adjacent</em> rows with the <em>same</em> ID number, but keep the same overall sequence so that contiguous runs can be combined. Thus I want to end up with data like:</p> <pre><code>Row Start Finish ID Amount --- --------- ---------- -- ------ 1 2008-10-01 2008-10-02 01 10 2 2008-10-02 2008-10-03 02 20 3 2008-10-03 2008-10-05 01 61 4 2008-10-05 2008-10-06 03 14 5 2008-10-06 2008-10-08 02 11 6 2008-10-08 2008-11-08 03 19 </code></pre> <p>I am after a T-SQL solution that can be put into a SP, however I can't see how to do that with simple queries. I suspect that it may require iteration of some sort but I don't want to go down that path.</p> <p>The reason I want to do this aggregation is that the next step in the process is to do a SUM() and Count() grouped by the unique ID's that occur within the sequence, so that my final data will look something like:</p> <pre><code>ID Counts Total -- ------ ----- 01 2 71 02 2 31 03 2 33 </code></pre> <p>However if I do a simple </p> <pre><code>SELECT COUNT(ID), SUM(Amount) FROM data GROUP BY ID </code></pre> <p>On the original table I get something like</p> <pre><code>ID Counts Total -- ------ ----- 01 3 71 02 3 31 03 2 33 </code></pre> <p>Which is not what I want.</p>
<p>If you read the book "Developing Time-Oriented Database Applications in SQL" by <a href="http://www.cs.arizona.edu/~rts/" rel="nofollow noreferrer">R T Snodgrass</a> (the pdf of which is available from his web site under publications), and get as far as Figure 6.25 on p165-166, you will find the non-trivial SQL which can be used in the current example to group the various rows with the same ID value and continuous time intervals.</p> <p><em>The query development below is close to correct, but there is a problem spotted right at the end, that has its source in the first SELECT statement. I've not yet tracked down why the incorrect answer is being given.</em> [If someone can test the SQL on their DBMS and tell me whether the first query works correctly there, it would be a great help!]</p> <p>It looks something like:</p> <pre><code>-- Derived from Figure 6.25 from Snodgrass "Developing Time-Oriented -- Database Applications in SQL" CREATE TABLE Data ( Start DATE, Finish DATE, ID CHAR(2), Amount INT ); INSERT INTO Data VALUES('2008-10-01', '2008-10-02', '01', 10); INSERT INTO Data VALUES('2008-10-02', '2008-10-03', '02', 20); INSERT INTO Data VALUES('2008-10-03', '2008-10-04', '01', 38); INSERT INTO Data VALUES('2008-10-04', '2008-10-05', '01', 23); INSERT INTO Data VALUES('2008-10-05', '2008-10-06', '03', 14); INSERT INTO Data VALUES('2008-10-06', '2008-10-07', '02', 3); INSERT INTO Data VALUES('2008-10-07', '2008-10-08', '02', 8); INSERT INTO Data VALUES('2008-10-08', '2008-11-08', '03', 19); SELECT DISTINCT F.ID, F.Start, L.Finish FROM Data AS F, Data AS L WHERE F.Start &lt; L.Finish AND F.ID = L.ID -- There are no gaps between F.Finish and L.Start AND NOT EXISTS (SELECT * FROM Data AS M WHERE M.ID = F.ID AND F.Finish &lt; M.Start AND M.Start &lt; L.Start AND NOT EXISTS (SELECT * FROM Data AS T1 WHERE T1.ID = F.ID AND T1.Start &lt; M.Start AND M.Start &lt;= T1.Finish)) -- Cannot be extended further AND NOT EXISTS (SELECT * FROM Data AS T2 WHERE T2.ID = F.ID AND ((T2.Start &lt; F.Start AND F.Start &lt;= T2.Finish) OR (T2.Start &lt;= L.Finish AND L.Finish &lt; T2.Finish))); </code></pre> <p>The output from that query is:</p> <pre><code>01 2008-10-01 2008-10-02 01 2008-10-03 2008-10-05 02 2008-10-02 2008-10-03 02 2008-10-06 2008-10-08 03 2008-10-05 2008-10-06 03 2008-10-05 2008-11-08 03 2008-10-08 2008-11-08 </code></pre> <p><strong>Edited</strong>: There's a problem with the penultimate row - it should not be there. And I'm not clear (yet) where it is coming from.</p> <p>Now we need to treat that complex expression as a query expression in the FROM clause of another SELECT statement, which will sum the amount values for a given ID over the entries that overlap with the maximal ranges shown above.</p> <pre><code>SELECT M.ID, M.Start, M.Finish, SUM(D.Amount) FROM Data AS D, (SELECT DISTINCT F.ID, F.Start, L.Finish FROM Data AS F, Data AS L WHERE F.Start &lt; L.Finish AND F.ID = L.ID -- There are no gaps between F.Finish and L.Start AND NOT EXISTS (SELECT * FROM Data AS M WHERE M.ID = F.ID AND F.Finish &lt; M.Start AND M.Start &lt; L.Start AND NOT EXISTS (SELECT * FROM Data AS T1 WHERE T1.ID = F.ID AND T1.Start &lt; M.Start AND M.Start &lt;= T1.Finish)) -- Cannot be extended further AND NOT EXISTS (SELECT * FROM Data AS T2 WHERE T2.ID = F.ID AND ((T2.Start &lt; F.Start AND F.Start &lt;= T2.Finish) OR (T2.Start &lt;= L.Finish AND L.Finish &lt; T2.Finish)))) AS M WHERE D.ID = M.ID AND M.Start &lt;= D.Start AND M.Finish &gt;= D.Finish GROUP BY M.ID, M.Start, M.Finish ORDER BY M.ID, M.Start; </code></pre> <p>This gives:</p> <pre><code>ID Start Finish Amount 01 2008-10-01 2008-10-02 10 01 2008-10-03 2008-10-05 61 02 2008-10-02 2008-10-03 20 02 2008-10-06 2008-10-08 11 03 2008-10-05 2008-10-06 14 03 2008-10-05 2008-11-08 33 -- Here be trouble! 03 2008-10-08 2008-11-08 19 </code></pre> <p><strong>Edited</strong>: This is <em>almost</em> the correct data set on which to do the COUNT and SUM aggregation requested by the original question, so the final answer is:</p> <pre><code>SELECT I.ID, COUNT(*) AS Number, SUM(I.Amount) AS Amount FROM (SELECT M.ID, M.Start, M.Finish, SUM(D.Amount) AS Amount FROM Data AS D, (SELECT DISTINCT F.ID, F.Start, L.Finish FROM Data AS F, Data AS L WHERE F.Start &lt; L.Finish AND F.ID = L.ID -- There are no gaps between F.Finish and L.Start AND NOT EXISTS (SELECT * FROM Data AS M WHERE M.ID = F.ID AND F.Finish &lt; M.Start AND M.Start &lt; L.Start AND NOT EXISTS (SELECT * FROM Data AS T1 WHERE T1.ID = F.ID AND T1.Start &lt; M.Start AND M.Start &lt;= T1.Finish)) -- Cannot be extended further AND NOT EXISTS (SELECT * FROM Data AS T2 WHERE T2.ID = F.ID AND ((T2.Start &lt; F.Start AND F.Start &lt;= T2.Finish) OR (T2.Start &lt;= L.Finish AND L.Finish &lt; T2.Finish))) ) AS M WHERE D.ID = M.ID AND M.Start &lt;= D.Start AND M.Finish &gt;= D.Finish GROUP BY M.ID, M.Start, M.Finish ) AS I GROUP BY I.ID ORDER BY I.ID; id number amount 01 2 71 02 2 31 03 3 66 </code></pre> <p><strong>Review</strong>: Oh! Drat...the entry for 3 has twice the 'amount' that it should have. Previous 'edited' parts indicate where things started to go wrong. It looks as though either the first query is subtly wrong (maybe it is intended for a different question), or the optimizer I'm working with is misbehaving. Nevertheless, there should be an answer closely related to this that will give the correct values.</p> <p>For the record: tested on IBM Informix Dynamic Server 11.50 on Solaris 10. However, should work fine on any other moderately standard-conformant SQL DBMS.</p>
<p>Well I decided to go down the iteration route using a mixture of joins and cursors. By JOINing the data table against itself I can create a link list of only those records that are consecutive. </p> <pre><code>INSERT INTO #CONSEC SELECT a.ID, a.Start, b.Finish, b.Amount FROM Data a JOIN Data b ON (a.Finish = b.Start) AND (a.ID = b.ID) </code></pre> <p>Then I can unwind the list by iterating over it with a cursor, and doing updates back to the data table to adjust (And delete the now extraneous records from the Data table)</p> <pre><code>DECLARE CCursor CURSOR FOR SELECT ID, Start, Finish, Amount FROM #CONSEC ORDER BY Start DESC @Total = 0 OPEN CCursor FETCH NEXT FROM CCursor INTO @ID, @START, @FINISH, @AMOUNT WHILE @FETCH_STATUS = 0 BEGIN @Total = @Total + @Amount @Start_Last = @Start @Finish_Last = @Finish @ID_Last = @ID DELETE FROM Data WHERE Start = @Finish FETCH NEXT FROM CCursor INTO @ID, @START, @FINISH, @AMOUNT IF (@ID_Last&lt;&gt; @ID) OR (@Finish&lt;&gt;@Start_Last) BEGIN UPDATE Data SET Amount = Amount + @Total WHERE Start = @Start_Last @Total = 0 END END CLOSE CCursor DEALLOCATE CCursor </code></pre> <p>This all works and has acceptable performance for typical data that I am using.</p> <p>I did find one small issue with the above code. Originally I was updating the Data table on each loop through the cursor. But this didn't work. It seems that you can only do one update on a record, and that multiple updates (in order to keep adding data) revert back to the reading the original contents of the record.</p>
29,144
<p>We are using trac and are really satisfied with it. However, out of the box, trac is best suited for single-project environments only. I'd be interested to hear about the various approaches people take to make it work with multiple projects nevertheless and their experiences with them. Are there any plugins to recommend? Any patches, tweaks or whatnots? Are you maybe even using an entirely different bug-tracking system that offers all of trac's functionality plus multi-project support?</p> <p>We recently started managing a second project ourselves which generally works okay but also has some drawbacks, especially where the two projects overlap because of common library code we wrote that is used in both projects. How do you handle this?</p> <p>(I'll attach our own current approach as an answer to this post.)</p>
<p>The approach we took is to create another trac environment for each new project and set up <a href="http://trac.edgewall.org/wiki/InterTrac" rel="noreferrer">InterTrac</a> links for simpler cross-referencing between the two. We also use a common base <a href="http://trac.edgewall.org/wiki/TracIni" rel="noreferrer">Trac.ini</a> file via the [inherit] directive.</p> <p>Besides the ambiguity issues with shared code mentioned in the question, this has a couple of drawbacks that may or may not affect you, depending on the nature of your projects and your workflow:</p> <ul> <li>creating new projects is not an easy process; it can not be done via the browser interface</li> <li>ticket numbers are not unified: each new project environment starts fresh from #1 - at least with InterTrac aliases you can easily disambiguate them</li> <li>you have to take extra care when installing and configuring plugins so they will be installed and configured for all environments</li> </ul>
<p>Same feeling here, Trac is really nice once configured properly. And it's easily hackable without touching any code. I only wish the wiki syntax were something more common, like markdown.</p> <p>We took the approach of using one Trac instance. We didn't need/want to use tight ACL and it has the benefit to keep all activity of developers in one place.</p> <p>For separating projects, we're essentially assigning bugs to various milestones. Every project has a short-term and long-term milestone. The short-term is used for fixing actual bugs and the long-term for major releases.</p> <p>Most of the other "new ticket" fields have been pruned, keeping the "type" and "severity" fields, which are the same on every project anyways.</p> <p>Reports are essentially limited to "My tickets", and the "Show Report" button has been tweaked to directly access your tickets.</p> <p>Workflow has also been adapted to add an intermediate "testing" status, so that QA can guarantee the fixing.</p> <p>Email configuration has been tweaked to not flood the mailboxes, so that developers actually read their assignments.</p> <p>With that in place, we have a pretty efficient tool. It took some time to get it right, but it is easy to change things if you know how to hack around and lookup things on google.</p>
33,629
<p>What do search engine bots use as a starting point? Is it DNS look-up or do they start with some fixed list of well-know sites? Any guesses or suggestions?</p>
<p>Your question can be interpreted in two ways:</p> <p>Are you asking where search engines start their crawl from in general, or where they start to crawl a particular site?</p> <p>I don't know how the big players work; but if you were to make your own search engine you'd probably seed it with popular portal sites. <a href="https://web.archive.org/web/20080916124519/http://www.dmoz.org/" rel="nofollow noreferrer">DMOZ.org</a> seems to be a popular starting point. Since the big players have so much more data than we do they probably start their crawls from a variety of places.</p> <p>If you're asking where a SE starts to crawl your particular site, it probably has a lot to do with which of your pages are the most popular. I imagine that if you have one super popular page that lots of other sites link to, then that would be the page that SEs starts will enter from because there are so many more entry points from other sites.</p> <p>Note that I am not in SEO or anything; I just studied bot and SE traffic for a while for a project I was working on.</p>
<p>You can submit your site to search engines using their <a href="http://www.google.com/addurl/" rel="nofollow noreferrer">site submission forms</a> - this will get you into their system. When you actually get crawled after that is impossible to say - from experience it's usually about a week or so for an initial crawl (homepage, couple of other pages 1-link deep from there). You can increase how many of your pages get crawled and indexed using clear semantic link structure and submitting a <a href="https://www.google.com/webmasters/tools/docs/en/protocol.html" rel="nofollow noreferrer">sitemap</a> - these allow you to list all of your pages, and weight them relative to one another, which helps the search engines understand how important you view each part of site relative to the others.</p> <p>If your site is linked from other crawled websites, then your site will also be crawled, starting with the page linked, and eventually spreading to the rest of your site. This can take a long time, and depends on the crawl frequency of the linking sites, so the url submission is the quickest way to let google know about you!</p> <p>One tool I can't recommend highly enough is the <a href="http://www.google.com/webmaster" rel="nofollow noreferrer">Google Webmaster Tool</a>. It allows you to see how often you've been crawled, any errors the googlebot has stumbled across (broken links, etc) and has a host of other useful tools in there. </p>
6,271
<p>When installing and using a new hotend for the first time, which steps of action should be taken before. This will probably be more applicable to chinese clones than to authentic products (is the statement true?): <strong>Should a certain cleaning procedure be carried out</strong> (removing swarf/shavings for example)? <strong>Should mechanical precision be controlled and if necessary improved</strong> (de-edging and nozzle size are two things I could think of)?</p> <p>I know the topic <a href="https://3dprinting.stackexchange.com/questions/233/how-should-i-clean-my-extruder-when-changing-materials">How should I clean my extruder when changing materials?</a>, which is a nice addon read, but I am concerned about brand-new extruders.</p>
<p>I haven't done anything special to set up mine. But it's probably worth doing a general cleaning. I'd swab it off with alcohol, including running a q-tip or similar inside the fiber feed path. Then blow out the nozzle with compressed air to make sure it's clear.</p> <p>You could measure the nozzle diameter by fitting fine drill bits in to see which is the largest one the passes through freely. Be sure to measure how much fiber your extruder <em>really</em> takes in when you ask it to extrude a certain length -- but that's about the extruder, not the hotend per se.</p> <p>Finally, I'd check the insulation, if any. I got a couple hot ends that had big gaps in/around the insulation. I've found that "high-temperature gasket maker" is great for improving insulation (depends, of course, on the shape and design of the specific hot end.</p>
<p>I haven't done anything special to set up mine. But it's probably worth doing a general cleaning. I'd swab it off with alcohol, including running a q-tip or similar inside the fiber feed path. Then blow out the nozzle with compressed air to make sure it's clear.</p> <p>You could measure the nozzle diameter by fitting fine drill bits in to see which is the largest one the passes through freely. Be sure to measure how much fiber your extruder <em>really</em> takes in when you ask it to extrude a certain length -- but that's about the extruder, not the hotend per se.</p> <p>Finally, I'd check the insulation, if any. I got a couple hot ends that had big gaps in/around the insulation. I've found that "high-temperature gasket maker" is great for improving insulation (depends, of course, on the shape and design of the specific hot end.</p>
167
<p>I need to insert records into a table that has no primary key using LINQ to SQL. The table is poorly designed; I have NO control over the table structure. The table is comprised of a few varchar fields, a text field, and a timestamp. It is used as an audit trail for other entities.</p> <p>What is the best way to accomplish the inserts? Could I extend the Linq partial class for this table and add a "fake" key? I'm open to any hack, however kludgey.</p>
<p>LINQ to SQL isn't meant for this task, so don't use it. Just warp the insert into a stored procedure and add the procedure to your data model. If you can't do that, write a normal function with a bit of in-line SQL.</p>
<p>You might use the <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.executecommand.aspx" rel="nofollow noreferrer">DataContext.ExecuteCommand</a> method to run your own custom insert statement.</p> <p>Or, you might add a <a href="http://msdn.microsoft.com/en-us/library/bb386963.aspx" rel="nofollow noreferrer">primary key</a> to a column, this will allow the <a href="http://msdn.microsoft.com/en-us/library/bb399376.aspx" rel="nofollow noreferrer">objects to be tracked</a> for inserts/updates/deletes by the datacontext. This will work even if the column isn't really an enforced primary key in the database (how would linq know?). If you're only doing inserts and never re-use a primary key value in the same datacontext, you'll be fine.</p>
43,189
<p>I am using the ASP.Net plugin and control provided by <a href="http://recaptcha.net" rel="noreferrer">reCAPTCHA</a>. I can successfully get the control to work if the submit button on the web form is not in a validationgroup. There is no validationgroup attribute for the reCAPTCHA control. </p> <p>Has anybody had any success with this or any solutions to get the reCAPTCHA control to work when there is a validationgroup on the web form?</p>
<p>The reCAPTCHA ASP.NET plug-in is written to be backward-compatible with ASP.NET 1.1, which means the <code>ValidationGroup</code> concept (which is new in ASP.NET 2.0) is not supported. But the plug-in comes with <a href="http://code.google.com/p/recaptcha/downloads/list?q=label:aspnetlib-Latest" rel="nofollow noreferrer">downloadable source code</a>, so you can modify it yourself to support <code>ValidationGroup</code>. </p> <p>In ASP.NET 2.0, <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basevalidator_methods.aspx" rel="nofollow noreferrer">validators should inherit from <code>BaseValidator</code></a> and implement <code>IValidator</code>, which means you should change the RecaptchaControl type to inherit from <code>BaseValidator</code> instead of <code>WebControl</code>. You will then have to modify the code a bit to implement all methods and properties defined in <code>BaseValidator</code>. Then you can use this new control on your page instead, which now supports <code>ValidationGroup</code>.</p>
<p>See ReCaptchaImage and ReCaptchaValidator controls being part of Altairis Web UI Toolkit: <a href="http://altairiswebui.codeplex.com/" rel="nofollow">http://altairiswebui.codeplex.com/</a></p> <p>It's open source set of web components, containing quite decent and ASP.NET standards-compliant (if I may say it being the author :-) implementation of ReCaptcha for Web Forms.</p>
28,638
<p>I have been using PLA filament for two years now and have had good prints. ABS on the other hand has not been so good, so my choice of filament is PLA. </p> <p>I am getting ready to do a sign for the American Legion and the colors are black, blue, and red and are 0.8 mm thin. The black letters are 4" x 2.5", blue are 3" x 2" and the red are 7.75" x 5.5". I plan to treat them with UV protection spray and attach them with clear epoxy to white back lit Plexiglass. </p> <p>As the letters are quite thin, my question is how well will this hold up in the weather? The sign hangs on a pole that points east &amp; west so the letters will be facing north and south. The original was painted with spray paint and the red paint south side faded to the point you could hardly see it at all. The sign had been there for some time and was done at a professional sign company.</p>
<p>I printed a handle for a rather big rolling door in natural PLA (From Fabberparts) - no UV protection. It's on the weather side of the house and is exposed to direct sun half the day.</p> <p>And after three years cycling to all the German seasons it's still absolutely fine. Also, Wikipedia told me that PLA has good UV resistance - so you should be fine IMHO.</p> <p>Here is a good blog post about your question: <a href="https://www.iepas.ucar.edu/using-pla-for-long-term-outdoor-applications/" rel="nofollow noreferrer">Using PLA for Long-Term Outdoor Applications</a>.</p> <p>Update: After ~ 8 Years the door handle ist still fine.</p>
<p>Keep in mind that PLA has a much lower temperature point, where is starts getting flexible. I once had PLA-printed parts in my car in the summer for three hours and when I came back, they where bent. </p> <p>I don't know about the weather conditions in your local environment, but if you experience hot temperatures and your sign is hanging in direct sunlight, I would suggest to make sure you secure the letters against bending (e.g. cover them with a coat of epoxy or something like this).</p>
410
<p>Is there such a thing as unit test generation? If so...</p> <p>...does it work well? </p> <p>...What are the auto generation solutions that are available for .NET?</p> <p>...are there examples of using a technology like this?</p> <p>...is this only good for certain types of applications, or could it be used to replace all manually written unit testing?</p>
<p>Take a look at <a href="http://research.microsoft.com/Pex/" rel="noreferrer">Pex</a>. Its a Microsoft Research project. From the website:</p> <p><em>Pex generates Unit Tests from hand-written Parameterized Unit Tests through Automated Exploratory Testing based on Dynamic Symbolic Execution.</em></p> <h2>UPDATE for 2019:</h2> <p>As mentioned in the comments, Pex is now called <a href="https://learn.microsoft.com/en-us/visualstudio/test/generate-unit-tests-for-your-code-with-intellitest?view=vs-2019" rel="noreferrer">IntelliTest</a> and is a feature of Visual Studio Enterprise Edition. It supports emitting tests in MSTest, MSTest V2, NUnit, and xUnit format and it is extensible so you can use it with other unit test frameworks.</p> <p>But be aware of the following caveats:</p> <ul> <li>Supports only C# code that targets the .NET Framework. </li> <li>Does not support x64 configurations.</li> <li>Available in Visual Studio <strong>Enterprise Edition only</strong></li> </ul>
<p>I've used <a href="http://code.google.com/p/nstub/" rel="nofollow noreferrer">NStub</a> to stub out test for my classes. It works fairly well.</p>
17,221
<p>It seems to me that the size of hole in the nozzle shouldn't matter in and of itself. If you program in the layer height and line width, then the same amount of plastic has to be extruded, no matter what size the hole is in the nozzle. </p> <p>Of course I understand that, mechanically, the best results are got with the line width slightly larger than the nozzle size. We couldn't print a 0.3&nbsp;mm line with a 0.6&nbsp;mm nozzle, and trying to print a 1&nbsp;mm line with a 0.4&nbsp;mm nozzle probably wouldn't work well either. But in terms of what the actual G-code needs to do, the nozzle size doesn't seem to matter. After all, printers feed filament based on length/volume, so the size of the nozzle shouldn't impact the amount of plastic extruded. </p> <p>What prompted this question: I want to switch from a 0.4&nbsp;mm nozzle to a 0.8&nbsp;mm nozzle, but I cannot find out how to change the nozzle size in Cura. There are many bug reports about the nozzle size setting disappearing or not displaying in Cura, and I think that's my problem. However, in the troubleshooting threads, many people claim that you can just change the line width and ignore the nozzle size completely and the result will be the same. In other words, if I want to switch from 0.4 nozzle and 0.48 line width, to 0.8 nozzle and 1&nbsp;mm line width, I can just keep my slicer set to 0.4 nozzle size, but increase the line width to 1&nbsp;mm, and if I physically install a 0.8&nbsp;mm nozzle, it will do exactly the same thing. There are even Cura developers saying the nozzle size setting will be removed in a future version completely. </p> <p>This may depend on the way individual slicers work. Has anyone tried switching between say 0.4 and 0.6 nozzle settings, while leaving the line width the same (say 0.8&nbsp;mm line width for both), and see any differences in the G-code? I can't test this myself, because I can't change the nozzle size right now...</p>
<p>CNC kitchen tested various extrusion widths with various nozzles and in fact there's no difference, only the line width matters. <a href="https://www.cnckitchen.com/blog/big-nozzles-how-do-they-make-your-3d-prints-stronger" rel="nofollow noreferrer">https://www.cnckitchen.com/blog/big-nozzles-how-do-they-make-your-3d-prints-stronger</a></p> <p>Of course it's up to you to avoid too thick layers with small nozzles.</p>
<p>I’m using sli3r. It use nozzle size for some auto value like auto extrusion width which calculate by 105% of nozzle diameter and prevent some error like setting layer height greater than nozzle diameter.</p>
1,655
<p>Since yesterday, I am analyzing one of our project with <a href="http://www.ndepend.com/" rel="nofollow noreferrer">Ndepend</a> (free for most of its features) and more I am using it, and more I have doubt about the real value of this type of software (code-analysis software).</p> <p>Let me explain, The system build a report about the health of the system and class by Rank every metric. I thought it would be a good starting point to do modifications but most of the top result are here because they have over 100 lines inside the class (we have big headers and we do use VS comments styles) so it's not a big deal... than the number of Afferent Coupling level (CA) is always too high and this is almost very true for Interface that we used a lot... so at this moment I do not see something wrong but NDepend seem to do not like it (if you have suggestion to improve that tell me because I do not see the need for). It's the samething for the metric called "NOC" for Number of children that most of my Interface are too high...</p> <p>For the moment, the only very useful metric is the Cyclomatic Complexity...</p> <p><strong>My question is</strong> : Do you find is worth it to analyse code with Automatic Code Analyser like NDepend? If yes, how do you filter all information that I have mentionned that doesn't really show the real health of the system?</p>
<p>Not yet, but maybe soon. First, note that your suggested query will not work at all in LINQ to Entities, with or without the property, because, at present, it doesn't support Contains. The new version of the Entity Framework in .NET 4.0, however, is supposed to support custom methods in LINQ to Entities queries. You can see <a href="http://mschnlnine.vo.llnwd.net/d1/pdc08/WMV-HQ/TL20.wmv" rel="nofollow noreferrer">a video about this from PDC</a>. Essentially, you have to write the custom method twice; once in code, and once on your database (e.g., in a calculated field). See the video for more information.</p>
<p>Craig,</p> <p>Sarted watching the video, then realised it's over an hour long, so will have to watch it when i have more time. Just to let you know though.. <strong><em>Contains</em></strong> seems to be working ok for me, here's the SQL that's generated by Linq to Entities:</p> <pre><code>SELECT 1 AS [C1], [Extent1].[PeopleID] AS [PeopleID], [Extent1].[Forenames] AS [Forenames], [Extent1].[Surname] AS [Surname] FROM [dbo].[People] AS [Extent1] WHERE (CHARINDEX(N'Dave', [Extent1].[Forenames] + N' ' + [Extent1].[Surname])) &gt; 0 </code></pre> <p>It seems to work a treat. Using <strong><em>CHARINDEX</em></strong> to workout if the Concatinated field contains the entered text which is the above case was "<strong><em>Dave</em></strong>".</p> <p>Thanks Dave</p>
38,338
<p>I'm converting an application to use Java 1.5 and have found the following method:</p> <pre><code> /** * Compare two Comparables, treat nulls as -infinity. * @param o1 * @param o2 * @return -1 if o1&amp;lt;o2, 0 if o1==o2, 1 if o1&amp;gt;o2 */ protected static int nullCompare(Comparable o1, Comparable o2) { if (o1 == null) { if (o2 == null) { return 0; } else { return -1; } } else if (o2 == null) { return 1; } else { return o1.compareTo(o2); } } </code></pre> <p>Ideally I would like to make the method take two Comparables of the same type, is it possible to convert this and how? </p> <p>I thought the following would do the trick:</p> <pre><code>protected static &lt;T extends Comparable&gt; int nullCompare(T o1, T o2) { </code></pre> <p>but it has failed to get rid of a warning in IntelliJ "Unchecked call to 'compareTo(T)' as a member of raw type 'java.lang.Comparable'" on the line:</p> <pre><code>return o1.compareTo(o2); </code></pre>
<p>Change it to:</p> <pre><code>protected static &lt;T extends Comparable&lt;T&gt;&gt; int nullCompare(T o1, T o2) { </code></pre> <p>You need that because Comparable is itself a generic type.</p>
<p>I'm not sure that genericizing this method makes sense. Currently the method works on any kind of Comparable; if you genericize it you will have to implement it (with exactly the same code) multiple times. Sometimes it is possible to compare two objects that don't have a common ancestor, and any generic version won't allow this.</p> <p>By adding generics you won't add any safety to the code; any problems of safety will occur in the call to compareTo. What I would suggest is simply suppressing the warning. It's not really warning you about anything useful.</p>
8,358
<p>This question is about a Java JTree or a Window .Net Tree (Winforms) or an Adobe Flex Tree.</p> <p>In a client-server application (for Flex it's Web, really), I have a tree with hierarchical data (in a Windows Explorer type interface). Right now I lazily load up the tree as the user requests more data from the server. This is fine and will work up to about 750K nodes (empirically tested on .Net Winforms and Adobe Flex), but after that it gets sluggish. But the databases grow fast (mostly because users can paste in huge amounts of nodes) and a database of 20 million nodes is not at all unlikely.</p> <p>Should I be releasing data from the tree when a branch is collapsed so the Garbage Collector can release the memory? This is fine, but what if the users are not efficient and don't collapse branches? Should I do a memory management module that goes around closing branches that haven't been touched in a while?</p> <p>This all seems like a lot of work so as not to not run out of memory.</p> <p><strong>Edit:</strong> Should I release data on node collapse? If so, when? The weak-object cache idea is good, but should I just continue filling up the UI until it busts (maybe it's not a bad idea)?</p>
<p>PHP, Ruby On Rails, ASP.Net, or Java.</p> <p>It's a religious choce and it depends on who you ask.</p> <p>Everyone you ask will give you a different answer.</p> <p>You should ask yourself how you want to work, PHP java and ASP all let you write markup that is interspersed with code or code that writes the markup for you.</p> <p>To be honest it's subjective and no one will be able to give you a straight answer.</p> <p>Given your two options ASP is probably a better choice for industry though, there is a lot of money in it and C# is close enough to C/C++ for it to be readable.</p>
<p>.NET platform, without a doubt.</p> <p>Pick up RoR as a secondary.</p>
36,256
<p>Am I able to embed the .net runtime so that .net is not required on the host operating system? I was looking at doing this with Mono by looking here: <a href="http://mono-project.com/Embedding_Mono" rel="nofollow noreferrer">http://mono-project.com/Embedding_Mono</a> but seems to allude to using external modules to accomplish this. My goal is to have one single executable with no installed .net runtime. I do not know how this would be configured in my application to compile the native code, link the mono runtime- as well as compile the C# code and link that as well? </p>
<p>You can now <a href="http://tirania.org/blog/archive/2008/Nov-05.html" rel="nofollow noreferrer">statically compile Mono assemblies</a> as was just demonstrated at PDC. The purpose of doing this was to allow .Net applications to run on the iPhone, but this should work anywhere.</p> <p>There are some limitations to this; obviously, it can't depend on runtime-generated code, so Reflection.Emit is out.</p>
<p>This is not currently supported, and AFAIK there are no plans to change that status.</p> <p>There are some third party tools out there that try to do this for you, but last time I checked none were very good yet.</p>
34,003
<p>I am having an issue with SSH hanging on my Mac Book Pro. This only happens to me once I get home from work after I have used SSH while at work. The three factors I have narrowed the issue down to are SSH, our work AFS network drive and the method of network connectivity.</p> <p>At work we use an AFS drive with Kerberos Authentication to do all of our software development work on. I authenticate with Kerberos in order to gain access to the AFS drive where all my source code lives, but I open a local editor (Eclipse) which references the files on the AFS drive. Whenever I need to compile my code, I SSH in to my development server (which is also authenticated to the AFS drive) and compile from there. (Sanity Note: I know that it is a super wacky setup, but I promise I had NOTHING to do with it. I'm just making do with what I've got.)</p> <p>For my Network Preferences, I use the Automatic location all the time. For that configuration I have Built-in Ethernet en1 configured to use DHCP and our company's DNS server for when I'm at work (there is no wireless available). When I go home I connect to my home network via wireless, again using DHCP.</p> <p>I have a hunch that the AFS connection/Ethernet configuration is somehow the culprit here. Restarting the SSH daemon doesn't correct the problem. The only way I have found to correct the issue is by restarting the computer each time I want to use SSH. Keep in mind that I have no other (known) networking issues while at home after I've had the laptop at work. </p> <p>I have a co-worker who has reported to me the same issue on his MBP.</p> <p>I'm truly stumped on this one. Please provide some guidance. Thanks! </p>
<p>Can you be more specific about "SSH hanging"?</p> <p>It sounds like your ssh <strong>client</strong> hangs after losing the connection and you are unable to do anything in the terminal. To get around this, you can use the ssh escape character (default: ‘~’) to begin an escape sequence, and use the the '.' to terminate the connection.</p> <p>You can get a list of other ssh escape sequences using ~?, here's the one for OpenSSH SSH client:</p> <pre><code>Supported escape sequences: ~. - terminate connection ~B - send a BREAK to the remote system ~C - open a command line ~R - Request rekey (SSH protocol 2 only) ~^Z - suspend ssh ~# - list forwarded connections ~&amp; - background ssh (when waiting for connections to terminate) ~? - this message ~~ - send the escape character by typing it twice (Note that escapes are only recognized immediately after newline.) </code></pre> <p>If typing ~. does not work, it could be that you have the escape character disabled, in which case you can put</p> <pre><code>EscapeChar ~ </code></pre> <p>inside <em>~/.ssh/config</em> or <em>/etc/ssh_config</em></p> <p>Even when the escape character is disabled, you can simply pull up another Terminal window and type</p> <pre><code>killall ssh </code></pre> <p>to end all running ssh processes, allowing you to connect out again.</p> <p>Restarting the SSH daemon would not correct this problem because sshd allows other clients to connect in to your machine, and does not affect your ssh clients connecting out to some other machine.</p>
<p>Just a shot in the dark: I recently had problems using ssh after installing Rogue Amoeba Audio Hijack Pro. I could only use ssh as super user (sudo). An Update to 2.8.1 resolved the issue...</p> <p>Also see <a href="http://www.macobserver.com/article/2008/03/19.8.shtml" rel="nofollow noreferrer">http://www.macobserver.com/article/2008/03/19.8.shtml</a> for the issue.</p>
36,725
<p>I'm using the contentEditable attribute on a DIV element in Firefox 3.03. Setting it to true allows me to edit the text content of the DIV, as expected.</p> <p>Then, when I set contentEditable to "false", the div is no longer editable, also as expected. </p> <p>However the flashing caret (text input cursor) remains visible even though the text is no longer editable. The caret is now also visible when I click on most other text in the same page, even in normal text paragraphs.</p> <p>Has anyone seen this before? Is there any way to force the caret hidden? </p> <p>(When I either resize the browser or click within another application, and come back, the caret magically disappears.)</p>
<p>I've dealt with this and my workaround is clearing the selection when I disable contentEditable:</p> <pre><code>if ($.browser.mozilla) { // replace with browser detection of your choice window.getSelection().removeAllRanges(); } </code></pre> <p>I am actually removing the "contenteditable" attribute for browsers other than IE, rather than setting it to false:</p> <pre><code>if ($.browser.msie) { element.contentEditable = false; } else { $(element).removeAttr( 'contenteditable' ); } </code></pre> <p>The browsers manage the contentEditable attribute inconsistently and my testing revealed that this worked better overall. I don't remember if this contributed to fixing the caret problem, but I'm throwing it in here just in case.</p>
<p>The style attribute <code>-moz-user-input</code> can be used in Firefox to get the functionality <code>contenteditable=false</code> working. <br> The value assigned defines if user input is accepted. The possible values are </p> <pre><code>none : The element does not respond to user input. enabled : The element can accepts user input. This is default. disabled : The element does not accept user input. </code></pre> <p>E.g.: </p> <pre><code>// to disallow users to enter input &lt;asp:TextBox ID="uxFromDate" runat="server" style="-moz-user-input: disabled;"&gt;&lt;/asp:TextBox&gt; // to allow users to enter input &lt;asp:TextBox ID="uxFromDate" runat="server" style="-moz-user-input: enabled ;"&gt;&lt;/asp:TextBox&gt; </code></pre> <p>Refer to <a href="https://developer.mozilla.org/en/CSS/-moz-user-input" rel="nofollow noreferrer">https://developer.mozilla.org/en/CSS/-moz-user-input</a> for further reference.</p>
26,393
<p>Can you show sample code for reading a drive label or volume name in .NET? I get the sense this requires WMI, but I am loathe to "drop-down" into WMI because it is like dropping down into a string-based SQL query in the sense that certain objects may not exist on certain versions of OSes or the user may not have the right to query certain data. I will be happy to be convinced that I'm wrong about WMI ...</p>
<p>No WMI required. The following will get all volume labels:</p> <pre><code>var labels = from drive in DriveInfo.GetDrives() select drive.VolumeLabel </code></pre>
<p>You could use System.IO.DriveInfo to get the list of drives. See following example:</p> <p>Note: CDRom drive types do not have a volume name.</p> <pre><code>Using System.IO; . . . DriveInfo[] driveInfoList = DriveInfo.GetDrives(); foreach (DriveInfo drive in driveInfoList) { if (drive.DriveType != DriveType.CDRom) textBox1.Text += String.Format("Name:{0} Volume:{1}\r\n", drive.Name, drive.VolumeLabel); else textBox1.Text += String.Format("Name:{0}\r\n", drive. } </code></pre>
48,648
<p>I have an application where 2 threads are running... Is there any certanty that when I change a global variable from one thread, the other will notice this change? I don't have any syncronization or Mutual exclusion system in place... but should this code work all the time (imagine a global <strong>bool</strong> named <strong>dataUpdated</strong>):</p> <p>Thread 1:</p> <pre><code>while(1) { if (dataUpdated) updateScreen(); doSomethingElse(); } </code></pre> <p>Thread 2:</p> <pre><code>while(1) { if (doSomething()) dataUpdated = TRUE; } </code></pre> <p>Does a compiler like gcc optimize this code in a way that it doesn't check for the global value, only considering it value at compile time (because it nevers get changed at the same thred)?</p> <p>PS: Being this for a game-like application, it really doen't matter if there will be a read while the value is being written... all that matters is that the change gets noticed by the other thread.</p>
<p>Yes. No. Maybe.</p> <p>First, as others have mentioned you need to make dataUpdated volatile; otherwise the compiler may be free to lift reading it out of the loop (depending on whether or not it can see that doSomethingElse doesn't touch it).</p> <p>Secondly, depending on your processor and ordering needs, you may need memory barriers. volatile is enough to guarentee that the other processor will see the change eventually, but not enough to guarentee that the changes will be seen in the order they were performed. Your example only has one flag, so it doesn't really show this phenomena. If you need and use memory barriers, you should no longer need volatile</p> <p><a href="http://www.kernel.org/doc/Documentation/volatile-considered-harmful.txt" rel="noreferrer">Volatile considered harmful</a> and <a href="http://www.kernel.org/doc/Documentation/memory-barriers.txt" rel="noreferrer">Linux Kernel Memory Barriers</a> are good background on the underlying issues; I don't really know of anything similar written specifically for threading. Thankfully threads don't raise these concerns nearly as often as hardware peripherals do, though the sort of case you describe (a flag indicating completion, with other data presumed to be valid if the flag is set) is exactly the sort of thing where ordering matterns...</p>
<p>If the scope is right ( "extern", global, etc. ) then the change will be noticed. The question is when? And in what order?</p> <p>The problem is that the compiler <strong>can</strong> and frequently <strong>will</strong> re-order your logic to fill all it's concurrent pipelines as a performance optimization.</p> <p>It doesn't really show in your specific example because there aren't any other instructions around your assignment, but imagine functions declared after your bool assign execute <strong>before</strong> the assignment.</p> <p>Check-out <a href="http://en.wikipedia.org/wiki/Pipeline_stall#Eliminating_hazards" rel="nofollow noreferrer">Pipeline Hazard</a> on wikipedia or search google for "compiler instruction reordering"</p>
14,386
<p>In the past I have needed to create custom SOAP headers in a C# project that was using an imported WSDL web reference. I found a way to do it but I was never happy with it and I have sense wondered if there was a better way. What I did was create a header that derives from SoapHeader:</p> <pre><code>[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://model.test.net")] [System.Xml.Serialization.XmlRootAttribute("securitytoken", Namespace = "http://model.test.net", IsNullable = false)] public class SpecialHeader : SoapHeader { [System.Xml.Serialization.XmlTextAttribute()] public string aheadervalue; } </code></pre> <p>I then had to modify the code that was generated from the WSDL and add a referen ce to an instance of the new header and the following before each web call that I wanted to contain the custom header:</p> <pre><code>[System.Web.Services.Protocols.SoapHeaderAttribute("instancename", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut)] </code></pre> <p>Where "instancename" is the custom header's instance variable name in the generated class.</p> <p>This works fine except that any change in the WSDL requires that it all be done over again since it regenerates the class. In other languages the headers can be added outside of the generated code so maybe I'm missing the way that is done in C#. Are there better ways of doing this?</p>
<p>It seems that you are using .Net 2.0 and asmx webservices. Do you know that there is a framework called WCF (Windows Communication Framework) in .Net 3.0. I know that it is not easy to migrate to a new framework, but with WCF you get so much. Furthermore WCf can be used for so much more than WebServices (remoting, msmq and more). It is the framework that Microsoft is betting on for the future. Ie. manipulation a soap header is done using MessageContracts.</p> <p>So the answer is that in WCF you can do this with MessageContracts.</p>
<p>I ran into this problem today. I ended creating a class that derives from the autogenerated class and overriding the <a href="http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soaphttpclientprotocol.getwriterformessage.aspx" rel="nofollow noreferrer">GetWriterForMessage</a> method to ensure my header was always present. I would update the header value on every call to the method.</p>
42,908
<p>Imagine a web application written in Ruby on Rails. Part of the state of that application is represented in a piece of data which doesn't fit the description of a model. This state descriptor needs to be persisted in the same database as the models. Where it differs from a model is that there needs to be only one instance of its class and it doesn't have relationships with other classes.</p> <p>Has anyone come across anything like this?</p>
<p>From your description I think the rails-settings plugin should do what you need. </p> <p>From the Readme:</p> <p>"Settings is a plugin that makes managing a table of global key, value pairs easy. Think of it like a global Hash stored in you database, that uses simple ActiveRecord like methods for manipulation. Keep track of any global setting that you dont want to hard code into your rails app. You can store any kind of object. Strings, numbers, arrays, or any object."</p> <p><a href="http://github.com/Squeegy/rails-settings/tree/master" rel="nofollow noreferrer">http://github.com/Squeegy/rails-settings/tree/master</a></p>
<p>I'm not sure I understand why you say it can't fit in a Rails model. </p> <p>If it's just a complex data structure, just save a bunch of Ruby code in a text field in the database :-)</p> <p>If for example you have a complex nested hash you want to save, assign the following to your 'data' text field:</p> <pre><code>ComplexThing.data = complex_hash.inspect </code></pre> <p>When you want to read it back, simply</p> <pre><code>complex_hash = eval ComplexThing.data </code></pre> <p>Let me point out 2 more things about this solution:</p> <ul> <li>If your data structure is not standard Ruby classes, a simple inspect may not do it. If you see #&lt;MyClass:0x4066e3c&gt; anywhere, something's not being serialized properly.</li> <li>This is a naive implementation. You may want to check out real marshalling solutions if you risk having unicode data or if you really are saving a lot of custom-made classes.</li> </ul>
13,940
<p>What are some of the better AJAX Treeviews out there that support asynchronous JSON loading.</p> <p>YUI TreeView seems nice, but bloated with tables, etc.</p>
<p><a href="http://plugins.jquery.com/project/treeview" rel="noreferrer">jQuery TreeView plugin</a> it's really good and it haves very nice <a href="http://jquery.bassistance.de/treeview/demo/async.html" rel="noreferrer">asynchronous</a> <a href="http://jquery.bassistance.de/treeview/demo/source.phps" rel="noreferrer">JSON</a> loading capabilities...</p> <p><a href="http://extjs.com/deploy/dev/examples/tree/reorder.html" rel="noreferrer">ExtJS TreeView Component</a>, also great, multi-level asynchronous loading, excelent for large trees.</p>
<p>I suggest DHTMLX Tree:</p> <ul> <li>Cross Browser </li> <li>AJAX Support </li> <li>In-line node editing </li> <li>Drag-n-drop capabilities</li> <li>*Smart Rendering - allows avoiding performance problems in trees with great number of nodes per level. </li> <li><p>Rich Client API</p></li> <li><p>Special techniques implemented into the component make loading of really big trees fast and effective. </p></li> <li><p>Advanced drag-and-drop makes it possible to drag items not just within one tree, but between different ones (even if trees are located in different frames or iframes). </p></li> </ul> <p>You can try this functionality right now:</p> <p><a href="http://dhtmlx.com/docs/products/dhtmlxTree/index.shtml" rel="noreferrer">Live Demo</a></p>
27,184
<p>I have a small app which references the Microsoft.SqlServer.Smo assembly (so I can display to the user a list of servers &amp; databases to which they can connect).</p> <p>My application originally referenced Microsoft.SqlServer.Smo and Microsoft.SqlServer.ConnectionInfo. Things worked as expected on my dev box.</p> <p>When I installed the application on a test machine, I received a <strong>System.IO.FileNotFoundException</strong>. The details of the message included the following: <strong>Could not load file or assembly Microsoft.SqlServer.SmoEnum</strong></p> <p>I eventually resolved the issue by referencing the following assemblies in addition to the ones mentioned above: </p> <ul> <li>Microsoft.SqlServer.SmoEnum</li> <li>Microsoft.SqlServer.SqlEnum</li> <li>Microsoft.SqlServer.BatchParser</li> <li>Microsoft.SqlServer.Replication</li> </ul> <p>Can anyone confirm that I do indeed need to include each of these additional assemblies in my application (and therefore install them on user's machines) even though the app builds fine on my development box without them referenced?</p>
<p>Yes, they do need to be included. On the development machine you probably have SQL Server installed, which places those assemblies into the Global Assembly Cache. Whenever you build, Visual Studio just pulls from them from the GAC. It also assumes that the GAC of whatever computer it will be deployed on will also have those files. If not, it throws the FileNotFound exception.</p>
<p>Since JIT links to external assemblies at run-time, this question can't be answered without analyzing your code and seeing what you call and in turn, what those calls call, etc.</p> <p>If you want to analyze this yourself, your best bet would be to reference only the assembly you need and then to learn from the exceptions and inner-exceptions what happened.</p> <p>Another thing you should look into is why the four assemblies you mention aren't in the GAC. It sure seems like they should be.</p>
10,253
<p>I am looking to allow users to control of subdomain of an app I am toying with, much like Basecamp where it is <code>customusername.seework.com</code>.</p> <p>What is required on the <code>DNS</code> end to allow these to be created dynamically and be available instantly. </p> <p>And how do you recommend dealing with this in the logic of the site? <code>Htaccess</code> rule to lookup the subdomain in the <code>DB</code>?</p>
<p>The way we do this is to have a 'catch all' for our domain name registered in DNS so that anything.ourdomain.com will point to our server.</p> <p>With Apache you can set up a similar catch-all for your vhosts. The ServerName must be a single static name but the ServerAlias directive can contain a pattern.</p> <pre><code>Servername www.ourdomain.com ServerAlias *.ourdomain.com </code></pre> <p>Now all of the domains will trigger the vhost for our project. The final part is to decode the domain name actually used so that you can work out the username in your code, something like (PHP):</p> <pre><code>list( $username ) = explode( ".", $_SERVER[ "HTTP_HOST" ] ); </code></pre> <p>or a RewriteRule as already suggested that silently maps user.ourdomain.com/foo/bar to www.ourdomain.com/foo/bar?user=user or whatever you prefer.</p>
<p>I was looking to do something similar (<code>www.mysite.com/SomeUser</code>).</p> <p>What I did was I edited <code>404.shtml</code> to include this server side include (SSI) code:</p> <pre><code>&lt;!--#include virtual="404.php" -- &gt; </code></pre> <p>Then I created the file <code>404.php</code>, where I parsed the URL to check for a user's name and showed their info from the database.</p>
2,360
<p>I realise this is not the ideal place to ask about this in terms of searchability, but I've got a page whose JavaScript code throws "Stack overflow in line 0" errors when I look at it in Internet Explorer.</p> <p>The problem is quite clearly not in line 0, but somewhere in the list of stuff that I'm writing to the document. Everything works fine in Firefox, so I don't have the delights of Firebug and friends to assist in troubleshooting.</p> <p>Are there any standard causes for this? I'm guessing this is probably an Internet Explorer 7 bug or something quite obscure, and my <a href="http://en.wiktionary.org/wiki/Google-fu" rel="nofollow noreferrer">Google-fu</a> is bringing me little joy currently. I can find lots of people who have run into this before, but I can't seem to find how they solved it.</p>
<p>You can turn <em>off</em> the <code>"Disable Script Debugging"</code> option inside of Internet Explorer and start debugging with <code>Visual Studio</code> if you happen to have that around.</p> <p>I've found that it is one of few ways to diagnose some of those <code>IE</code> specific issues.</p>
<p>This is problem with Java and Flash Player. Install the latest Java and Flash Player, and the problem will be resolved. If not, then install Mozilla Firefox, it will auto install the updates required.</p>
27,951
<p>I've always wanted a way to make a socket connection to a server and allow the server to manipulate the page DOM. For example, this could be used in a stock quotes page, so the server can push new quotes as they become available. </p> <p>I know this is a classic limitation (feature?) of HTTP's request/response protocol, but I think this could be implemented as a Firefox plugin (cross-browser compatibility is not important for my application). Java/Flash solutions are not acceptable, because (as far as i know) they live in a box and can't interact with the DOM. </p> <p>Can anyone confirm whether this is within the ability of a Firefox plugin? Has someone already created this or something similar? </p>
<p>You may want to look at <a href="http://en.wikipedia.org/wiki/Comet_(programming)" rel="nofollow noreferrer">Comet</a> which is a fancy name for a long running HTTP connection where the server can push updates to the page.</p>
<blockquote> <p>You may want to look at Comet</p> </blockquote> <p>a.k.a. <a href="http://ejohn.org/blog/streaming-http-server-push/" rel="nofollow noreferrer">server push</a>. This does not let the server "update" the client page directly, but all the new data is sent to the page through a single connection.</p> <p>Of course, a Firefox <a href="http://developer.mozilla.org/en/docs/Extension" rel="nofollow noreferrer">extension</a> (as well as <a href="http://developer.mozilla.org/en/docs/Plugins" rel="nofollow noreferrer">plugins</a>, which are binary libraries that can do whatever any other application can do) can work with sockets too. See <a href="http://www.xulplanet.com/tutorials/mozsdk/serverpush.php" rel="nofollow noreferrer">1</a>, <a href="http://www.xulplanet.com/tutorials/mozsdk/serverpush.php" rel="nofollow noreferrer">2</a>.</p>
3,428
<p>Is there any way to prevent Visual Studio from creating a VSMacros80 folder in my default project directory?</p>
<p>I just found it out myself: If you add a trailing backslash to the <em>Project Folder</em> setting e.g. changing it from <code>C:\dev</code> to <code>C:\dev\</code>, the <code>VSMacros80</code> directory will no longer be created. </p> <p>I tested it with Visual Studio 2005 SP1, with all windows updates installed.</p>
<p>I could not find the previous thread, because I was searching for "vsmacros" instead of "vsmacros80".</p> <p>There are currently 5 different entries in <code>Tools-&gt;Options-&gt;Addin/Macro Security</code></p> <pre><code>%ALLUSERSPROFILE%\Application Data\Microsoft\MsEnvShared\Addins %APPDATA%\Microsoft\MsEnvShared\Addins %VSAPPDATA%\Addins %VSCOMMONAPPDATA%\Addins %VSMYDOCUMENTS%\Addins </code></pre> <p>Can you tell me which one I have to delete?</p>
9,574
<p>My machine is seriously underpowered, and I think I need to start conserving every spare cycle. I know that my Gnome environment seems to underperform compared to my coworkers' KDE setups. But if I'm going to make that big of a switch, I might as well consider running something even lighter.</p> <p>Is it possible to survive on a lightweight window manager and still run modern apps (Firefox, Eclipse, OpenOffice)? What's a good candidate window manager for me to try, and what do I need to know?</p>
<p>The window managers listed below all subscribe to the lightweight and fast approach. They are faster than fully fledged window managers like KDE or Gnome and trim down on most visual distractions. Which one you pick will be mostly determined by your own taste and what you can get to run.</p> <p>There's a subfamily of these window managers, notably those which attempt to let you do everything by keyboard and let you tile your applications with minimal screen real estate waste. These can feel funny if you come from mouse-oriented window managers. XMonad and ratpoison are members of this family.</p> <ul> <li><a href="http://www.xfce.org/" rel="nofollow noreferrer">xfce</a></li> <li><a href="http://www.nongnu.org/ratpoison/" rel="nofollow noreferrer">ratpoison</a></li> <li><a href="http://www.fluxbox.org/" rel="nofollow noreferrer">fluxbox</a></li> <li><a href="http://awesome.naquadah.org/" rel="nofollow noreferrer">awesome</a> -1, cannot handle minimize to tray</li> <li><a href="http://xmonad.org/" rel="nofollow noreferrer">XMonad</a></li> <li><a href="http://dwm.suckless.org/" rel="nofollow noreferrer">dwm</a></li> <li><a href="http://www.fvwm.org/" rel="nofollow noreferrer">fvwm</a> (codebase for another WMs)</li> <li><a href="http://www.icewm.org/" rel="nofollow noreferrer">icewm</a></li> <li><a href="http://www.enlightenment.org/" rel="nofollow noreferrer">Englightenment</a></li> <li><a href="http://www.suckless.org/wmii/" rel="nofollow noreferrer">wmii</a></li> <li><a href="http://icculus.org/openbox/index.php/Main_Page" rel="nofollow noreferrer">openbox</a></li> <li><a href="http://www.pekwm.org/projects/pekwm" rel="nofollow noreferrer">pekwm</a></li> </ul>
<p>I'll second xfce, it's probably the most popular of the lightweight WM's out there (perhaps due to its inclusion in <a href="http://www.xubuntu.org/" rel="nofollow noreferrer">Xubuntu</a>). I've also had good experiences with <a href="http://www.fluxbox.org/" rel="nofollow noreferrer">Fluxbox</a> (it came with Damn Small Linux when I used that as a lightweight Linux VM (back when VMs were slow :-) ).</p> <p>There is definitely an ease-of-use learning curve to reckon with when migrating to these more lightweight WMs, but the performance benefits aren't hard to see on older hardware (menus appear instantly, navigation is pretty snappy).</p>
14,118
<p>How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight.</p> <p>Edit: Here's the code I'm now using this for, based on the answer from Santiago below.</p> <pre><code>public DataTemplate Create(Type type) { return (DataTemplate)XamlReader.Load( @"&lt;DataTemplate xmlns=""http://schemas.microsoft.com/client/2007""&gt; &lt;" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/&gt; &lt;/DataTemplate&gt;" ); } </code></pre> <p>This works really nicely and allows me to change the binding on the fly. </p>
<p>Although you cannot programatically create it, you can load it from a XAML string in code like this:</p> <pre><code> public static DataTemplate Create(Type type) { return (DataTemplate) XamlReader.Load( @"&lt;DataTemplate xmlns=""http://schemas.microsoft.com/client/2007""&gt; &lt;" + type.Name + @"/&gt; &lt;/DataTemplate&gt;" ); } </code></pre> <p>The snippet above creates a data template containing a single control, which may be a user control with the contents you need.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.datatemplate%28v=vs.95%29.aspx" rel="nofollow noreferrer">citation from MSDN</a>: </p> <blockquote> <p>The XAML usage that defines the content for creating a data template is not exposed as a settable property. It is special behavior built into the XAML processing of a DataTemplate object element.</p> </blockquote>
8,405
<p>What is an algorithm to compare multiple sets of numbers against a target set to determine which ones are the most "similar"?</p> <p>One use of this algorithm would be to compare today's hourly weather forecast against historical weather recordings to find a day that had similar weather.</p> <p>The similarity of two sets is a bit subjective, so the algorithm really just needs to diferentiate between good matches and bad matches. We have a lot of historical data, so I would like to try to narrow down the amount of days the users need to look through by automatically throwing out sets that aren't close and trying to put the "best" matches at the top of the list.</p> <p><strong>Edit</strong>: Ideally the result of the algorithm would be comparable to results using different data sets. For example using the mean square error as suggested by <a href="https://stackoverflow.com/questions/139811/algorithm-to-score-similarness-of-sets-of-numbers#139842">Niles</a> produces pretty good results, but the numbers generated when comparing the temperature can not be compared to numbers generated with other data such as Wind Speed or Precipitation because the scale of the data is different. Some of the non-weather data being is very large, so the mean square error algorithm generates numbers in the hundreds of thousands compared to the tens or hundreds that is generated by using temperature.</p>
<p>I think the mean square error metric might work for applications such as weather compares. It's easy to calculate and gives numbers that do make sense.</p> <p>Since your want to compare measurements over time you can just leave out missing values from the calculation.</p> <p>For values that are not time-bound or even unsorted, multi-dimensional scatter data it's a bit more difficult. Choosing a good distance metric becomes part of the art of analysing such data. </p>
<p>First of all, ask yourself if these are sets, or ordered collections.</p> <p>I assume that these are ordered collections with duplicates. The most obvious algorithm is to select a tolerance within which numbers are considered the same, and count the number of slots where the numbers are the same under that measure.</p>
16,908
<p>I have been trying to tokenize a string using SPACE as delimiter but it doesn't work. Does any one have suggestion on why it doesn't work?</p> <p>Edit: tokenizing using:</p> <pre><code>strtok(string, " "); </code></pre> <p>The code is like the following</p> <pre><code>pch = strtok (str," "); while (pch != NULL) { printf ("%s\n",pch); pch = strtok (NULL, " "); } </code></pre>
<p>Do it like this:</p> <pre><code>char s[256]; strcpy(s, "one two three"); char* token = strtok(s, " "); while (token) { printf("token: %s\n", token); token = strtok(NULL, " "); } </code></pre> <p>Note: <code>strtok</code> modifies the string its tokenising, so it cannot be a <code>const char*</code>. </p>
<pre><code>int not_in_delimiter(char c, char *delim){ while(*delim != '\0'){ if(c == *delim) return 0; delim++; } return 1; } char *token_separater(char *source, char *delimiter, char **last){ char *begin, *next_token; char *sbegin; /*Get the start of the token */ if(source) begin = source; else begin = *last; sbegin = begin; /*Scan through the string till we find character in delimiter. */ while(*begin != '\0' &amp;&amp; not_in_delimiter(*begin, delimiter)){ begin++; } /* Check if we have reached at of the string */ if(*begin == '\0') { /* We dont need to come further, hence return NULL*/ *last = NULL; return sbegin; } /* Scan the string till we find a character which is not in delimiter */ next_token = begin; while(next_token != '\0' &amp;&amp; !not_in_delimiter(*next_token, delimiter)) { next_token++; } /* If we have not reached at the end of the string */ if(*next_token != '\0'){ *last = next_token--; *next_token = '\0'; return sbegin; } } void main(){ char string[10] = "abcb_dccc"; char delim[10] = "_"; char *token = NULL; char *last = "" ; token = token_separater(string, delim, &amp;last); printf("%s\n", token); while(last){ token = token_separater(NULL, delim, &amp;last); printf("%s\n", token); } </code></pre> <p>}</p> <p>You can read detail analysis at blog mentioned in my profile :)</p>
33,395
<p>I have a class that looks like this</p> <pre><code>public class SomeClass { public SomeChildClass[] childArray; } </code></pre> <p>which will output XML from the XMLSerializer like this:</p> <pre><code>&lt;SomeClass&gt; &lt;SomeChildClass&gt; ... &lt;/SomeChildClass&gt; &lt;SomeChildClass&gt; ... &lt;/SomeChildClass&gt; &lt;/SomeClass&gt; </code></pre> <p>But I want the XML to look like this:</p> <pre><code>&lt;SomeClass&gt; &lt;SomeChildClass index=1&gt; ... &lt;/SomeChildClass&gt; &lt;SomeChildClass index=2&gt; ... &lt;/SomeChildClass&gt; &lt;/SomeClass&gt; </code></pre> <p>Where the index attribute is equal to the items position in the array.</p> <p>I could add an index property to SomeChildClass with the "XMLAttribute" attribute but then I would have to remember to loop through the array and set that value before I serialize my object.</p> <p>Is there some attribute i can add or some other way to automatically generate the index attribute for me?</p>
<p>The best approach would be to do what you said and add a property to the "SomeChildClass" like this</p> <pre><code>[XmlAttribute("Index")] public int Order { { get; set; } } </code></pre> <p>Then however you are adding these items to your array, make sure that this property get's set. Then when you serialize....Presto!</p>
<p>You may need to look into implementing System.Xml.Serialization.IXmlSerializable to accomplish this.</p>
19,710
<p>The following <strong>C++</strong> code uses a <strong>ifstream</strong> object to read integers from a text file (which has one number per line) until it hits <strong>EOF</strong>. Why does it read the integer on the last line twice? How to fix this?</p> <p><strong>Code:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; using namespace std; int main() { ifstream iFile("input.txt"); // input.txt has integers, one per line while (!iFile.eof()) { int x; iFile &gt;&gt; x; cerr &lt;&lt; x &lt;&lt; endl; } return 0; } </code></pre> <p><strong>input.txt</strong>:</p> <pre><code>10 20 30 </code></pre> <p><strong>Output</strong>:</p> <pre><code>10 20 30 30 </code></pre> <p><strong>Note</strong>: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).</p>
<p>Just follow closely the chain of events.</p> <ul> <li>Grab 10</li> <li>Grab 20</li> <li>Grab 30</li> <li>Grab EOF</li> </ul> <p>Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop.</p> <p>Try this:</p> <pre><code>while (true) { int x; iFile &gt;&gt; x; if( iFile.eof() ) break; cerr &lt;&lt; x &lt;&lt; endl; } </code></pre> <p>By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.</p>
<pre><code>int x; ifile &gt;&gt; x while (!iFile.eof()) { cerr &lt;&lt; x &lt;&lt; endl; iFile &gt;&gt; x; } </code></pre>
4,177
<p>Suppose I want to create a set of observers based on type. That is to say, when they are notified of an event, they are told the type of one of the arguments and then decides whether or not to act based on if it can operate on that type.</p> <p>Are there any simple ways to do this? I figured this would be fairly simple to do with generics, but that seems to be turning out to be harder than I imagined. And I would prefer not to have to deal with casting a bunch of references to object if I can avoid it.</p> <p>Where I'm getting stuck is in doing this:</p> <pre><code>public delegate void NotifyDelegate&lt;T&gt;(IEnumerator&lt;T&gt; loadable, NotifyArgs na); interface IObserver { void Notify&lt;T&gt;(IEnumerator&lt;T&gt; loadable, NotifyArgs na); } class Subject { NotifyDelegate notifier; //won't compile: needs type args void Register(IObserver o) { notifier += o.Notify; } } </code></pre> <p>Of course, I could make the Subject generic as well, but then I have to have a separate Subject for each type. Does anyone have any advice here? Is there some piece of functionality that I'm missing somewhere or am I overcomplicating this?</p> <p><strong>UPDATE</strong>: I did oversimplify the arguments that Notify and NotifyDelegate take. Instead of this:</p> <pre><code>public delegate void NotifyDelegate&lt;T&gt;(NotifyArgs na); </code></pre> <p>I'm actually wanting to do something like this:</p> <pre><code>public delegate void NotifyDelegate&lt;T&gt;(IEnumerator&lt;T&gt; loadable, NotifyArgs na); </code></pre> <p>What I'm basically trying to pass back and forth is data from a database. Sorry if the previous code sample confused anyone.</p>
<p>First off, change the code you've got to the following:</p> <pre><code>interface IObserver { } class Subject { public Subject () { m_observers = new List&lt;IObserver&gt; (); } public void Register (IObserver o) { m_observers.Add (o); } List&lt;IObserver&gt; m_observers; } </code></pre> <p>Then, use reflection to find an appropriate function based on parameter type:</p> <pre><code> public void NotifyObservers (object param) { foreach (IObserver observer in m_observers) { foreach (MethodInfo method in observer.GetType ().GetMethods (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Instance)) { if (method.Name == "Notify") { ParameterInfo [] parameters = method.GetParameters (); if (parameters.Length == 1 &amp;&amp; parameters [0].ParameterType == param.GetType ()) { method.Invoke (observer, new object [] { param }); break; } } } } } </code></pre> <p>and use it like this:</p> <pre><code>class Observer : IObserver { public Observer (Subject s) { s.Register (this); } void Notify (float value) { System.Diagnostics.Trace.WriteLine ("float value = " + value); } void Notify (int value) { System.Diagnostics.Trace.WriteLine ("int value = " + value); } } static void Main (string [] args) { Subject s = new Subject (); Observer o = new Observer (s); float v1 = 3.14f; int v2 = 42; System.Diagnostics.Trace.WriteLine ("sending float"); s.NotifyObservers (v1); System.Diagnostics.Trace.WriteLine ("sending int"); s.NotifyObservers (v2); } </code></pre>
<pre><code>interface IObserver { void Notify(NotifyArgs na); bool SupportsType(Type t); } class Subject { List&lt;IObserver&gt; observers; void Register(IObserver o) { observers.Add(o); } void OnNotify(Type t, NotifyArgs args) { foreach (IObserver o in observers) { if (o.SupportsType(t)) o.Notify(args)); } } } </code></pre>
37,845
<p>I have a String such as: </p> <pre><code>Cerepedia, una apliación web </code></pre> <p>I would like to transform it into something URL valid such as: </p> <pre><code>Cerepedia,unaaplicacionweb </code></pre> <p><strong>Note:</strong> the special character transformation and spaces removal. </p> <p>By the way, are commas allowed in URLs?</p>
<p>Have you looked at <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLEncoder.html" rel="nofollow noreferrer">URLEncoder</a>? That seems to do what you need it to do. Though the special characters will be transformed to escaped entities and not stripped from their "special" properties.</p>
<p>Try this code</p> <pre><code> public class Test { public static void main(final String[] args) { String str = "Cerepedia, una apliación web"; String[] parts = str.split(" "); int sum=0; for (int i=0;i&lt;=parts.length-1;i++) { sum = sum+parts[i].length(); } int k=0; char[] url = new char[25]; for (int i=0;i&lt;=parts.length-1;i++) { char[] temp = parts[i].toCharArray(); for(int j=0;j&lt;temp.length;j++){ url[k]=temp[j]; k++; } } System.out.println(url); } } </code></pre>
25,162
<p>I am interested in what methods of logging is frequent in an Oracle database. Our method is the following:</p> <p>We create a log table for the table to be logged. The log table contains all the columns of the original table plus some special fields including timestamp, modification type (insert, update, delete), modifier's id. A trigger on the original table creates one log row for each insertion and deletion, and two rows for a modification. Log rows contain the data before and after the alteration of the original one.</p> <p>Although state of the records can be mined back in time using this method, it has some drawbacks:</p> <ul> <li>Introduction of a new column in the original table does not automatically involves log modification.</li> <li>Log modification affects log table and trigger and it is easy to mess up.</li> <li>State of a record at a specific past time cannot be determined in a straightforward way.</li> <li>...</li> </ul> <p>What other possibilities exist? What kind of tools can be used to solve this problem?</p> <p>I only know of <a href="http://log4plsql.sourceforge.net/" rel="noreferrer">log4plsql</a>. What are the pros/cons of this tool?</p> <p>Edit: Based on Brian's answer I have found the following <a href="http://www.oracle-base.com/articles/10g/Auditing_10gR2.php" rel="noreferrer">reference</a> that explains standard and fine grain auditing.</p>
<p>It sounds like you are after 'auditing'. Oracle has a built-in feature called Fine Grain Auditing (FGA). In a nutshell you can audit everything or specific conditions. What is really cool is you can 'audit' selects as well as transactions. Simple command to get started with auditing:</p> <pre><code>audit UPDATE on SCOTT.EMP by access; </code></pre> <p>Think of it as a 'trigger' for select statements. For example, you create policies:</p> <pre><code>begin dbms_fga.add_policy ( object_schema=&gt;'BANK', object_name=&gt;'ACCOUNTS', policy_name=&gt;'ACCOUNTS_ACCESS' ); end; </code></pre> <p>After you have defined the policy, when a user queries the table in the usual way, as follows:</p> <pre><code>select * from bank.accounts; </code></pre> <p>the audit trail records this action. You can see the trail by issuing:</p> <pre><code>select timestamp, db_user, os_user, object_schema, object_name, sql_text from dba_fga_audit_trail; TIMESTAMP DB_USER OS_USER OBJECT_ OBJECT_N SQL_TEXT --------- ------- ------- ------- -------- ---------------------- 22-OCT-08 BANK ananda BANK ACCOUNTS select * from accounts </code></pre>
<p>log4plsql is a completely different thing, its for logging debug info from PL/SQL</p> <p>For what you want, you need to either.</p> <ol> <li>Setup a trigger</li> <li>Setup PL/SQL interface around the tables, CRUD operations happen via this interface, the interface ensures the log tables are updated.</li> <li>Setup interface in your application layer, as with PL/SQL interface, just higher up.</li> <li>Oracle 11g contains versioned tables, I have not used this at all though, so can make no real comment.</li> </ol>
23,737
<p>I'm implementing a class that wraps around an xml document with a very strictly defined schema. I don't control the schema. </p> <p>One of the properties in the class is for an element value that the schema indicates must match a certain regular expression. In the setter for the property, if a string doesn't match the expression I'm throwing an exception.</p> <p>My question is, how can I better communicate to users of my class the requirements for this field? Is there an attribute I can use? Xml comments (so it shows up in intellisense)? Should I do something other than thrown an exception? What other options do I have?</p>
<p>XmlComments may help if you ship them with your assembly, but I would say that you are best off throwing exceptions if the requirements are not met, and making the exception message as detailed as possible. I would also throw exceptions (again with lots of detail) if the requirement is not met when the user calls and methods/properties the rely on the property.</p> <p>There isn't really much you can do to keep someone using the code from making the mistake the first time, but you should be as clear as possible when the mistake does occur about how to correct it.</p>
<p>Document it in the XML comments, and throw an exception. Make the message explicit:</p> <pre><code>Element &lt;elementname&gt; must match /regex/ </code></pre>
21,620
<p><code>itoa()</code> is a really handy function to convert a number to a string. Linux does not seem to have <code>itoa()</code>, is there an equivalent function or do I have to use <code>sprintf(str, "%d", num)</code>?</p>
<p>EDIT: Sorry, I should have remembered that this machine is decidedly non-standard, having plugged in various non-standard <code>libc</code> implementations for academic purposes ;-)</p> <p>As <code>itoa()</code> is indeed non-standard, as mentioned by several helpful commenters, it is best to use <code>sprintf(target_string,"%d",source_int)</code> or (better yet, because it's safe from buffer overflows) <code>snprintf(target_string, size_of_target_string_in_bytes, "%d", source_int)</code>. I know it's not quite as concise or cool as <code>itoa()</code>, but at least you can Write Once, Run Everywhere (tm) ;-)</p> <h2>Here's the old (edited) answer</h2> <p>You are correct in stating that the default <code>gcc libc</code> does not include <code>itoa()</code>, like several other platforms, due to it not technically being a part of the standard. See <a href="http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html" rel="noreferrer">here</a> for a little more info. Note that you have to </p> <pre><code>#include &lt;stdlib.h&gt; </code></pre> <p>Of course you already know this, because you wanted to <em>use</em> <code>itoa()</code> on Linux after presumably using it on another platform, but... the code (stolen from the link above) would look like:</p> <p><strong>Example</strong></p> <pre><code>/* itoa example */ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main () { int i; char buffer [33]; printf ("Enter a number: "); scanf ("%d",&amp;i); itoa (i,buffer,10); printf ("decimal: %s\n",buffer); itoa (i,buffer,16); printf ("hexadecimal: %s\n",buffer); itoa (i,buffer,2); printf ("binary: %s\n",buffer); return 0; } </code></pre> <p><strong>Output:</strong></p> <blockquote> <pre><code>Enter a number: 1750 decimal: 1750 hexadecimal: 6d6 binary: 11011010110 </code></pre> </blockquote> <p>Hope this helps!</p>
<p>You can use this program instead of sprintf.</p> <pre><code>void itochar(int x, char *buffer, int radix); int main() { char buffer[10]; itochar(725, buffer, 10); printf ("\n %s \n", buffer); return 0; } void itochar(int x, char *buffer, int radix) { int i = 0 , n,s; n = s; while (n &gt; 0) { s = n%radix; n = n/radix; buffer[i++] = '0' + s; } buffer[i] = '\0'; strrev(buffer); } </code></pre>
23,082
<p>Mac OS X stores some files with resource forks. I need to create a file with a resource fork. The trouble is, I need to create this file on the command line. Is anyone aware of how you can create a file with a resource fork on the command line in Mac OS X?</p>
<p>You can directly access the resource fork of a file using path/to/file/..namedfork/rsrc.</p>
<p>As an alternative, you can make a copy of an existing file, fork and all, using ditto:</p> <p>ditto -rsrc srcFile dstFile</p>
40,047
<p>i want to check my server connection to know if its available or not to inform the user..</p> <p>so how to send a pkg or msg to the server (it's not SQL server; it's a server contains some serviecs) ...</p> <p>thnx in adcvance ..</p>
<p>With all the possibilities for firewalls blocking ICMP packets or specific ports, the only way to guarantee that a service is running is to do something that uses that service.</p> <p>For instance, if it were a JDBC server, you could execute a non-destructive SQL query, such as <code>select * from sysibm.sysdummy1</code> for DB2. If it's a HTTP server, you could create a GET packet for index.htm.</p> <p>If you actually have control over the service, it's a simple matter to create a special sub-service to handle these requests (such as you send through a CHECK packet and get back an OKAY response).</p> <p>That way, you avoid all the possible firewall issues and the test is a true end-to-end one. PINGs and traceroutes will be able to tell if you can get to the machine (firewalls permitting) but they won't tell you if your service is functioning.</p> <p>Take this from someone who's had to battle the network gods in a corporate environment where machines are locked up as tight as the proverbial fishes ...</p>
<p>If you can open a port but don't want to use ping (i dont know why but hey) you could use something like this:</p> <pre><code>import socket host = '' port = 55555 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) s.listen(1) while 1: try: clientsock, clientaddr = s.accept() clientsock.sendall('alive') clientsock.close() except: pass </code></pre> <p>which is nothing more then a simple python socket server listening on 55555 and returning alive</p>
47,643
<p>I'm trying to insert a <a href="http://en.wikipedia.org/wiki/Spry_framework" rel="nofollow noreferrer">Spry</a> <a href="http://en.wikipedia.org/wiki/Accordion_(GUI)" rel="nofollow noreferrer">accordion</a> into an already existing <a href="http://en.wikipedia.org/wiki/JavaServer_Faces" rel="nofollow noreferrer">JSF</a> page using <a href="http://en.wikipedia.org/wiki/Adobe_Dreamweaver" rel="nofollow noreferrer">Dreamweaver</a>. Is this possible? </p> <p>I've already tried several things, and only the labels show up.</p>
<p>I'm not a Dreamweaver expert, but all Spry Accordian requires is the correct HTML structure. E.g.: </p> <pre><code> &lt;div id="Accordion1" class="Accordion"&gt; &lt;div class="AccordionPanel"&gt; &lt;div class="AccordionPanelTab"&gt;Panel 1&lt;/div&gt; &lt;div class="AccordionPanelContent"&gt; Panel 1 Content&lt;br/&gt; Panel 1 Content&lt;br/&gt; Panel 1 Content&lt;br/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Provided you have the <a href="http://en.wikipedia.org/wiki/JavaScript" rel="nofollow noreferrer">JavaScript</a> library loaded correctly, that should pretty much be all you need to do.</p>
<p>The only other thing you might check is if your ids are getting munged by JSF. Obviously that could impact the ability of Spry to wire itself to your accordion html structure.</p> <p>+1 to Dave's answer.</p>
10,151
<p>What is the best practices regarding storing files uploaded from users?</p> <p>Currently, I am during the following method for storing files:</p> <pre><code>&lt;web_app_root&gt;/course_material/&lt;term_id&gt;/&lt;course_id&gt;/&lt;file_id&gt; </code></pre> <p>As you can see, the files are stored according to the keys in the database. I thought this was safer, since I wouldn't have to filter filenames and turn unsafe characters into safe characters.</p> <p>However, I am starting a new project and wanted to know if it was a bad idea to tie a web app's filesystem so closely with a database. Should I store files in a more human readable format?</p> <pre><code>&lt;web_app_root&gt;/course_material/&lt;term_name_underscored&gt;/&lt;course_name_underscored&gt;/&lt;file_name_underscored&gt; </code></pre> <p>If so, what are the best ways to filter out filenames to be safe? Or is the way I am currently doing it a best practice?</p>
<p>I've always just stored the files in a directory with unique GUID based filenames, and mapped the guid to the file in the DB. As long as you're not manually browsing the files and such, this is probably the easiest solution (also gets around invalid chars).</p> <p>Another option is storing them as BLOBS in the database. I've also done this - but it was to fill a replicated DR scenario, which modern NAS devices should handle.</p> <p>If you see the need to manually browse the files outside of the app for some reason, then using the long or short name (however you'd like to browse them) would be cleaner.</p>
<p>I've always just stored the files in a directory with unique GUID based filenames, and mapped the guid to the file in the DB. As long as you're not manually browsing the files and such, this is probably the easiest solution (also gets around invalid chars).</p> <p>Another option is storing them as BLOBS in the database. I've also done this - but it was to fill a replicated DR scenario, which modern NAS devices should handle.</p> <p>If you see the need to manually browse the files outside of the app for some reason, then using the long or short name (however you'd like to browse them) would be cleaner.</p>
42,993
<p>Are there any open source or commercial web programming language that function much like Fog Creek's Wasabi? As in you write your web app in this parent language and it then compiles down to php for Linux hosts and ASP.NET for Windows hosts.</p>
<p><a href="http://haxe.org/" rel="nofollow noreferrer">Haxe</a> is the closest I've seen, but it only compiles to PHP (and mod_neko), not to ASP.</p>
<p>As far as I know, Fog Creek had to develop Wasabi because there wasn't such a tool. There are a few toolkits trying to be portable, but none that compiled to ASP or PHP that I know of (besides Wasabi, that is).</p>
19,242
<p>I have a function that looks something like this:</p> <pre><code>//iteration over scales foreach ($surveyScales as $scale) { $surveyItems = $scale-&gt;findDependentRowset('SurveyItems'); //nested iteration over items in scale foreach ($surveyItems as $item) { //retrieve a single value from a result table and do some stuff //depending on certain params from $item / $scale } } </code></pre> <p><strong>QUESTION</strong>: is it better to do a db query for every single value within the inner foreach or is it better to fetch all result values into an array and get the value from there?</p>
<p>One query that returns a dozen pieces of data is almost 12x faster than 12 queries that return 1 piece of data.</p> <p>Oh, and NEVER EVER NEVER put a SQL inside a loop, it will always lead in a disaster. </p> <p>Depending on how your app works, a new connection might be opened for each query, this is especially bad as every DB server has a limit on the number of connections. Then also realize this will happen for each user, so 50 queries with 5 users and you already have 250 queries at any given moment. But even if all the queries do share just 1 connection, you're taxing the DB server X times more, slowing it down for everything else, every page, because users are hogging the DB server on this page, and everybody has to share.</p> <p>I've seen an entire application fail in the past because of this 1 design flaw, just don't do it.</p>
<p>Definitely fetch all and retrieve from array.</p>
46,520
<p>i dunno, but will your machine suffer great slowdown if you use a very complex regex? like for example the famous email validation module proposed just recently? which can be found here <a href="http://ex-parrot.com/~pdw/Mail-RFC822-Address.html" rel="nofollow noreferrer">RFC822</a></p> <p>update: sorry i had to ask this question in a hurry anyway i posted the link to the email regex i was talking about</p>
<p>It highly depends on the individual regex: features like look-behind or look-ahead can get very expensive, while simple regular expressions are fine for most situations.</p> <p>Tutorials on <a href="http://www.regular-expressions.info/" rel="nofollow noreferrer">http://www.regular-expressions.info/</a> offer performance advice, so that can be a good start.</p>
<p>I once made a program that analyzed a lot of text (a big code base, >300k lines). First I used regex but when I switched to using regular string functions it got a lot faster, like taking 40% of the time of the regex version. So while of course it depends, my thing got a lot faster.</p>
27,790
<p>I need to tweak some variables (only in a development setting) without having to restart IIS or anything (so I assume Web.Config is the wrong place to put them). Where is the easiest place to put about 500 config settings that have to be read for every request and written to, like I said, while IIS is running?</p> <p><strong>EDIT</strong>: Like I said, this is only for some Q&amp;D development so I don't care about performance in any way. A database is a bit of overkill (and is probably more work than I want to deal with), I want something fast (like Settings), that I don't have to worry about parsing and can read from and write to. If I do XML, where do I write the file to so I don't have to spend time messing around with permissions? </p>
<p>In a database?</p>
<p>500 Config Settings to be read for every request? I'd put them in a database so they can be indexed and cached. A separate XML or data file would also most likely be cached in memory by the web server, but still wouldn't provide the performance an indexed database table could. But it depends on how you are accessing the settings.</p>
22,759
<p>I've come to love <a href="http://en.wikipedia.org/wiki/Amazon_Elastic_Compute_Cloud" rel="nofollow noreferrer">Amazon's EC2 service</a> and I'm looking for something similar that supports the ability to save a running Windows server image and start new instances from it.</p> <p>I contacted <a href="http://www.gogrid.com/" rel="nofollow noreferrer">GoGrid</a> (the feature is planned in future) and <a href="http://www.mosso.com/" rel="nofollow noreferrer">Mosso</a> (no joy)</p> <p>Anyone know of any hosting/cloud providers that can dothis?</p>
<p>I have just received a message from Amazon to the effect that that they will be <a href="http://aws.amazon.com/windows/" rel="nofollow noreferrer">supporting Windows Server on EC2</a> this fall.</p> <p>Wahaay!!</p>
<p>Seems like dealing with licensing issues would be nightmarish for the host.</p>
4,248
<p>Here is what I have:</p> <p>JAVA_HOME=C:\Software\Java\jdk1.5.0_12 (points to JDK 5.0)</p> <p>In Eclipse "Installed Runtimes" I have: jre 1.5.0_12 (points to JRE 5.0) jre 1.6.0_3 (points to JRE 6.0) (this one is default)</p> <p>I do not have "javac" on my PATH (i.e. I cannot run javac -version from command line if I am not in JDK/bin).</p> <p>My project is set to use jre 1.6.0_3 and compiler's Compliance Level is set to 6.0.</p> <p>Question is: how Eclipse is able to compile my project? Where it finds a compiler for 6.0? Moreover, is there a way to tell precisely which compiler (i.e. path to javac) is used by Eclipse?</p> <p>P.S. OS XP SP2 if it is relevant P.P.S. I do not have any -vm set in eclipse.ini. In eclipse I see eclipse.vm=C:\Program Files\Java\jre6\bin\client\jvm.dll and it is still a JRE.</p>
<p>Eclipse has the <a href="http://www.eclipse.org/jdt/overview.php" rel="noreferrer">JDT</a> which includes the incremental compiler so it does not need an external one unless that is your wish :)</p>
<p>Eclipse is shipped with an built-in compiler. You can use an external JDK, if you configure it in the preferences.</p> <p>Edit: Thanks to André!</p>
42,152