instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>A GUI driven application needs to host some prebuilt WinForms based components. These components provide high performance interactive views using a mixture of GDI+ and DirectX. The views handle control input and display custom graphical renderings. The components are tested in a WinForms harness by the supplier.</p> <p>Can a commericial application use WPF for its GUI and rely on <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.integration.windowsformshost.aspx" rel="noreferrer" title="WindowsFormsHost">WindowsFormsHost</a> to host the WinForms components or have you experience of technical glitches e.g. input lags, update issues that would make you cautious?</p>
<p>We're currently using WindowsFormsHost in our software to host the WinForms DataGridView control, and we've not had any real problems with it. A few things to watch out for though:</p> <p>The first is the <a href="http://msdn.microsoft.com/en-us/library/aa970688.aspx" rel="noreferrer">air-space restrictions</a>. Practically speaking, this means that WinForms content always appears on top of WPF content. So if you are using WPF adorners they will appear to be "trimmed" if they hit up against a WinForms region in your app.</p> <p>The second is that, because they use Windows resources, you have to manage the lifetimes of WinForms components more carefully. Unlike WPF components, WinForms controls expect to be Disposed when they're finished with. This makes it tricky to include them in a pure XAML view.</p> <p>The last thing is that WinForms controls don't seem to resize as smoothly as the rest of the WPF display: they tend to snap to their new size once you've finished making an adjustment.</p>
<p>I hosted WPF controls in WinForms and vice versa without problems. Though, I would test such scenarios extensively 'cause it's hard to predict how complex control will behave.</p>
7,733
<p>I have a website cgi-bin program that is written in c++. </p> <p>Unfortunately the website provider for my friend's site only allows Perl or PHP cgi-bin scripts.</p> <p>Is there an easy way to simply have a very small Perl or PHP wrapper that just calls the c++ compiled binary? </p> <p>Would the c++ program still be able to read from stdin for POST commands or would it have to be read by the Perl or PHP and then forwarded.</p>
<p>You can use Perl's backticks or "system" commands to run shell commands. Also, perl has a lot of "Inline" classes that allow you to write code in other languages to be called in perl, including one for <a href="http://search.cpan.org/~neilw/Inline-CPP-0.25/" rel="nofollow noreferrer">C++</a>. If you can't find something that works, maybe you can make your own wrapper using that package. </p>
<p>See my <a href="http://blog.matthewsmith.id.au/2008/02/15/awstats-wrapper/" rel="nofollow noreferrer">Awstats Wrapper</a> blog post for some PHP code that solved my problem. My approach was to construct a command line that has the right environment variables set from the CGI query params and then do substitutions on the resulting output so that any links back to the CGI would go to my wrapper script instead. I also nuked the headers output from the CGI since PHP provides its own headers.</p>
35,811
<p>Here is some sample VBA code:</p> <pre><code>Sub Macro1() Dim pt As PivotTable Set pt = ActiveSheet.PivotTables("SomePivotTable") 'Set colOfFields = pt.PivotFields End Sub </code></pre> <p>The third line is incomplete/broken. What is the correct way to get access to collection of all the fields in a PivotTable? I need to be able to loop over them. Actual coding is being done in C# VSTO Project.</p>
<p>This works for me (Excel 2003 [11.8146.8202] SP2):</p> <pre><code>Sub Macro1() Dim pt As PivotTable Dim col As PivotFields Dim c As PivotField ' Name of the pivot table comes from right clicking on the pivot table, ' Table Options..., Name field. Set pt = ActiveSheet.PivotTables("PivotTable1") Set col = pt.PivotFields For Each c In col Debug.Print c.Name Next End Sub </code></pre>
<p>Ok. Found some C#-flavored code ideas from:<br> <a href="http://blogs.msdn.com/andreww/archive/2008/07/25/creating-a-pivottable-programmatically.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/andreww/archive/2008/07/25/creating-a-pivottable-programmatically.aspx</a></p> <pre><code>// pvtTable is an Excel.PivotTable set earlier in the code Excel.PivotFields pflds = (Excel.PivotFields)pvtTable.PivotFields(System.Type.Missing); foreach (Excel.PivotField pf in pflds) { //some code here } </code></pre> <p>The trick is passing in the System.Type.Missing to get the "collection" of fields back.</p>
44,338
<p>Do you build all your login, account creation, password recovery, etc. into your Flex app, or do you keep all of that in web pages and only redirect to the .swf on successful login?</p>
<p>We do it all in Flex in a pretty complex app, there's no reason to divert to HTML. Since Flex talks (stateless) HTTP to the backend if you use AMF, you need session support in Flex anyway.</p>
<p>It's pretty easy to communicate with a server over http (a normal webserver) in flash. If you don't do heavy data-exchange with a server, AMF might be overkill and JSON, XML or your own format will suffice more than enough.</p> <p><a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/URLLoader.html" rel="nofollow noreferrer">http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/URLLoader.html</a></p> <p><a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/URLRequest.html" rel="nofollow noreferrer">http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/URLRequest.html</a></p> <p>EDIT: I mean't to say flash, not flex.</p>
48,989
<p>Using <a href="http://imdbpy.sourceforge.net" rel="noreferrer">IMDbPy</a> it is painfully easy to access movies from the IMDB site:</p> <pre><code>import imdb access = imdb.IMDb() movie = access.get_movie(3242) # random ID print "title: %s year: %s" % (movie['title'], movie['year']) </code></pre> <p>However I see no way to get the picture or thumbnail of the movie cover. Suggestions?</p>
<p><strong>Note:</strong></p> <ul> <li>Not every movie has a cover url. (The random ID in your example doesn't.)</li> <li>Make sure you're using an up-to-date version of IMDbPy. (IMDb changes, and IMDbPy with it.)</li> </ul> <p>...</p> <pre><code>import imdb access = imdb.IMDb() movie = access.get_movie(1132626) print "title: %s year: %s" % (movie['title'], movie['year']) print "Cover url: %s" % movie['cover url'] </code></pre> <p>If for some reason you can't use the above, you can always use something like BeautifulSoup to get the cover url.</p> <pre><code>from BeautifulSoup import BeautifulSoup import imdb access = imdb.IMDb() movie = access.get_movie(1132626) page = urllib2.urlopen(access.get_imdbURL(movie)) soup = BeautifulSoup(page) cover_div = soup.find(attrs={"class" : "photo"}) cover_url = (photo_div.find('img'))['src'] print "Cover url: %s" % cover_url </code></pre>
<p>Response from the IMDbPy mailing list:</p> <blockquote> <p>If present, the url is accessible through movie['cover url']. Beware that it could be missing, so you must first test it with something like:<br> if 'cover url' in movie: ...</p> <p>After that, you can use the urllib module to fetch the image itself.</p> <p>To provide a complete example, something like that should do the trick:</p> <pre><code>import urllib from imdb import IMDb ia = IMDb(#yourParameters) movie = ia.get_movie(#theMovieID) if 'cover url' in movie: urlObj = urllib.urlopen(movie['cover url']) imageData = urlObj.read() urlObj.close() # now you can save imageData in a file (open it in binary mode). </code></pre> <p>In the same way, a person's headshot is stored in person['headshot'].</p> <p>Things to be aware of:</p> <ul> <li>covers and headshots are available only fetching the data from the web server (via the 'http' or 'mobile' data access systems), and not in the plain text data files ('sql' or 'local').</li> <li>using the images, you must respect the terms of the IMDb's policy; see <a href="http://imdbpy.sourceforge.net/docs/DISCLAIMER.txt" rel="nofollow noreferrer">http://imdbpy.sourceforge.net/docs/DISCLAIMER.txt</a></li> <li>the images you'll get will vary in size; you can use the python-imaging module to rescale them, if needed.</li> </ul> </blockquote>
34,750
<p>As input I get an int (well, actually a string I should convert to an int).<br> This int should be converted to bits.<br> For each bit position that has a 1, I should get the position.<br> In my database, I want all records that have an int value field that has this position as value.<br> I currently have the following naive code that should ask my entity(holding the databaseValue) if it matches the position, but obviously doesn't work correctly:</p> <pre><code>Byte[] bits = BitConverter.GetBytes(theDatabaseValue); return bits[position].equals(1); </code></pre> <p>Firstly, I have an array of byte because there apparantly is no bit type. Should I use Boolean[] ? Then, how can I fill this array? Lastly, if previous statements are solved, I should just return bits[position]</p> <p>I feel like this should somehow be solved with bitmasks, but I don't know where to start..</p> <p>Any help would be appreciated</p>
<p>Your feeling is correct. This should be solved with bitmasks. BitConverter does not return bits (and how could it? "bits" isn't an actual data type), it converts raw bytes to CLR data types. Whenever you want to extract the bits out of something, you should think bitmasks.</p> <p>If you want to check if a bit at a certain position is set, use the &amp; operator. Bitwise &amp; is only true if both bits are set. For example if you had two bytes 109 and 33, the result of &amp; would be</p> <pre> 0110 1101 & 0010 0001 ----------- 0010 0001</pre> <p>If you just want to see if a bit is set in an int, you &amp; it with a number that has only the bit you're checking set (ie 1, 2, 4, 8, 16, 32 and so forth) and check if the result is not zero.</p> <pre><code>List&lt;int&gt; BitPositions(uint input) { List&lt;int&gt; result = new List&lt;int&gt;(); uint mask = 1; int position = 0; do { if (input &amp; mask != 0) { result.Add(position); } mask &lt;&lt;= 1; position++; } while (mask != 0); return result; } </code></pre>
<p>Do not use Boolean. Although boolean has only two values, it is actually stored using 32 bits like an int.</p> <p>EDIT: Actually, in array form Booleans will be packed into bytes, not 4 bytes.</p>
49,052
<p>In the following case I'm calling a <code>Func</code> with pointer passed to it, but in the called function, the parameter shows the pointer value as something totally bogus. Something like below.</p> <pre><code>bool flag = Func(pfspara);--&gt; pfspara = 0x0091d910 bool Func(PFSPARA pfspara) --&gt; pfspara = 0x00000005 { return false; } </code></pre> <p>Why does <code>pfspara</code> change to some bogus pointer? I can't reproduce the problem in debug, only in production.</p> <p>Thanks.</p>
<p>If you are trying to debug optimized code in for example Visual Studio, you cannot always rely on the debugger properly showing the values of variables - especially not if the variable is unused so that the compiler probably optimizes it away.</p> <p>Try running this instead:</p> <pre><code>bool Func(PFSPARA pfspara) { printf("%x\n", pfspara); return false; } </code></pre>
<p>In addition to Rasmus' comments, I find it is generally worth checking whether the problem occurs in a debug build as well as the release build. If you see genuine problems occurring in a release build but not in the debug build, it is often down to a bug that is exposed by the optimization processs, such as an uninitialised variable. There is a real danger in doing most of your testing in a debug build, to avoid the problem you are seeing here, and then shipping a release build. IMO, if you don't have a good regression test suite (preferably automated) I would avoid shipping opimized code.</p>
26,390
<p>I have 10 websites on an IP. I would like to share the IP among all the websites.How do I achieve this without having to run these websites on different port numbers?</p>
<p>You could use TADOQuery to limit the result set with a sql query. Or you could use TADOTable and set the <a href="http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate4/EN/html/delphivclwin32/ADODB_TCustomADODataSet_CursorLocation.html" rel="nofollow noreferrer">CursorLocation</a> to a Server side cursor to prevent the client loading the complete resultset in memory.</p>
<p>I have found ADO + Access w/Delphi to be painfully slow, for lots of things (big table reads like you're describing, but also inserts as well, etc). My answer became "Quit using ADO and Access altogether." <br><br>Never did understand why it performed so poorly, especially when earlier technologies seemed not to.</p>
44,677
<p>I am migrating a client's SourceSafe repository (3 projects) to SVN and two of the projects share source files. (These projects are separate products - with different names and release versions, etc)</p> <p>Has SVN resolved this shortcoming? How do people generally handle this scenario?</p> <p>Of the options I know about/can think of</p> <ul> <li><p>Use the external or extern or whatever for SVN. I hear this is not a good option for various reasons</p></li> <li><p>Create a new project (maybe called shared) that contains the source. The problem with this is that we still have to get that code (it is not a library) and import it into the project somehow. It can be shown to be the same problem as the one above and it introduces the overhead of an additional product/project.</p></li> <li><p>Just check in the files in both repositories and cross-update them. This requires developers to know about the sharing and to remember to check in. I suppose I could write a script that checks all known shared files and updates them when needed.</p></li> <li><p>Have one repository for the two projects that share. This leaves me with the problem having to create a top level project/repository that contains the two and it is a problem for labeling. I do not really want to label the top pseudo project. (the tags, trunk and branch things are not exactly where I would want them.)</p></li> </ul> <p>I will probably go with the last option.</p> <p>Any other comments?</p>
<p>The safe way to do it is to have a third project that builds the shared source into a library that is used by the other two. The library project has it's own SVN repository.</p> <p>You can even do this with shared files that are just headers, simply leave them in the lib project directory and add it to the list of includes.</p> <p>Having the same file in two projects, even with soruce control is asking for trouble sooner or later!</p>
<p>Using a trigger to update the files sounds like a bad idea. Somehow they are going to get out of sync. Really the solution with shared code is to extract it into a library and use that library in multiple solutions. That sounds to be outside of the scope of your project, though, so the last solution is your best bet. </p>
16,395
<p>We can use Bitmapsource object as the content of a Image control, However if I only have Bitmap object, can I use it directly, if I convert Bitmap to Bitmapsouce using the following method:</p> <pre><code> Bitmap bitmap = imageObjToBeConvert; IntPtr HBitmap = bitmap.GetHbitmap(); result = Imaging.CreateBitmapSourceFromHBitmap (HBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); DeleteObject(HBitmap); bitmap.Dispose(); </code></pre> <p>It take some time. Is there any way to use Bitmap directly?</p> <p>And I found BitmapSource seems can't be released directly, Is there a sample method to release the memory immediately, after the Bitmapsouce is not used again.</p>
<p>I think REST would make more sense than traditional RPC. Even the <a href="http://msdn.microsoft.com/en-us/library/bb466255.aspx" rel="noreferrer">Micorosft Robotics Studio runtime application model</a> uses REST.</p> <p>The robot can consist of different resources that are identified by URI, including one for each sensor and actuator or composite abstractions thereof.</p> <p>REST puts emphasis on guaranteeing what the side effects of certain methods are and also it facilitates caching, both of which can be useful for something like controlling and monitoring a distant robot. And just because you can use REST it <strong>doesn't</strong> have to be the HTTP protocol.</p> <p>A SAFE and IDEMPOTENT method like GET, though, is good for tracking the state of the robot and polling its sensor data. You can use something like the Last-Modified header to retrieve cached sensor data that doesn't change often (e.g., humidity or light levels). </p> <p>For long distances you can use relay proxies for caching.</p> <p>For commands that move the robot, something like POST would be used where every such message will change the robot (e.g., turn right ). A status code can be returned indicating whether the command was immediately executed or queued for processing. </p> <p>The absolute state of any resources can be set using something like PUT where multiple messages will not change things any more than just a single message (e.g., point to north pole or dim front lights to 10% brightness). This allows for reliable messaging in case of probablity of messages getting lost en route.</p> <p>A new resource may be created via a POST-like operation as well, e.g., a data-collection routine and a set of parameters. The POST request can send back a CREATED result with a URI for the new resource, which can be used to DELETE when no longer needed.</p> <p>A group of robots may also speak to each other using the same REST based protocol and can enjoy the same benefits.</p> <p>Granted, for something simple like one person controlling a single isolated local robot, a REST API may be overkill. But for multi-user and/or unreliable-communications-channels and/or Web-scale-networking, REST is something to consider.</p>
<p>REST principles ensure that your application scales well, and plays well with intermediaries across the internet, (proxies, caching, etc). If your "virtual machine" network is large scale then a RESTful architecture could be advantageous. If you are building a small-scale network, then REST would not be as compelling.</p>
22,471
<p>What is the benefit of referencing resources using globally-unique URIs (as REST does) versus using a proprietary id format?</p> <p>For example:</p> <ol> <li><a href="http://host.com/student/5" rel="nofollow noreferrer">http://host.com/student/5</a></li> <li><a href="http://host.com/student?id=5" rel="nofollow noreferrer">http://host.com/student?id=5</a></li> </ol> <p>In the first approach the entire URL is the ID. In the second approach only the 5 is the ID. What is the practical benefit of the first approach over the second?</p> <p><strike>Why does REST (seem to) go out of its way to advocate the first approach?</strike></p> <p>-- EDIT:</p> <p>My question was confusing because it really asked two separate questions:</p> <ol> <li>What is the benefit of addressibility?</li> <li>What is the difference between the two URI forms seen above.</li> </ol> <p>I've answered both questions below using my own post.</p>
<p>The main thing when i see uri's like that is a normal user would be able to remember that uri. </p> <p>Us geeks are fine with question marks and get variables, but if someone remembers <a href="http://www.host.com/users/john" rel="nofollow noreferrer">http://www.host.com/users/john</a> instead of <a href="http://www.host.com/?view=users&amp;name=john" rel="nofollow noreferrer">http://www.host.com/?view=users&amp;name=john</a>, then that is a huge benefit.</p>
<p>I think it comes down to how closely you want to adhere to the principles of feng shui.</p>
17,717
<p>I have created a web project which references a class library project. When deployed to the local machine the web/classes all work fine but deployed on a ‘shared’ IIS site, the class DLLs exist in the /bin directory, but the web page generates the following error:</p> <p><strong>can’t find file</strong> <strong>“Documents and settings/….”</strong></p> <p>when trying to access the class DLL.</p> <p>Is there a special setup to make the web pages look in its /bin directory?</p> <p><strong>Update: I am using .NET 1.1</strong> and IIS settings are configured for .NET 1.1</p>
<p>sometimes the existence (or absense) of a web.config file in a virtual directory can cause wierd behavior that you've described. Also I've seen where a virtual directory will not look under virtual-directory/bin but rather under base/bin for the corresponding dll.</p>
<p>No by defauls IIS looks for DLL's in the Project/bin folder (not the /bin/Debug). Check if you have the correct dotNET version set in IIS and all referenced libraries in the same folder.</p>
13,939
<p>When developing JavaScript, I tend to separate JavaScript code out into different files and then run a script to concatenate the files and compress or pack the resulting file. In the end, I have one file that I need to include on my production site. </p> <p>This approach has usually worked, but I've started to run into a problems with prototypal inheritance. Specifically, if one class inherits from another class, the file for the parent class needs to be included already for the inheritance to work. If the concatenation script I'm using is simply concatenating a directory full of files, the child class might occur in the code before the parent class. Like this:</p> <p><em>parent_class.js</em></p> <pre><code>var Namespace = Namespace || {}; Namespace.Parent = function () { }; Namespace.Parent.prototype.doStuff = function () { ... }; </code></pre> <p><em>child_class.js</em></p> <pre><code>var NameSpace = Namespace || {}; Namespace.Child = function () { ... }; Namespace.Child.prototype = new Namespace.Parent(); </code></pre> <p>The only way this works is if parent_class.js is included before child_class.js, which might not happen if the concatenation script places the child code before the parent code. </p> <p>Is there a way to write this code so that the functionality is the same, but the order in which the code is written no longer matters?</p> <p>Edit: I forgot that I'm using namespaces as well, so I added that to the code as well, which might change things a little bit.</p>
<blockquote> <p>If the concatenation script I'm using is simply concatenating a directory full of files, the child class might occur in the code before the parent class.</p> </blockquote> <p>Is it too simple a solution to prepend a sort order value to each filename, and sort by name before performing the operation?</p> <p>eg:</p> <pre><code>01_parent.js 02_child.js </code></pre> <p>Otherwise, perhaps maintaining a preordered list of files in a separate file. Maybe even go one step further and provide a hierarchical dependancy structure in xml to parse? This might be over-engineering the solution a bit :-D</p> <p>Some options for ways to deal with the problem if you had no way of determining how the javascript files are written.</p>
<p>I suppose you could do something really hackish like this:</p> <pre><code>setTimeout(function() { if(typeof(Parent) != "undefined" &amp;&amp; typeof(Child) != "undefined") { Child.prototype = new Parent(); } else { setTimeout(arguments.callee, 50); } }, 50); </code></pre> <p>That code could also be anywhere, and would continually run until both the <code>Parent</code> and the <code>Child</code> were loaded...But I wouldn't do that.</p> <p>Personally, I would just make sure your files are combined in the correct order.</p>
35,298
<p>I'm looking for a testing framework for the Windows kernel environment. So far, I've found <a href="http://cfix.sourceforge.net/" rel="noreferrer">cfix</a>. Has any one tried it? Are there alternatives?</p>
<p>Being the author of cfix, I might be a little biased here -- but as a matter of fact, I am currently not aware of any other unit-testing framework for NT kernel mode.</p> <p>If you should experience any problems with cfix, feel free to contact me.</p>
<p><a href="http://www.microsoft.com/whdc/devtools/tools/SDV.mspx" rel="nofollow noreferrer">Microsoft Static Driver Verifier</a> is described as "a compile-time tool that explores code paths in a device driver by symbolically executing the source code. SDV is a unit-testing tool for Microsoft Windows device drivers based on the Windows Driver Model (WDM)."</p> <p>Is that what you're looking for?</p>
3,885
<p>Hi Guys I'm very new to regex, can you help me with this.</p> <p>I have a string like this <code>"&lt;input attribute='value' &gt;"</code> where <code>attribute='value'</code> could be anything and I want to get do a <code>preg_replace</code> to get just <code>&lt;input /&gt;</code></p> <p>How do I specify a wildcard to replace any number of any characters in a srting?</p> <p>like this? <code>preg_replace("/&lt;input.*&gt;/",$replacement,$string);</code></p> <p>Many thanks</p>
<p>What you have: </p> <pre><code>.* </code></pre> <p>will match "any character, and as many as possible. </p> <p>what you <em>mean</em> is </p> <pre><code>[^&gt;]+ </code></pre> <p>which translates to "any character, thats not a ">", and there must be at least one </p> <p>or altertaively, </p> <pre><code>.*? </code></pre> <p>which means "any character, but only enough to make this rule work"</p> <h1>BUT DONT</h1> <p>Parsing HTML with regexps is <strong>Bad</strong></p> <p>use any of the existing html parsers, DOM librarys, anything, Just NOT NAïVE REGEX </p> <p>For example: </p> <pre><code> &lt;foo attr="&gt;"&gt; </code></pre> <p>Will get grabbed wrongly by regex as </p> <pre><code>'&lt;foo attr=" ' with following text of '"&gt;' </code></pre> <p>Which will lead you to this regex: </p> <pre><code> `&lt;[a-zA-Z]+( [a-zA-Z]+=['"][^"']['"])*)&gt; etc etc </code></pre> <p>at which point you'll discover this lovely gem: </p> <pre><code> &lt;foo attr="'&gt;\'\""&gt; </code></pre> <p>and your head will explode. </p> <p>( the syntax highlighter verifies my point, and incorrectly matches thinking i've ended the tag. ) </p>
<pre><code>preg_replace("&lt;input[^&gt;]*&gt;", $replacement, $string); // [^&gt;] means "any character except the greater than symbol / right tag bracket" </code></pre> <p>This is really <em>basic</em> stuff, you should <a href="http://www.regular-expressions.info/php.html" rel="nofollow noreferrer">catch up with some reading</a>. :-)</p>
36,238
<p>If i have a complex XML file, is there a cheap or free way to get a rough approximation of an XSD from it?</p>
<p>A good xml to xsd converter is Trang. It is a command line tool that is very small and does the trick. It can be found on kam's blog - <a href="http://www.dotkam.com/2008/05/28/generate-xsd-from-xml/" rel="nofollow">http://www.dotkam.com/2008/05/28/generate-xsd-from-xml/</a></p>
<p>Yes. There are tools that can analyse your XML and provide an XSD. For example, Visual Studio 2005 and 2008 include a Create XSD command from within the IDE as well as a command line tool, xsd.exe, that will do this.</p> <p>However, note that it can only deduce the XSD from your provided XML, so the XSD may only validate that one file correctly. Once you've created your XSD, you should consider refactoring it against other XML files to ensure it properly fits the format you want to validate.</p>
21,570
<p>i did this in msvc 2005.</p> <pre><code>typedef void (*cleanup_t)(); void func(cleanup_t clean) { cleanup_t(); } </code></pre> <p>Why does this compile? and not give me a warning? ok, it gave me a unreferenced formal parameter warning but originally i did this when clean was in a class no there was no unreferenced formal parameter when this code gave me problems.</p> <p>What is cleanup_t(); really doing and what is the point? now for laughs i tried int() and that worked also.</p>
<p>I think it's an expression that evaluates to a default value for a cleanup_t type. In other words, an expression that returns a NULL pointer to a function that returns void.</p> <p>In C/C++, expressions with no side effects (which this is - I think) are valid statements, just like you can have a statement like:</p> <pre><code>1 + 2; </code></pre> <p>That's not a syntax error, but some compilers might give a warning. They don't often give a warning for side-effect-less expressions that return NULL values or are simply variable names because that type of expression is often used in macros for debugging purposes (like the assert() macro).</p> <p>You can think of it as calling the default constructor for the <code>cleanup_t</code> type. Having this default constructor-like syntax for built-in types (or typedef's of them) was added to C++ so that templates could set items of the type passed in as a template parameter to default values while still allowing the template type parameter to be a non-user defined type. There might other reasons, but I believe that to be one of them.</p> <p>Something like:</p> <pre><code>template &lt;class T&gt; class foo { T myT; public: foo() { myT = T(); }; }; typedef void (*cleanup_t)(); class bar { }; int not_quite_a_cleanup_t_func() { return 1; } int main() { foo&lt;int&gt; intFoo; foo&lt;cleanup_t&gt; cleanup_t_foo; foo&lt;bar&gt; barFoo; // here I'm going to harp on one of the things I don't like about C++: // // That so many things that look like function calls are not or that // the parens cause subtle behavior changes. // // I believe this is the reason this question was posted to // stackoverflow, so it's not too far off topic. // // Many of these things exist because of backwards compatibility with C or // because they wanted to fit in new features without adding keywords or // new reserved tokens or making the parser even more complex than it already // is. So there are probably good rationales for them. // // But I find it confusing more often than not, and the fact that there // might be a rationale for it doesn't mean I have to like it... cleanup_t cleanup1(); // declares a function named cleanup1 that returns a cleanup_t cleanup_t cleanup2 = cleanup_t(); // cleanup2 is a variable of type cleanup_t that // is default initialized cleanup_t* cleanup3 = new cleanup_t; // cleanup3 is a pointer to type cleanup_t that // is initialized to point to memory that is // *not* initialized cleanup_t* cleanup4 = new cleanup_t(); // cleanup4 is a pointer to type cleanup_t that // is initialized to point to memory that *is* // initialized (using default intialization) cleanup2 = cleanup_t( not_quite_a_cleanup_t_func); // explicit type conversion using functional notation cleanup_t(); // the OP's problem cleanup2(); // call the function pointed to by cleanup2 (*cleanup2)(); // same thing class cleanup_class { cleanup_t cleanup5; public: cleanup_class() : cleanup5() // class member default initialization { }; }; } </code></pre>
<p>I think it's an expression that evaluates to a default value for a cleanup_t type. In other words, an expression that returns a NULL pointer to a function that returns void.</p> <p>In C/C++, expressions with no side effects (which this is - I think) are valid statements, just like you can have a statement like:</p> <pre><code>1 + 2; </code></pre> <p>That's not a syntax error, but some compilers might give a warning. They don't often give a warning for side-effect-less expressions that return NULL values or are simply variable names because that type of expression is often used in macros for debugging purposes (like the assert() macro).</p> <p>You can think of it as calling the default constructor for the <code>cleanup_t</code> type. Having this default constructor-like syntax for built-in types (or typedef's of them) was added to C++ so that templates could set items of the type passed in as a template parameter to default values while still allowing the template type parameter to be a non-user defined type. There might other reasons, but I believe that to be one of them.</p> <p>Something like:</p> <pre><code>template &lt;class T&gt; class foo { T myT; public: foo() { myT = T(); }; }; typedef void (*cleanup_t)(); class bar { }; int not_quite_a_cleanup_t_func() { return 1; } int main() { foo&lt;int&gt; intFoo; foo&lt;cleanup_t&gt; cleanup_t_foo; foo&lt;bar&gt; barFoo; // here I'm going to harp on one of the things I don't like about C++: // // That so many things that look like function calls are not or that // the parens cause subtle behavior changes. // // I believe this is the reason this question was posted to // stackoverflow, so it's not too far off topic. // // Many of these things exist because of backwards compatibility with C or // because they wanted to fit in new features without adding keywords or // new reserved tokens or making the parser even more complex than it already // is. So there are probably good rationales for them. // // But I find it confusing more often than not, and the fact that there // might be a rationale for it doesn't mean I have to like it... cleanup_t cleanup1(); // declares a function named cleanup1 that returns a cleanup_t cleanup_t cleanup2 = cleanup_t(); // cleanup2 is a variable of type cleanup_t that // is default initialized cleanup_t* cleanup3 = new cleanup_t; // cleanup3 is a pointer to type cleanup_t that // is initialized to point to memory that is // *not* initialized cleanup_t* cleanup4 = new cleanup_t(); // cleanup4 is a pointer to type cleanup_t that // is initialized to point to memory that *is* // initialized (using default intialization) cleanup2 = cleanup_t( not_quite_a_cleanup_t_func); // explicit type conversion using functional notation cleanup_t(); // the OP's problem cleanup2(); // call the function pointed to by cleanup2 (*cleanup2)(); // same thing class cleanup_class { cleanup_t cleanup5; public: cleanup_class() : cleanup5() // class member default initialization { }; }; } </code></pre>
37,245
<p>I am using this HTML</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;Title&gt;EBAY Search&lt;/title&gt; &lt;/head&gt; &lt;script language="JavaScript" src="ajaxlib.js"&gt;&lt;/script&gt; &lt;body&gt; Click here &lt;a href="#" OnClick="GetEmployee()"&gt;link&lt;/a&gt; to show content &lt;div id="Result"&gt;&lt;The result will be fetched here&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>With this Javascript</p> <pre><code>var xmlHttp function GetEmployee() { xmlHttp=GetXmlHttpObject() if(xmlHttp==null) { alert("Your browser is not supported") } var url="get_employee.php" url=url+"cmd=GetEmployee" url=url+"&amp;sid="+Math.random() xmlHttp.open("GET",url,true) xmlHttp.send(null) } function FetchComplete() { if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById("Result").innerHTML=xmlHttp.responseText } if(xmlHttp.readyState==1 || xmlHttp.readyState=="loading") { document.getElementById("Result").innerHTML="loading" } } function GetXmlHttpObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp =new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } </code></pre> <p>However it is not being called. get_employee.php works fine when I call it by itself, so that is not the problem. Is there anything wrong in my code that would prevent it from being called? I cannot test with any firefox extensions, I do not have access, so please don't give that as an answer.</p> <p>edit: the problem is the javascript is not being called at all. I fixed the question mark problem, but even just a simple javascript with an alert is not being called.</p>
<p>use a javascript debugging tool like firebug, this will make your life simpler.</p> <p>you had a syntax error in your code that made the error "GetEmployee is not defined"</p> <p>it was a missing "catch" after the last try in "GetXmlHttpObject()". this is the same function after adding the missing "catch".</p> <pre><code>function GetXmlHttpObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); }catch (e) { try { xmlHttp =new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } return xmlHttp; } </code></pre>
<p>var url="get_employee.php" <strong><em>+ "?"</em></strong></p> <p>(answering the comment)</p> <p><em>What</em> error is reported? You still have to attach your FetchComplete function to xmlHttp's "onreadystatechange" property, but it shouldn't be an error not to do it.</p> <p>Make sure that ajaxlib.js is really loaded, and that it is the file you mean. Put some alerts and see if they pop up.</p>
39,245
<p>How do I discard changes in my working copy that are not in the index?</p>
<p>For all <em>unstaged</em> files in current working directory use:</p> <pre><code>git restore . </code></pre> <p>For a specific file use:</p> <pre><code>git restore path/to/file/to/revert </code></pre> <p>That together with <code>git switch</code> replaces the overloaded <code>git checkout</code> (<a href="https://stackoverflow.com/questions/58003030/what-is-the-git-restore-command-and-what-is-the-difference-between-git-restor">see here</a>), and thus removes the argument disambiguation.</p> <p>If a file has both staged and unstaged changes, only the unstaged changes shown in <code>git diff</code> are reverted. Changes shown in <code>git diff --staged</code> stay intact.</p> <p><strong>Before Git 2.23</strong></p> <p>For all unstaged files in current working directory:</p> <pre><code>git checkout -- . </code></pre> <p>For a specific file:</p> <pre><code>git checkout -- path/to/file/to/revert </code></pre> <p><code>--</code> here to remove ambiguity (this is known as <a href="https://git-scm.com/docs/git-checkout#_argument_disambiguation" rel="noreferrer">argument disambiguation</a>).</p>
<p>To delete unstaged changes I tried &quot;git restore .&quot; as I was told by Git but it just didn't work. A very good way is to use:</p> <pre><code>git revert --hard </code></pre> <p>It works perfectly. Its Git Help explains perfectly the point:</p> <blockquote> <p><strong>--hard</strong> Resets the index and working tree. <strong>Any changes to tracked files in the working tree since are discarded.</strong> Any untracked files or directories in the way of writing any tracked files are simply deleted.</p> </blockquote> <p>PS: I am using git version 2.35.3.windows.1. I think quite some answers here made the issue over-complicated.</p>
7,598
<p>Is there any way to apply an attribute to a model file in ASP.NET Dynamic Data to hide the column?</p> <p>For instance, I can currently set the display name of a column like this:</p> <pre><code>[DisplayName("Last name")] public object Last_name { get; set; } </code></pre> <p>Is there a similar way to hide a column?</p> <p><strong>Edit</strong>: Many thanks to Christian Hagelid for going the extra mile and giving a spot-on answer :-)</p>
<p>Had no idea what ASP.NET Dynamic Data was so you promted me to so some research :)</p> <p>Looks like the property you are looking for is </p> <pre><code>[ScaffoldColumn(false)] </code></pre> <p>There is also a similar property for tables</p> <pre><code>[ScaffoldTable(false)] </code></pre> <p><a href="http://davidhayden.com/blog/dave/archive/2008/05/15/DynamicDataWebsitesScaffoldTableScaffoldColumnAttributes.aspx" rel="noreferrer">source</a></p>
<p>A much, much easier method: If you want to only show certain columns in the List page, but all or others in the Details, etc. pages, see <a href="https://stackoverflow.com/questions/80175/how-do-i-hide-a-column-only-on-the-list-page-in-asp-net-dynamic-data">How do I hide a column only on the list page in ASP.NET Dynamic Data?</a></p> <p>Simply set AutoGenerateColumns="false" in the GridView control, then define exactly the columns you want:</p> <p>&lt;Columns><br/> ...<br/> &lt;asp:DynamicField DataField="FirstName" HeaderText="First Name" /><br/> &lt;asp:DynamicField DataField="LastName" HeaderText="Last Name" /><br/> &lt;/Columns></p>
4,526
<p>I'm currently looking at indexing an ASP website from Sharepoint and I need to replicate the old "advanced search" schema that the users are familiar with. In order to do this I need to index a few meta tags from the web pages. This is easily done and for the text fields I can use them in the search as well. However for date meta tags, like "expired" or "published" I'm having some problems. The problem is basically that the meta tags are crawled as "text", but I need Sharepoint to parse them as datetime. I've seen a few posts on <a href="https://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=2614064&amp;SiteID=17" rel="noreferrer">TechNet</a> asking for the same, but with no answer.</p> <p><a href="https://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=2614064&amp;SiteID=17" rel="noreferrer">1</a>: <a href="https://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=2614064&amp;SiteID=17" rel="noreferrer">https://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=2614064&amp;SiteID=17</a> TechNet</p>
<p>You're not doing anything wrong, this is how the product works. To add to what was said earlier, it's not easy to customize.</p> <p>The proper way to approach this is to create a custom protocol handler for HTML. This is a custom COM Object that implements a few interfaces. The MOSS 2007 SDK has a protocol handler reference. </p> <p>When we did this, we created an ini file so we could define the type we wanted META fields crawled as (String, Int, DateTime). Then when you added the custom properties everything was properly parsed. Then you can use the custom properties like you would normally.</p>
<p>The web crawler built into search is rudimentary and you won't be able to easily extend it to include meta tags. Allegedly you can write your own protocol handler and crawl the ASP pages in their own content source; allegedly that works. I don't think anyone actually writes their own protocol handlers though.</p> <p>You're going to be disappointed with what the SharePoint crawler offers, which is why there are no answers on the official forum either--because the real answer is "Can't do that easily, sorry."</p> <p>You may be able to hack something up by writing a custom web service (ASMX or WCF-based) that itself crawls the ASP pages' meta tags. From there, you could pull the web service results into the BDC which is searchable, and then in the search results/BDC data you can have a link to the original page. It's like a Rube Goldberg device, I know, but trust me when I say it will be easier than figuring out how to write a protocol handler.</p>
20,068
<p>When i deploy a rails application in production mode, it appends a date-time string as a query param to the end of all the static asset urls. This is to prevent browsers using old-out of date cahed copies of the assets after I redeploy the application. </p> <p>Is there a way to make rails use the old time stamps for the assets that have not changed (and <strong>only</strong> the ones that have not changed) since the last deployment. I want to do this to prevent users having to redownload those assets that have not changed.</p>
<p>I think you can use ENV['RAILS_ASSET_ID'] to alter the cache-busting asset ID. Unfortunately, this is for all assets.</p> <p>But if it's not set, it uses the asset's source modification time. If that file hasn't been modified since the last time you used it, it shouldn't be a problem.</p> <p>If the asset ID is changing when they haven't been changed, it might be because of your deployment process altering the modification time and maybe you could look at tweaking that.</p> <p>Lastly, you can always <a href="http://geekblog.vodpod.com/?p=88" rel="noreferrer">override rails_asset_id with your own custom method</a>.</p> <p>Hope this helps.</p>
<p>@Aupajo I like this, but I think I can take it a bit further. The problem here is that capistrano does create new copies of all the files on every deploy, so all the cache-busting strings are changed. However an MD5 of the file would only change when the file content changes. </p> <p>Of course, generating an MD5 is expensive and slow, but you can cache the MD5 of a file in memcache, (keyed on the change time, as if the time has changed the MD5 <strong>may</strong> have changed, but if the timestamp has not changed the MD5 <strong>will not</strong> have changed</p>
22,118
<p>Where can i find some .Net or conceptual resources to start working with Natural Language where I can pull context and subjects from text. I wish not to work with word frequency algorithms.</p>
<p>To find resources in part of speech tagging (a natural language processing task) look at this: </p> <ul> <li><a href="http://nltk.sourceforge.net/index.php/Book" rel="nofollow noreferrer">Natural Language Toolkit</a></li> <li><a href="http://search.cpan.org/dist/Lingua-EN-Tagger/Tagger.pm" rel="nofollow noreferrer">PoS tagger in perl</a></li> <li><a href="http://www.lsi.upc.es/~nlp/SVMTool/" rel="nofollow noreferrer">SVM Tool</a></li> <li><a href="http://nlp.stanford.edu/software/tagger.shtml" rel="nofollow noreferrer">NLP Group at Stanford</a></li> </ul> <p>Hope it helps.</p>
<p>Hank's tag change leads to <a href="https://stackoverflow.com/questions/88984/your-favorite-natural-language-parser">a list of parsers</a> and to <a href="https://stackoverflow.com/questions/25332/whats-a-good-natural-language-library-to-use-for-paraphrasing">libraries</a></p>
15,482
<p>I had the following line snippet of code that searches for a propery of an instance by name:</p> <pre><code>var prop = Backend.GetType().GetProperty(fieldName); </code></pre> <p>Now I want to ignore the case of fieldName, so I tried the following:</p> <pre><code>var prop = Backend.GetType().GetProperty(fieldName, BindingFlags.IgnoreCase); </code></pre> <p>... No dice. Now prop won't find field names that have the exact case.</p> <p>Hence..... How do I use .Net reflection to search for a property by name ignoring case?</p>
<p>You need to specify <code>BindingFlags.Public | BindingFlags.Instance</code> as well:</p> <pre><code>using System; using System.Reflection; public class Test { private int foo; public int Foo { get { return foo; } } static void Main() { var prop = typeof(Test).GetProperty("foo", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); Console.WriteLine(prop); } } </code></pre> <p>(When you don't specify any flags, public, instance and static are provided by default. If you're specifying it explicitly I suggest you only specify one of instance or static, if you know what you need.)</p>
<p>Try adding the scope BindingFlags like so:</p> <pre><code>var prop = Backend.GetType().GetProperty(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase); </code></pre> <p>This works for me. </p>
35,294
<p>I have what must be a typical catch-22 problem. I have a .NET WinForm control that contains a textbox and a checkbox. Both controls are data bound to properties on a data class instance. The textbox is for price, the check box to indicate that the price is a price override. Also on the data class is a property that holds the item's original price.</p> <p>I would like the controls to respect the following rules:</p> <ul> <li>When the user enters a value into the price textbox, the checkbox is automatically checked to indicate they are overriding the price value</li> <li>When the check box is un-checked, the item's price is restored to the original price.</li> </ul> <p>When the user unchecks the checkbox, the event handler tests the checked state, and sets the item's price property to the original price value. However, the price value being databound, a bind event is fired, which updates the textbox value, which fires the text changed event handler which re-checks the checkbox. </p> <p>I've attempted to trap the conditions where I'm explicitly updating something that would trigger a control change event. This only works for part of it though. The textbox change event fires other times that are outside my control, such as when databinding fires when the form is initially shown.</p> <p>I've been searching around and I guess I'm just not coming up with the right search terms to find what I'm looking for. It seems that databinding is all wonderful and nifty until you need to do something pratical with it, like having two bound controls interact with each other. There just doesn't seem to be a way to discriminate between what triggered the control events.</p> <p>I've also looked at the events available on the binding source component but there doesn't seem to be anything there that is any more useful. I can handle the event that fires after binding is complete, but that's after the problems occur.</p> <p>Anyone have any suggestions?</p>
<p>I would suggest not handling the logic in the form code, but rather in the data class. All you need in the form is a couple of lines to set up the data binding. The data class can then take care of the rest:</p> <p>Form</p> <pre><code>Private _dc As DataClass Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load _dc = New DataClass txtPrice.DataBindings.Add("text", _dc, "Price") chkOverride.DataBindings.Add("checked", _dc, "override") End Sub </code></pre> <p>Data Class</p> <pre><code>Private _originalPrice As Double = 50 Private _price As Double = _originalPrice Public Property Price() As Double Get Return _price End Get Set(ByVal value As Double) If (_price &lt;&gt; value) Then _price = value Override = _price &lt;&gt; _originalPrice End If End Set End Property Private _override As Boolean Public Property Override() As Boolean Get Return _override End Get Set(ByVal value As Boolean) If _override &lt;&gt; value Then _override = value If Not _override Then Price = OriginalPrice End If End Set End Property </code></pre> <p>No need to handle any CheckedChanged or TextChanged events in the form.</p>
<p>Have you considered handling the TextBox <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.textchanged(VS.80).aspx" rel="nofollow noreferrer">TextChanged</a> event to handle the CheckBox state instead of binding it?</p> <p>You could then compare the current TextBox value to the original and determine if the CheckBox should be true or false.</p> <p>Another thought is you could inherit TextBox and add properties to your custom TextBox so the TextBox handles it's own state. For example it can have a read-only IsOriginal property. </p> <p>I don't have VS installed right now so I didn't verify it, let me know if you want an example.</p>
24,902
<p>When using a class that has an enum property, one usually gets a naming conflict between the property name and the enum type. Example:</p> <pre><code>enum Day{ Monday, Tuesday, ... } class MyDateClass { private Day day; public Day Day{ get{ return day; } } } </code></pre> <p>Since only flags enums should have plural names, naming the enum "Days" is not the way to go for a non-flag enum. In the above example you could use some variation like "WeekDay" for either the enum or the property. But in the general case there are no good variations like that so you end up using properties like "FooMode" or "BarKind" for an object with enum properties of Foo and Bar type. Not so elegant.</p> <p>How do you usually name enums and properties in this scenario? </p> <hr> <p>Thanks for the quick responses. Another question: why is it not recommended to nest public enums, and how do you resolve the naming issues if you want to nest public enums?</p> <pre><code>class Vehicle { enum Kind{ Car, Bike } public Kind Kind{ get{ return ... } } } class Meal { enum Kind{ Dessert, MainCourse } public Kind Kind{ get{ return ... } } } </code></pre> <p>In the scenario above, given that Meal and Vehicle share the same namespace, I can't move "Kind" outside either of the classes without renaming it MealKind and VehicleKind respectively. I like the look of </p> <pre><code>myVehicle.Kind = Vehicle.Kind.Car </code></pre> <p>But that is not what the guidlines recommend. What would be the best practice here? Never to use nested public enums and instead name them VehicleKind etc.? </p>
<p>There is no conflict. In fact, the <a href="http://msdn.microsoft.com/en-us/library/ms229012.aspx" rel="noreferrer">.NET Framework style guide encourages you to do this</a>, e.g. if you have a class that has a single property of a type (no matter if enum or class), then you should name it the same. Typical example is a Color property of type Color. It's fine, unless there are two colors - in that case both should add something to the name (i.e. BackColor and ForeColor, instead of Color and BackColor).</p>
<p>So long as the enumeration isn't nested within MyDateClass, I don't see that that's a problem. It's far from uncommon (in my experience) to have a property with the same name as the type it returns. I'll see if I can find some examples in the framework...</p> <p>EDIT: First example: DateTimeOffset.DateTime (not an enum, but that's somewhat irrelevant)</p>
26,003
<p>It's my understanding that common wisdom says to only use exceptions for truly exceptional conditions (In fact, I've seen that statement here at SO several times). </p> <p>However, Krzysztof Cwalina says:</p> <blockquote> <blockquote> <p>One of the biggest misconceptions about exceptions is that they are for “exceptional conditions.” The reality is that they are for communicating error conditions. From a framework design perspective, there is no such thing as an “exceptional condition”. Whether a condition is exceptional or not depends on the context of usage, --- but reusable libraries rarely know how they will be used. For example, OutOfMemoryException might be exceptional for a simple data entry application; it’s not so exceptional for applications doing their own memory management (e.g. SQL server). In other words, one man’s exceptional condition is another man’s chronic condition.</p> </blockquote> </blockquote> <p>He then also goes on to say that exceptions should be used for: </p> <ul> <li>Usage errors</li> <li>Program errors</li> <li>System failures</li> </ul> <p>Considering Krzysztof Cwalina is the PM for the CLR team at MS I ask: What do you think of his statement? </p>
<p>This sounds over-simplistic, but I think it makes sense to simply use exceptions where they are appropriate. In languages like Java and Python, exceptions are very common, especially in certain situations. Exceptions are appropriate for the type of error you want to bubble up through a code path and force the developer to explicitly catch. In my own coding, I consider the right time to add an exception when the error either can't be ignored, or it's simply more elegant to throw an exception instead of returning an error value to a function call etc. </p> <p>Some of the most appropriate places for exceptions that I can think of offhand: </p> <ul> <li><strong>NotImplementedException</strong> - very appropriate way of designating that a particular method or function isn't available, rather than simply returning without doing anything.</li> <li><strong>OutOfMemory</strong> exceptions - it's difficult to imagine a better way of handling this type of error, since it represents a process-wide or OS-wide memory allocation failure. This is essential to deal with, of course!</li> <li><strong>NullPointerException</strong> - Accessing a null variable is a programmer mistake, and IMO this is another good place to force an error to bubble to the surface</li> <li><strong>ArrayIndexException</strong> - In an unforgiving language like C, buffer overflows are disastrous. Nicer languages might return a null value of some type, or in some implementations, even wrap around the array. In my opinion, throwing an exception is a much more elegant response.</li> </ul> <p>This is by no means a comprehensive list, but hopefully it illustrates the point. Use exceptions where they are elegant and logical. As always with programming, the right tool for the right job is good advice. There's no point going exception-crazy for nothing, but it's equally unwise to completely ignore a powerful and elegant tool at your disposal.</p>
<p>KCwalina has a point. It will be good to identify cases where the code will fail (upto a limit)</p> <p>I agree with S.Lott that sometimes validating is better than to throw Exception. Having said that, OutOfMemory is not what you might expect in your application (unless it is allocating a large memory &amp; needs memory to go ahead).</p> <p>I think, it depends on the domain of the application.</p>
21,830
<p>We are working on a large project with a measure of new/modified GUI functionality. We've found in the past that we often introduced new problems in related code when adding new functionality.</p> <p>We have non-technical users perform testing, but they often miss parts and allow bugs to slip through.</p> <p>Are there any best practices for organizing the UI testing of a WinForms project? Is there any way to automate it?</p>
<p>There are GUI testing tools that will click buttons and stuff for you but they're pretty fragile in my experience.</p> <p>The best thing to do is to keep your UI layer as thin as possible. Your event handler classes should optimally be only one or two lines that call out to other more testable classes. That way you can test your business logic in unit tests without having to actually do a button click.</p>
<p>I can't really help with organization or best practices, but an <a href="http://www.nunit.org/index.php" rel="nofollow noreferrer">NUnit</a> extension appears to be available for forms testing, <a href="http://www.google.com/search?q=nunitforms" rel="nofollow noreferrer">NUnitForms</a>.</p>
6,294
<p>I seemed to get the following exception when trying to deploy my application:</p> <pre><code>Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions java.util.List is an interface, and JAXB can't handle interfaces. this problem is related to the following location: at java.util.List at private java.util.List foobar.alkohol.register.webservice.jaxws.GetRelationsFromPersonResponse._return at foobar.alkohol.register.webservice.jaxws.GetRelationsFromPersonResponse java.util.List does not have a no-arg default constructor. this problem is related to the following location: at java.util.List at private java.util.List foobar.alkohol.register.webservice.jaxws.GetRelationsFromPersonResponse._return at foobar.alkohol.register.webservice.jaxws.GetRelationsFromPersonResponse </code></pre> <p><strong><br/>My code worked just well until I changed the return type from List to List&lt;List&lt;RelationCanonical&gt;&gt;</strong></p> <p>Here is the partial webservice:</p> <pre><code> @Name("relationService") @Stateless @WebService(name = "RelationService", serviceName = "RelationService") @SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED) public class RelationService implements RelationServiceLocal { private boolean login(String username, String password) { Identity.instance().setUsername(username); Identity.instance().setPassword(password); Identity.instance().login(); return Identity.instance().isLoggedIn(); } private boolean logout() { Identity.instance().logout(); return !Identity.instance().isLoggedIn(); } @WebMethod public List&lt;List&lt;RelationCanonical&gt;&gt; getRelationsFromPerson(@WebParam(name = "username") String username, @WebParam(name = "password") String password, @WebParam(name = "foedselsnummer") String... foedselsnummer) { ...... ...... ...... } </code></pre> <p><br/> <strong>I have also tried by removing the @SOAPBinding and trying default, but the same result occurs. Appreciate any help</strong></p> <p><strong>UPDATE</strong></p> <p>I want to note out something. I changed all List to ArrayList, and then it compiled. The reason why I say compiled and not worked is because it behaves strange. I get an Object of type: RelationServiceStub.ArrayList but the object has no get methods or does not behave as a List either. I also tried to cast it to a List but that didnt work.</p> <p>Note that this is after I have used Axis 2 and wsdl2java So yes, now it compiles, but I dont know how to get the data out.</p>
<p>In my understanding, you will not be able to process a plain <code>List</code> via JAXB, as JAXB has no idea how to transform that into XML. </p> <p>Instead, you will need to define a JAXB type which holds a <code>List&lt;RelationCanonical&gt;</code> (I'll call it <code>Type1</code>), and another one to hold a list of those types, in turn (as you're dealing with a <code>List&lt;List&lt;...&gt;&gt;</code>; I'll call this type <code>Type2</code>).</p> <p>The result could then be an XML ouput like this:</p> <pre><code>&lt;Type2 ...&gt; &lt;Type1 ...&gt; &lt;RelationCanonical ...&gt; ... &lt;/RelationCanonical&gt; &lt;RelationCanonical ...&gt; ... &lt;/RelationCanonical&gt; ... &lt;/Type1&gt; &lt;Type1&gt; &lt;RelationCanonical ...&gt; ... &lt;/RelationCanonical&gt; &lt;RelationCanonical ...&gt; ... &lt;/RelationCanonical&gt; ... &lt;/Type1&gt; ... &lt;/Type2&gt; </code></pre> <p>Without the two enclosing JAXB-annotated types, the JAXB processor has no idea what markup to generate, and thus fails.</p> <p>--Edit: </p> <p>What I mean should look somewhat like this: </p> <pre><code>@XmlType public class Type1{ private List&lt;RelationCanonical&gt; relations; @XmlElement public List&lt;RelationCanonical&gt; getRelations(){ return this.relations; } public void setRelations(List&lt;RelationCanonical&gt; relations){ this.relations = relations; } } </code></pre> <p>and</p> <pre><code>@XmlRootElement public class Type2{ private List&lt;Type1&gt; type1s; @XmlElement public List&lt;Type1&gt; getType1s(){ return this.type1s; } public void setType1s(List&lt;Type1&gt; type1s){ this.type1s= type1s; } } </code></pre> <p>You should also check out the <a href="http://java.sun.com/javaee/5/docs/tutorial/doc/bnazf.html" rel="noreferrer">JAXB section in the J5EE tutorial</a> and the <a href="http://jaxb.java.net/guide/Mapping_interfaces.html" rel="noreferrer">Unofficial JAXB Guide</a>.</p>
<p>You can use "ArrayList" instead of inner "List"</p>
38,253
<p>I am precisely looking for the info like ,</p> <p>TAP is for regression and TDD is for Unit Testing ... or are they mutually exclusive( no need to use both of them ) ? </p> <p>bonus for suggesting 'good' Unit Test Frame work for TDD in C (expecting to address good aspect as well :) )</p> <p>finally cMockery (googles code) for Testing C code (not derived from xUnit Patterns) can be used for TDD ? how ? </p> <p><strong>added for clarity:</strong> TAP is test anything protocol , you can find documentation in CPAN (perl archive). libtap is TAP for C. <a href="http://www.onlamp.com/pub/a/onlamp/2006/01/19/libtap.html?page=1" rel="nofollow noreferrer">http://www.onlamp.com/pub/a/onlamp/2006/01/19/libtap.html?page=1</a> gives good explanation of TAP in </p>
<p>For unit testing frameworks for C, you can refer to this <a href="https://stackoverflow.com/questions/177251/unit-testing-frameworks-for-c">question</a>. </p> <p>There is no conflict between regression and unit testing, as the unit tests are used as a safety net to detect undesired changes. </p> <p>You certainly can use TAP for TDD, there is no contraindication. If you already use Perl Test::More, then sharing the same output format can be helpful. </p> <hr> <p>Why do you ask wheter cMockery can be used for TDD ? DO you think it cannot ? why ? </p> <p><strong>TDD and unit test frameworks are just means, not ends.</strong> </p>
<p>I guess you're referring to this <a href="http://tap.ethz.ch/2007/index.html" rel="nofollow noreferrer">TAP</a>: "Tests and Proofs". TAP is a conference where people talk about TDD and ways to mathematically prove that a program is correct. So the two are not really related (Way to write software vs. a forum where you can talk about this topic).</p> <p>TDD is used for both unit tests as for regression testing. For details, see <a href="https://stackoverflow.com/questions/2260/what-is-tdd">this answer</a>.</p> <p>I haven't used any TDD frameworks for C but googling for "unit testing c" yields a couple of interesting links.</p>
43,211
<p>How many bytes would an int contain and how many would a long contain?</p> <p>Context:</p> <ul> <li>C++</li> <li>32 bit computer</li> <li>Any difference on a 64-bit computer?</li> </ul>
<p>See <a href="http://en.wikipedia.org/wiki/Integer_(computer_science)" rel="nofollow noreferrer">the wikipedia article about it</a>.</p>
<p>It depends on your compiler. And your language, for that matter. Try asking a more specific question.</p>
19,817
<p>Edit: How to return/serve a file from a python controller (back end) over a web server, with the file_name? as suggested by @JV</p>
<p>You can either pass back a reference to the file itself i.e. the full path to the file. Then you can open the file or otherwise manipulate it.</p> <p>Or, the more normal case is to pass back the file handle, and, use the standard read/write operations on the file handle.</p> <p>It is not recommended to pass the actual data as files can be arbiterally large and the program could run out of memory.</p> <p>In your case, you probably want to return a tuple containing the open file handle, the file name and any other meta data you are interested in.</p>
<p>For information on MIME types (which are how downloads happen), start here: <a href="https://developer.mozilla.org/en/Properly_Configuring_Server_MIME_Types" rel="nofollow noreferrer">Properly Configure Server MIME Types</a>.</p> <p>For information on CherryPy, look at the attributes of a <a href="http://www.cherrypy.org/wiki/ResponseObject" rel="nofollow noreferrer">Response</a> object. You can set the <a href="http://www.cherrypy.org/wiki/ResponseObject#headers" rel="nofollow noreferrer">content type</a> of the response. Also, you can use <a href="http://www.cherrypy.org/wiki/BuiltinTools#tools.response_headers" rel="nofollow noreferrer">tools.response_headers</a> to set the content type.</p> <p>And, of course, there's an example of <a href="http://www.cherrypy.org/wiki/FileDownload" rel="nofollow noreferrer">File Download</a>.</p>
45,874
<p>Can anyone suggest some good browser add-on tools/extensions to help with development? I have firebug installed in Firefox which is great for dealing with CSS, HTML and javascript; any other suggestions?</p> <p><a href="https://addons.mozilla.org/en-US/firefox/addon/1843" rel="nofollow noreferrer">Firebug</a></p>
<p>Firefox:</p> <ul> <li><a href="https://addons.mozilla.org/en-US/firefox/addon/1913" rel="nofollow noreferrer">Inspect This</a> if you use the DOM Inspector at all</li> <li><a href="https://addons.mozilla.org/en-US/firefox/addon/539" rel="nofollow noreferrer">Measure It</a> for telling you pixel distances (if you need that)</li> <li><a href="https://addons.mozilla.org/en-US/firefox/addon/35" rel="nofollow noreferrer">IE View</a> or <a href="https://addons.mozilla.org/en-US/firefox/addon/4641" rel="nofollow noreferrer">Safari View</a> for ease of testing in other browsers</li> <li><a href="https://addons.mozilla.org/en-US/firefox/addon/249" rel="nofollow noreferrer">HTML Validator</a> if you care about validation</li> <li><a href="https://addons.mozilla.org/en-US/firefox/addon/1815" rel="nofollow noreferrer">Console<sup>2</sup></a> to improve your js error console</li> <li>The <a href="https://www.squarefree.com/bookmarklets/webdevel.html" rel="nofollow noreferrer">Javascript Shell</a> bookmarklet is also handy (and look at the others there as well)</li> </ul> <p>Edit: This is in addition to the <a href="https://addons.mozilla.org/en-US/firefox/addon/60" rel="nofollow noreferrer">Web Development Toolbar</a> mentioned by others</p>
<p>Other than the excellent tools already mentioned, I find <a href="http://www.charlesproxy.com/" rel="nofollow noreferrer">Charles</a> to be extremely useful. Especially since I do alot of work with Flash Remoting which it handles excellently.</p> <blockquote> <p>Charles is an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP traffic between their machine and the Internet. This includes requests, responses and the HTTP headers (which contain the cookies and caching information).</p> <p>Charles can act as a man-in-the-middle for HTTP/SSL communication, enabling you to debug the content of your HTTPS sessions.</p> </blockquote> <p>It's crossplatform, costs $50, but there's a &quot;30 minute per session&quot;-evaluation you can download.</p>
3,817
<p>It has been a few years since I used Actionscript. Back in the day, I made a project that emulated a QTVR panorama (at the time I was using Flash, you could only embed very basic mov files) by simply moving a very long flattened pano image left or right behind a mask. The effect was okay, but not as nice as a real pano, since the perspective was so warped. So now that a couple iterations of Flash have been developed I am curious...</p> <p>Is there a way now to get a bit closer to a real QTVR? ...or is it now possible to embed a real QTVR?</p>
<p>My advice would be - download <a href="http://blog.papervision3d.org/" rel="nofollow noreferrer">PaperVision</a>, cut your image into strips, then arrange these in ring as 3d planes. </p>
<p>My advice would be - download <a href="http://blog.papervision3d.org/" rel="nofollow noreferrer">PaperVision</a>, cut your image into strips, then arrange these in ring as 3d planes. </p>
14,021
<p>I am in the process of writing a text editor. After looking at other text editors I have noticed that a number of them refer to a "soft" versus "hard" wrap. What is the difference? I can't seem to find the answer by searching.</p>
<p>A hard wrap inserts actual line breaks in the text at wrap points, with soft wrapping the actual text is still on the same line but looks like it's divided into several lines.</p>
<p>It's usual for text editors to auto-wrap text into paragraphs with hard newlines, but it's less common for the text to be re-flowed into a nice paragraph if you come back later and edit/add/remove words later on. (You can do this manually in emacs with M-q.) </p> <p>This is rather annoying, since obsessive compulsive people like me then go back and have to manually re-insert the hard breaks at the appropriate points.</p> <p>On the other hand, soft wrapping is annoying because most all command line tools use line-based diff-ing (version control is where this becomes most noticeable to me). If you've got a 1/3-page paragraph that's soft wrapped and fix a typo, it's basically impossible to see where the change is in a regular <code>diff</code> output or similar.</p>
41,375
<p>In postgres you can do a comparison against multiple items like so:</p> <pre><code> SELECT 'test' IN ('not','in','here'); </code></pre> <p>Which is the same as doing:</p> <pre><code> SELECT ('test' = 'not' OR 'test' = 'in' OR 'test' = 'here'); </code></pre> <p>Is there a functional equivalent for SQL Server ?</p>
<p>It is supported, but you will need to put the expression somewhere that accepts a boolean expression. For example, in a <code>case</code> statement:</p> <pre><code>select case when 'test' in ('not','in','here') then 1 else 0 end ----------- 0 (1 row(s) affected) </code></pre> <p>Or a <code>where</code> clause:</p> <pre><code>select * from T where C in (1,3,5,7,9) </code></pre>
<p>this should give similar results in all recent versions of MSSQL. You could also write a scalar function to shorten things up a bit.</p> <pre><code>select case when 'test' IN ('not', 'in', 'here') then 1 else 0 end; </code></pre>
44,341
<p>What approach did you take to describe the benefits of SCRUM to clients / business units who do not have a technical background? Please list any analogies you thought were useful. Finally, how did you address the concerns that the Waterfall camp had?</p>
<p>I basically go around about risk reduction and ROI, since these are the main things people at the higher management level care about.</p> <p>Using a incremental process significantly reduces the risk of wasting money on something that's not gonna be useful, because the customer helps steer the product development in the right direction through series of planned feedback cycles. The #1 reason for project failure according to the CHAOS research is lack of customer involvement. So why not use a process that eliminates that risk?</p> <p>Also, with a incremental process you start delivering something in a much shorter time than when using a waterfall approach, which effectively increases the ROI (return on investment), since the customer starts benefiting from the product after one or two months, instead of waiting 6 to 12 months in a typical waterfall project.</p> <p>You can also mention improved customer satisfaction, team self-improvement and self-management, which reduces the administrative overhead, improved employee satisfaction.</p>
<p>I would mention the benefits of focus. Because the guiding principle of sprints is functional focus and shipability, all details (e.g. ergonomics) need to be taken care of, whose fixing would otherwise be postponed under pressure in more global approaches. You don't have it all but what you have is solid. Non technical people appreciate that because it reduces risk from their point of view: it injects honesty and trust, together with interactivity, in the dialog with clients.</p>
39,751
<p>Admittedly I don't get it. Say you have a memory with a memory word of length of 1 byte. Why can't you access a 4 byte long variable in a single memory access on an unaligned address(i.e. not divisible by 4), as it's the case with aligned addresses?</p>
<p>The memory subsystem on a modern processor is restricted to accessing memory at the granularity and alignment of its word size; this is the case for a number of reasons.</p> <h2>Speed</h2> <p>Modern processors have multiple levels of cache memory that data must be pulled through; supporting single-byte reads would make the memory subsystem throughput tightly bound to the execution unit throughput (aka cpu-bound); this is all reminiscent of how <a href="http://www.differencebetween.net/technology/difference-between-dma-and-pio/" rel="noreferrer">PIO mode was surpassed by DMA</a> for many of the same reasons in hard drives.</p> <p>The CPU <strong>always</strong> reads at its word size (4 bytes on a 32-bit processor), so when you do an unaligned address access — on a processor that supports it — the processor is going to read multiple words. The CPU will read each word of memory that your requested address straddles. This causes an amplification of up to 2X the number of memory transactions required to access the requested data.</p> <p>Because of this, it can very easily be slower to read two bytes than four. For example, say you have a struct in memory that looks like this:</p> <pre><code>struct mystruct { char c; // one byte int i; // four bytes short s; // two bytes } </code></pre> <p>On a 32-bit processor it would most likely be aligned like shown here:</p> <p><img src="https://i.stack.imgur.com/Vkg0j.png" alt="Struct Layout" /></p> <p>The processor can read each of these members in one transaction.</p> <p>Say you had a packed version of the struct, maybe from the network where it was packed for transmission efficiency; it might look something like this:</p> <p><img src="https://i.stack.imgur.com/Ebcwt.png" alt="Packed Struct" /></p> <p>Reading the first byte is going to be the same.</p> <p>When you ask the processor to give you 16 bits from 0x0005 it will have to read a word from 0x0004 and shift left 1 byte to place it in a 16-bit register; some extra work, but most can handle that in one cycle.</p> <p>When you ask for 32 bits from 0x0001 you'll get a 2X amplification. The processor will read from 0x0000 into the result register and shift left 1 byte, then read again from 0x0004 into a temporary register, shift right 3 bytes, then <code>OR</code> it with the result register.</p> <h2>Range</h2> <p>For any given address space, if the architecture can assume that the 2 LSBs are always 0 (e.g., 32-bit machines) then it can access 4 times more memory (the 2 saved bits can represent 4 distinct states), or the same amount of memory with 2 bits for something like flags. Taking the 2 LSBs off of an address would give you a 4-byte alignment; also referred to as a <a href="http://en.wikipedia.org/wiki/Stride_of_an_array" rel="noreferrer">stride</a> of 4 bytes. Each time an address is incremented it is effectively incrementing bit 2, not bit 0, i.e., the last 2 bits will always continue to be <code>00</code>.</p> <p>This can even affect the physical design of the system. If the address bus needs 2 fewer bits, there can be 2 fewer pins on the CPU, and 2 fewer traces on the circuit board.</p> <h2>Atomicity</h2> <p>The CPU can operate on an aligned word of memory atomically, meaning that no other instruction can interrupt that operation. This is critical to the correct operation of many <a href="http://kukuruku.co/hub/cpp/lock-free-data-structures-basics-atomicity-and-atomic-primitives" rel="noreferrer">lock-free data structures</a> and other <a href="http://www.sciencedirect.com/science/article/pii/0304397588900965" rel="noreferrer">concurrency</a> paradigms.</p> <h2>Conclusion</h2> <p>The memory system of a processor is quite a bit more complex and involved than described here; a discussion on <a href="http://www.rcollins.org/articles/pmbasics/tspec_a1_doc.html" rel="noreferrer">how an x86 processor actually addresses memory</a> can help (many processors work similarly).</p> <p>There are many more benefits to adhering to memory alignment that you can read at <a href="https://developer.ibm.com/technologies/systems/articles/pa-dalign/" rel="noreferrer">this IBM article</a>.</p> <p>A computer's primary use is to transform data. Modern memory architectures and technologies have been optimized over decades to facilitate getting more data, in, out, and between more and faster execution units–in a highly reliable way.</p> <h2>Bonus: Caches</h2> <p>Another alignment-for-performance that I alluded to previously is alignment on cache lines which are (for example, on some CPUs) 64B.</p> <p>For more info on how much performance can be gained by leveraging caches, take a look at <a href="http://igoro.com/archive/gallery-of-processor-cache-effects/" rel="noreferrer">Gallery of Processor Cache Effects</a>; from this <a href="https://stackoverflow.com/questions/14707803/line-size-of-l1-and-l2-caches">question on cache-line sizes</a></p> <blockquote> <p>Understanding of cache lines can be important for certain types of program optimizations. For example, the alignment of data may determine whether an operation touches one or two cache lines. As we saw in the example above, this can easily mean that in the misaligned case, the operation will be twice slower.</p> </blockquote>
<p>On PowerPC you can load an integer from an odd address with no problems.</p> <p>Sparc and I86 and (I think) Itatnium raise hardware exceptions when you try this.</p> <p>One 32 bit load vs four 8 bit loads isnt going to make a lot of difference on most modern processors. Whether the data is already in cache or not will have a far greater effect. </p>
49,972
<p>I'm trying to create a simple AJAX to Telnet client for the web. I may be re-inventing the wheel by doing this, but it is a learning project for myself. At the moment I haven't written anything, I'm just trying to get the idea wrapped around my brain. It doesn't necessarily have to be PHP.</p> <p>If I have a telnet client that supports multiple connections already running in its own process, how do I get a PHP script that fires off when the client-browser asks to be able to communicate with the client?</p> <p>For instance, I want the PHP script to be able to tell the already running process which client it is and receive any new data from the telnet process.</p>
<p>For PHP, your talking about interfacing through the shell right? It would all depend on the telnet client you are trying to hook up with, and what CLI options it supports. Opening a stream to this would probably require having each telnet session outputting its' STDIO to a text file, and then having PHP read that text file and displaying the 'difference'.</p> <p>With Fsockopen() in PHP, you really don't need to interface with another program though, you can run socket commands directly in PHP and get the results there.</p> <p><a href="http://us3.php.net/manual/en/function.fsockopen.php#79160" rel="nofollow noreferrer">PHP:Fsockopen</a></p>
<p>Even if the connection needs to be persistent?</p> <p>edit: nevermind, I think I have an idea.</p> <p>I'll be writing the client part myself, but if it could also act as a server that PHP makes calls to by connecting to it and giving relevant data to so that it can find out which connection the user needs... by George I think I've got it!</p> <p>edit2: That's what Jim said. Thanks Jim.</p>
44,560
<p>I want to use Sharepoint with python (C-Python)</p> <p>Has anyone tried this before ?</p>
<p>I suspect that since this question was answered the SUDS library has been updated to take care of the required authentication itself. After jumping through various hoops, I found this to do the trick:</p> <pre><code> from suds import WebFault from suds.client import * from suds.transport.https import WindowsHttpAuthenticated user = r'SERVER\user' password = "yourpassword" url = "http://sharepointserver/_vti_bin/SiteData.asmx?WSDL" ntlm = WindowsHttpAuthenticated(username = user, password = password) client = Client(url, transport=ntlm) </code></pre>
<p>SharePoint exposes several web services which you can use to query and update data.</p> <p>I'm not sure what web service toolkits there are for Python but they should be able to build proxies for these services without any issues.</p> <p>This article should give you enough information to get started.</p> <p><a href="http://www.developer.com/tech/article.php/3104621" rel="nofollow noreferrer">http://www.developer.com/tech/article.php/3104621</a></p>
26,949
<p>I had a straight forward approach of turning Key/Value pairs of an XML excerpt into an NSDictionary when I started a simple iPhone application. The problem is, I need to turn those NSDictionary's instances that once populated my UITableView's into custom classes because they require behavior and additional complexity. The problem here is that now in order for me to instantiate an object and fill its instance variables with key/value pairs from a web service becomes that much more difficult. I can no longer throw it into a method that iterates through the XML and uses KVC to set its instance variables. </p> <p>What kind of other solution is out there?</p>
<p>You can still use key value coding methods on your custom class, as long as you name your variables appropriately there's no difference there. With that being said though, when I'm working with XML I usually end up testing each node name or creating a key lookup table, since the names in the data source I'm working with aren't key value coding compliant. If you have control over the data source though, you could just continue to use <code>setValue:forKey:</code>.</p> <p>I'd recommend reading <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/KeyValueCoding.html#//apple_ref/doc/uid/10000107" rel="noreferrer">this guide</a> about key value coding if you haven't already. It's fundamental to many great tools in Cocoa.</p>
<p>Look into NSCoding. You can use the NSCoding protocol to save your object, properties and all, as data.</p> <p>Once your object is NSCoding compliant, you can just archive the whole array of objects using NSKeyedArchiver.</p> <p>Please note that if you have a large number of objects, this can dramatically affect the app's performance on the iPhone during load and save.</p>
49,665
<p>We've all seen cool WPF demo-applications with rich media.</p> <p>My question is <strong>if WPF-objects can replace some basic functionality in <a href="http://www.imagemagick.org/" rel="nofollow noreferrer">ImageMagick</a></strong>. Basic functions like <strong>resizing images, cropping</strong> and so on.</p> <p>The results from .NET 2.0's System.Graphics-namespace's resizing is just sad (GDI+). Maybe I'm using it wrong, but out of the box it seems to be.</p> <p>Also, a good bet would be that the API:s for WPF are a bit sharper than ImageMagick's .NET APIs.</p> <p><strong>Update</strong>: My thought was that WPF maybe would have <strong>an object for Image-manipulation</strong>. Like GDI has System.Drawing.Image and System.Drawing.Bitmap. But I was hoping that WPF's object was more performant and better in quality at, for example, image-resizing.</p>
<p>WPF and GDI+ are graphic systems designed specifically for GUI, they are not image manipulation libraries.</p> <p>WPF is much better then GDI+, but it's still a GUI system - things like producing the exact same result on different hardware (like IgorK is worried about) are just not a priority and resizing quality is less important then performance - otehrwise it won't be usable as part of a rendering pipeline.</p> <p>So, if you use ImageMagick for basic processing before displaying the image WPF may work for you (but I'll bet it has a lot less options then ImageMagick), if you need high quality image processing then WPF is just the wrong tool for the job. </p> <p>WPF is a great GUI system (the best I've ever worked with) but it's not a general purpose graphics system and it's not an image manipulation library.</p>
<p>I don't know about WPF, but you could use GDI+ - there is an intro here:</p> <ul> <li><a href="http://www.codeproject.com/KB/GDI-plus/imageresize.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/GDI-plus/imageresize.aspx</a></li> </ul>
46,350
<p>I was just looking through some information about Google's <a href="http://code.google.com/apis/protocolbuffers/" rel="noreferrer">protocol buffers</a> data interchange format. Has anyone played around with the code or even created a project around it?</p> <p>I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data.</p>
<p>If you are looking for user facing interaction, stick with xml. It has more support, understanding, and general acceptance currently. If it's internal, I would say that protocol buffers are a great idea.</p> <p>Maybe in a few years as more tools come out to support protocol buffers, then start looking towards that for a public facing api. Until then... <a href="http://en.wikipedia.org/wiki/JSON" rel="noreferrer">JSON</a>?</p>
<p>From your brief description, it sounds like protocol buffers is not the right fit. The phrase "structured content created by hand in a text editor" pretty much screams for XML.</p> <p>But if you want efficient, low latency communications with data structures that are not shared outside your organization, binary serialization such as protocol buffers can offer a huge win.</p>
2,404
<p>How do I define an Extension Method for <code>IEnumerable&lt;T&gt;</code> which returns <code>IEnumerable&lt;T&gt;</code>? The goal is to make the Extension Method available for all <code>IEnumerable</code> and <code>IEnumerable&lt;T&gt;</code> where <code>T</code> can be an anonymous type.</p>
<p>The easiest way to write any iterator is with an iterator block, for example:</p> <pre><code>static IEnumerable&lt;T&gt; Where&lt;T&gt;(this IEnumerable&lt;T&gt; data, Func&lt;T, bool&gt; predicate) { foreach(T value in data) { if(predicate(value)) yield return value; } } </code></pre> <p>The key here is the "<code>yield return</code>", which turns the method into an iterator block, with the compiler generating an enumerator (<code>IEnumerator&lt;T&gt;</code>) that does the same. When called, generic type inference handles the <code>T</code> automatically, so you just need:</p> <pre><code>int[] data = {1,2,3,4,5}; var odd = data.Where(i=&gt;i%2 != 0); </code></pre> <p>The above can be used with anonymous types just fine.</p> <p>You can, of coure, specify the <code>T</code> if you want (as long as it isn't anonymous):</p> <pre><code>var odd = data.Where&lt;int&gt;(i=&gt;i%2 != 0); </code></pre> <p>Re <code>IEnumerable</code> (non-generic), well, the simplest approach is for the caller to use <code>.Cast&lt;T&gt;(...)</code> or <code>.OfType&lt;T&gt;(...)</code> to get an <code>IEnumerable&lt;T&gt;</code> first. You can pass in <code>this IEnumerable</code> in the above, but the caller will have to specify <code>T</code> themselves, rather than having the compiler infer it. You can't use this with <code>T</code> being an anonymous type, so the moral here is: don't use the non-generic form of <code>IEnumerable</code> with anonymous types.</p> <p>There are some slightly more complex scenarios where the method signature is such that the compiler can't identify the <code>T</code> (and of course you can't specify it for anonymous types). In those cases, it is usually possible to re-factor into a different signature that the compiler <em>can</em> use with inference (perhaps via a pass-thru method), but you'd need to post actual code to provide an answer here.</p> <hr> <p>(updated)</p> <p>Following discussion, here's a way to leverage <code>Cast&lt;T&gt;</code> with anonymous types. The key is to provide an argument that can be used for the type inference (even if the argument is never used). For example:</p> <pre><code>static void Main() { IEnumerable data = new[] { new { Foo = "abc" }, new { Foo = "def" }, new { Foo = "ghi" } }; var typed = data.Cast(() =&gt; new { Foo = "never used" }); foreach (var item in typed) { Console.WriteLine(item.Foo); } } // note that the template is not used, and we never need to pass one in... public static IEnumerable&lt;T&gt; Cast&lt;T&gt;(this IEnumerable source, Func&lt;T&gt; template) { return Enumerable.Cast&lt;T&gt;(source); } </code></pre>
<p>This post may help you to get started:<a href="https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772">How do you write a C# Extension Method for a Generically Typed Class</a>. I'm not sure if it is exactly what you are looking for but it might get you started.</p>
34,968
<p>Anyone out there using Fogbugz and Scrum together?</p> <p>We use Fogbugz extensively, and I'm looking for ideas from anyone who may be using it as part of Scrum. I found these two items, but they are archived and unvailable for further discussion. I'm specifically interested in ideas for mapping Scrum concepts into Fogbugz.</p> <p>Some things are fairly obvious. Releases and sprints map well to each other. But other parts of Scrum don't really fit. </p> <p><a href="http://support.fogcreek.com/default.asp?fogbugz.4.12143.4" rel="noreferrer">http://support.fogcreek.com/default.asp?fogbugz.4.12143.4</a><br> <a href="http://support.fogcreek.com/default.asp?fogbugz.4.19971.3" rel="noreferrer">http://support.fogcreek.com/default.asp?fogbugz.4.19971.3</a> </p> <p><strike>I'm also thinking it might not be too hard to create some lightweight custom stuff to wrap around Fogbugz so that we don't have to abandon one of our favorite tools in order to improve our software process integration.</strike></p> <p><strong>Edit:</strong></p> <p>I'm adding a few more specific questions that have come up. Any suggestions on these items would be helpful:</p> <ul> <li><strike>How do we prioritize a large backlog with only the 7 priority levels provided by Fogbugz? We can modify the database tables to add more levels, but is that an appropriate in the current/intended Fogbugz model?</strike></li> <li>How/where do we document a sprint goal?</li> <li>How do we document a canceled sprint?</li> <li>How do we document sprint review?</li> <li>How do we track completed or canceled sprints?</li> </ul> <p><strong>Edit #2:</strong></p> <p>Chris's reply below reminded me that we have indeed upgraded to Fogbugz v7. It has many great features that align it more closely with Agile, Scrum, and Lean including:</p> <ul> <li>Project Backlog (via plugin)</li> <li>Custom Workflow</li> <li>Burn Down Charts</li> <li>Kanban Board (via plugin)</li> </ul> <p>See the following links for more info:<br> <a href="http://www.fogcreek.com/FogBugz/WhatsNew.html" rel="noreferrer">http://www.fogcreek.com/FogBugz/WhatsNew.html</a><br> <a href="http://www.fogcreek.com/FogBugz/Plugins/default.aspx?ixCategory=-3" rel="noreferrer">http://www.fogcreek.com/FogBugz/Plugins/default.aspx?ixCategory=-3</a></p> <p><strong>Edit #3</strong> Adding link that Perhentian mentioned in his answer as well as another I found:</p> <p><a href="http://www.danielroot.info/2009/08/how-to-apply-scrum-using-fogbugz-7.html" rel="noreferrer">http://www.danielroot.info/2009/08/how-to-apply-scrum-using-fogbugz-7.html</a><br> <a href="http://www.fogcreek.com/FogBugz/blog/post/Scrum-Friendly-Features.aspx" rel="noreferrer">http://www.fogcreek.com/FogBugz/blog/post/Scrum-Friendly-Features.aspx</a></p>
<p>FogBugz now (as of version 7) supports plugins, which should make it much easier to use with Scrum.</p> <p><a href="http://www.fogcreek.com/FogBUGZ/LearnMore.html?section=AgileScrum" rel="noreferrer">Tools for Agile / Scrum</a></p>
<p>We use Scrumworks and JIRA.</p> <p>SCRUM doesn't really cover how you implement QA/QC procedures, part of agile is being able to define, improve, iterate processes.</p>
40,741
<p>When trying to execute from within Visual Studio 2008 your application and you get the (uninformative) message "The operation could not be completed".</p> <p>The solution to this is to turn off the "Visual Studio Hosting Process".</p> <p>The problem with turning off this "hosting process" is that all the "run and rewrite" functionality is no longer available. OK, so this isn't a big deal, but I'm <em>always</em> getting this message no matter what machine I use (and it might be nice once in a while to use the rewrite and execute functionality).</p> <p>Am I doing something wrong? How come this "feature" within VS seems to complain so readily? Do other people have success with enabling the hosting process and making use of it?</p>
<blockquote> <p>The problem with turning off this "hosting process" is that all the "run and rewrite" functionality is no longer available.</p> </blockquote> <p>The Visual Studio Hosting Process is not needed to allow Edit and Continue. It is used for "Design time expression Evalutation" in the case where the project is a dll rather than an EXE. It is also used to provide debugging for partial trust scenarios. See the <a href="http://msdn.microsoft.com/en-us/library/ms242202.aspx" rel="nofollow noreferrer">documentation</a> for everything it does.</p> <p>It is highly unlikely it does anything you need, so don't feel bad <a href="http://msdn.microsoft.com/en-us/library/ms185330.aspx" rel="nofollow noreferrer">turning it off</a>.</p>
<p>Probably your web hosting already turn of the network function, you can open a ticket to contact with your web host to confirm, or anything you did would be useless.</p> <p>Some <a href="http://www.webhost4lifereview.com/visual-studio-hosting/" rel="nofollow">visual studio hosting</a> can be found at here.</p> <p>Good luck,</p> <p>Mark</p>
5,337
<p>Eg. can I write something like this code:</p> <pre><code>public void InactiveCustomers(IEnumerable&lt;Guid&gt; customerIDs) { //... myAdoCommand.CommandText = "UPDATE Customer SET Active = 0 WHERE CustomerID in (@CustomerIDs)"; myAdoCommand.Parameters["@CustomerIDs"].Value = customerIDs; //... } </code></pre> <p>The only way I know is to Join my IEnumerable and then use string concatenation to build my SQL string.</p>
<p>Generally the way that you do this is to pass in a comma-separated list of values, and within your stored procedure, parse the list out and insert it into a temp table, which you can then use for joins. As of <strong>Sql Server 2005</strong>, this is standard practice for dealing with parameters that need to hold arrays.</p> <p>Here's a good article on various ways to deal with this problem:</p> <p><a href="http://vyaskn.tripod.com/passing_arrays_to_stored_procedures.htm" rel="noreferrer">Passing a list/array to an SQL Server stored procedure</a></p> <p>But for <strong>Sql Server 2008</strong>, we finally get to pass table variables into procedures, by first defining the table as a custom type.</p> <p>There is a good description of this (and more 2008 features) in this article:</p> <p><a href="http://technet.microsoft.com/en-us/library/cc721270.aspx" rel="noreferrer">Introduction to New T-SQL Programmability Features in SQL Server 2008</a></p>
<p>Nope. Parameters are like SQL values in obeying <a href="http://www.anaesthetist.com/mnm/sql/normal.htm" rel="nofollow noreferrer">first normal form</a>, basically, there can only be one...</p> <p>As you are probably aware, generating SQL strings is risky business: you leave yourself open to an <a href="http://en.wikipedia.org/wiki/Sql_injection" rel="nofollow noreferrer">SQL injection attack</a>. As long as you're dealing with bona fide GUID's you should be fine, but otherwise you need to be sure to cleanse your input. </p>
13,980
<p>I would (as the question states) like to make an asynchronous call, preferably using ASP.net AJAX.</p> <p>The code for the WebMethod looks like this:</p> <pre><code>[WebMethod] public void SendMail(string name, string email, string subject, string body) { MailMessage toSend = new MailMessage(email, address@domain.com, subject, body); var smtp = new SmtpClient(); smtp.Send(toSend); } </code></pre> <p>The fields on the view are, not surprisingly: name, email, subject, body.</p> <p>In my attempts to do this I haven't been able to get to the WebMethod. The service reference is in place, so at least I didn't screw that up. </p> <p>Thanks for the help...</p>
<p>This is not an answer to your question but a warning. I was looking at this method and thinking, "hmm, I wonder if ASP.NET cares if a call to this web method comes from your site or somewhere else?" A quick google search leads me to believe that there isn't any checking to make sure some douche isn't using your web methods for his own malicious desires (<a href="http://softwaredevscott.spaces.live.com/Blog/cns!1A9E939F7373F3B7!484.entry" rel="nofollow noreferrer">here's a blog post talking about this</a>).</p> <p>So, before you get this working, you might want to think about ways to prevent someone from hijacking your webmethod to send me Viagra emails. Because if I get a Viagra email from your website, I'm not going to be very happy with you.</p>
<p>According to the MSDN Library</p> <blockquote> <p>In order for a Web service to be accessed from script, it must be an .asmx Web service whose Web service class is qualified with the ScriptServiceAttribute attribute. Individual methods to be called from script must be qualified with the WebMethodAttribute attribute.</p> </blockquote> <p>see <a href="http://msdn.microsoft.com/en-ca/library/bb398998.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-ca/library/bb398998.aspx</a></p>
43,941
<p>I need a fast container with only two operations. Inserting keys on from a very sparse domain (all 32bit integers, and approx. 100 are set at a given time), and iterating over the inserted keys. It should deal with <em>a lot of</em> insertions which hit the same entries (like, 500k, but only 100 different ones).</p> <p>Currently, I'm using a std::set (only insert and the iterating interface), which is decent, but still not fast enough. std::unordered_set was twice as slow, same for the Google Hash Maps. I wonder what data structure is optimized for this case?</p>
<p>Depending on the distribution of the input, you might be able to get some improvement without changing the structure.</p> <p>If you tend to get a lot of runs of a single value, then you can probably speed up insertions by keeping a record of the last value you inserted, and don't bother doing the insertion if it matches. It costs an extra comparison per input, but saves a lookup for each element in a run beyond the first. So it could improve things no matter what data structure you're using, depending on the frequency of repeats and the relative cost of comparison vs insertion.</p> <p>If you don't get runs, but you tend to find that values aren't evenly distributed, then a splay tree makes accessing the most commonly-used elements cheaper. It works by creating a deliberately-unbalanced tree with the frequent elements near the top, like a Huffman code.</p>
<p>Maybe a set with a <a href="http://en.wikipedia.org/wiki/B-tree" rel="nofollow noreferrer">b-tree</a> (instead of binary tree) as internal data structure. I found <a href="http://www.codeproject.com/KB/cpp/stree.aspx" rel="nofollow noreferrer">this</a> article on codeproject which implements this.</p>
40,120
<p>What is the Constant Value of the Underline font in Java ?</p> <p>Font.BOLD <strong>bold</strong> font</p> <p>Font.ITALIC <em>italic</em> font</p> <p>What is the UNDERLINE font Constant ? I try all the available constants but it didn't work .</p>
<p>Looking at the <a href="http://java.sun.com/javase/6/docs/api/" rel="noreferrer">Java API Specification</a>, it appears that the <a href="http://java.sun.com/javase/6/docs/api/java/awt/Font.html" rel="noreferrer"><code>Font</code> class</a> does not have a constant for underlining.</p> <p>However, using the <a href="http://java.sun.com/javase/6/docs/api/java/awt/Font.html#Font(java.util.Map)" rel="noreferrer"><code>Font(Map&lt;? extends AttributedCharacterIterator.Attribute,?&gt; attributes)</code></a> constructor, one can give it a <code>Map</code> containing the <a href="http://java.sun.com/javase/6/docs/api/java/awt/font/TextAttribute.html" rel="noreferrer"><code>TextAttribute</code></a> and the value to use, in order to specify the font attributes. (Note that the <code>TextAttribute</code> class is a subclass of <code>AttributedCharacterIterator.Attribute</code>)</p> <p><a href="http://java.sun.com/javase/6/docs/api/java/awt/font/TextAttribute.html#UNDERLINE" rel="noreferrer"><code>TextAttribute.UNDERLINE</code></a> seems like the <code>TextAttribute</code> of interest.</p> <p><strong>Edit:</strong> There's an example of using <code>TextAttribute</code> in the <a href="http://java.sun.com/docs/books/tutorial/2d/text/textattributes.html" rel="noreferrer">Using Text Attributes to Style Text</a> section from <a href="http://java.sun.com/docs/books/tutorial/index.html" rel="noreferrer">The Java Tutorials</a>.</p>
<p>For SWT you can use:</p> <pre><code>StyledText text = new StyledText(shell, SWT.BORDER); text.setText("0123456789 ABCDEFGHIJKLM NOPQRSTUVWXYZ"); // make 0123456789 appear underlined StyleRange style1 = new StyleRange(); style1.start = 0; style1.length = 10; style1.underline = true; text.setStyleRange(style1); </code></pre>
42,209
<p>I'm starting a web application that will target Mobile Safari on iPhone/iPod Touch. I'm evaluating the available client-side JavaScript/CSS libraries/frameworks that are currently out there.</p> <p>These are the ones I'm currenlty aware of:</p> <ul> <li><a href="http://code.google.com/p/iui/" rel="nofollow noreferrer" title="iUI">iUI</a></li> <li><a href="http://code.google.com/p/ciui-dev" rel="nofollow noreferrer">CiUI</a></li> <li><a href="http://code.google.com/p/iphone-universal/" rel="nofollow noreferrer">UiUIKit</a></li> <li><a href="http://webapp.net.free.fr/" rel="nofollow noreferrer">WebApp.Net</a></li> <li><a href="http://snippetspace.com/projects/iwebkit/" rel="nofollow noreferrer">iWebKit</a></li> <li><a href="http://developer.apple.com/documentation/AppleApplications/Conceptual/Dashcode_UserGuide/Contents/Resources/en.lproj/Introduction/chapter_1_section_1.html" rel="nofollow noreferrer">Apple's Dashcode Application</a> - not really a standalone library/framework, but it provides/generates JavaScript, CSS, and images that conform to the native iPhone UI metaphors.</li> </ul> <p>Are there any others out there? I want to make sure I'm not missing any before I make a decision. I'm only looking for client-side JavaScript/CSS solutions and building one from scratch isn't an option because of time constraints. No server-side PHP, Ruby, Python, Java, etc. solutions.</p> <p>I am aware of the <a href="https://stackoverflow.com/questions/8756/iphone-web-applications-templates-frameworks">iPhone web applications, templates, frameworks?</a> question that was asked, but this only mentioned iUI and UiUIKit.</p> <p>Thank you</p>
<p><a href="http://phonegap.com/" rel="noreferrer">PhoneGap</a> isn't exactly what you're asking about, but is something you might want to be aware of. It's a wrapper for making iPhone apps using HTML/CSS/JavaScript.</p>
<p>There is also <a href="http://www.journyx.com/jpint/" rel="nofollow noreferrer">jPint</a></p>
26,472
<p>I'm trying to build a HQL that can left join values from a collection, in order to give me the chance of checking "is null" on it.</p> <p>Taken from the example from hibernate manual:</p> <pre> from Cat as cat left join cat.kittens as kitten with kitten.bodyWeight > 10.0 </pre> <p>doesn't seem to work in NHibernate, since it doesn't recognize the "with" keyword. How else are you supposed to left join and check for no-matching entries if you cannot specify join-clauses directly in your join as opposed to in your WHERE-statement?</p> <p>I'm running NHibernate 2.0.0.</p>
<p>Unfortunately, this is not supported in NHibernate. It was <a href="http://jira.nhibernate.org/browse/NH-514" rel="nofollow noreferrer">first requested in 2005</a> and is by far the most popular requested feature.</p>
<p>I think you can workaround it by using an outer join, and then do this:</p> <pre><code>from Cat c left join c.Kittens as kitten where kitten.bodyweight &gt; 10 or kitten.bodyweight is null </code></pre>
33,858
<p>I have a sqlite3 table that I'm trying to map to an object in objective-C. One attribute of the table is 'completed_at' which is stored as a DATETIME.</p> <p>I want to create a property on my objective-C class (which inherits from NSObject) that will map well to the 'completed_at' attribute.</p> <p>Objective-C has an NSDate type but I'm not sure if that will map directly?</p>
<p>I am sharing here just the core things regarding date formatting for saving and retrieving the data for presentation. If you have any problem with this code snippet then I will share the full code that I used for my project. </p> <p>When you save your data, bind your date value in the sql statement like this way:</p> <pre><code> NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSString *dateString=[dateFormat stringFromDate:[NSDate date]]; sqlite3_bind_text(saveStmt, 1, [dateString UTF8String] , -1, SQLITE_TRANSIENT); </code></pre> <p>and when you retrieve data you have to write this code:</p> <pre><code> NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSDate *myDate =[dateFormat dateFromString:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)]]; </code></pre> <p>now you have a variable myDate of NSDate type which you can render in your way:</p> <pre><code> NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"dd-MM-yyyy hh:mm:ss a"]; NSLog(@"My Date was : %@", [formatter stringFromDate:myDate]); </code></pre> <p>You must have to remember three things:</p> <ol> <li>In your SQLite date field type should be DATETIME</li> <li>Date format should be same when you store and when you retrieve</li> <li>Now you can show in your own way but following the format. Below the format details is given.</li> </ol> <p>Format:</p> <pre><code> 'dd' = Day 01-31 'MM' = Month 01-12 'yyyy' = Year 2000 'HH' = Hour in 24 hour 'hh' = Hour in 12 hour 'mm' = Minute 00-59 'ss' = Second 00-59 'a' = AM / PM </code></pre>
<p>I have zero experience with Objective-C, but I found Apple's <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/doc/uid/20000188" rel="nofollow noreferrer">NSDate Class Reference</a> with a google search. With the information provided on the linked page you should be able to figure out how to manipulate 32-bit epoch times in Objective-C, and this would work well in SQLite. I would probably create the completed_at column as type INTEGER for 32-bit times.</p> <p>SQLite really prefers Julian dates, which are floats. I haven't found any documentation explaining how one might coerce the NSDate class into working with Julians.</p> <p><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/timeIntervalSince1970" rel="nofollow noreferrer">timeIntervalSince1970</a> looks very interesting.</p>
38,875
<p>What are the preffered plugins for monitoring and analyzing the performance of a Rails app? I'm looking for both database/query analyzers and the rest of the stack if possible, though not necessarily all in one plugin. Which ones do you recommend? ( Bonus points for free ones :)</p> <p>For example, <a href="http://railstips.org/2008/9/17/rails-app-monitoring" rel="nofollow noreferrer">this one</a> looks spify.</p>
<p><a href="http://ckhsponge.wordpress.com/2006/10/11/ruby-on-rails-log-analyzer-rawk/" rel="nofollow noreferrer">RAWK</a> I have used to get performance reports emailed to me at regular intervals. It works by analyzing the rails production logs and has always done well for me.</p> <p>I recently learned about <a href="http://scoutapp.com/" rel="nofollow noreferrer">Scout</a> from their article about <a href="http://blog.scoutapp.com/articles/2008/09/09/rails-monitoring-pillars" rel="nofollow noreferrer">rails monitoring</a>, but I haven't had a chance to try it out yet, looks promising!</p>
<p>This gives info on query analyzers in Rails</p> <p><a href="http://ronnyml.wordpress.com/2008/07/03/query-analyzer-for-rails/" rel="nofollow noreferrer">http://ronnyml.wordpress.com/2008/07/03/query-analyzer-for-rails/</a></p>
14,516
<pre><code>echo date('r',strtotime("16 Dec, 2010")); //Tue, 16 Dec 2008 20:10:00 +0530 echo date('r',strtotime("16 Dec 2010")); //Sat, 16 Jan 2010 00:00:00 +0530 </code></pre> <p>That's just wrong... Either it should fail or it should parse correctly. Do you know any robust natural language date/time parser in php? How do you parse natural language date time in php?</p> <p>Edit:</p> <pre><code>var_dump(strtotime("16 Dec, abcd")); //bool(false) </code></pre> <p>"16 Dec, 2010" is either a valid GNU date input format or it is not. In the first case it should return the correct answer and in the second it should return false. This is what I mean by 'wrong'. </p> <p>Edit:</p> <p>The purpose is as hop guessed to accept a significant variety of user input.</p>
<p>If you know in what format the time is represented in the string, you can use <code>strptime()</code> together with the appropriate format string to parse it. It will at least report an error when it cannot interpret the string according to the format.</p> <p>This function exists in PHP 5.1.0 and up.</p> <p>If you want to take arbitrary user input, you should offer clear and obvious feedback to the user, so that she can do something about a falsely interpreted date. Most of the time, there won't be a problem anyway and you can't ever catch all problematic cases (think American vs. European format).</p>
<p>strtotime is the best function you could find for that. I doubt that an arbitrary string representation of a date will ever be interpreted 100% correctly, since it would require at least <em>some</em> information on the formatting used.</p> <p>In other words: Please define natural language (You just used two different versions thereof in your question, as the php interpreter pointed out correctly)</p>
49,451
<p>I have an ADO.Net Data Service that I am using to do a data import. There are a number of entities that are linked to by most entities. To do that during import I create those entities first, save them and then use .SetLink(EntityImport, "NavigationProperty", CreatedEntity). Now the first issue that I ran into was that the context did not always know about CreatedEntity (this is due to each of the entities being imported independently and a creation of a context as each item is created - I'd like to retain this functionality - i.e. I'm trying to avoid "just use one context" as the answer). </p> <p>So I have a .AddToCreatedEntityType(CreatedEntity) before attempting to call SetLink. This of course works for the first time, but on the second pass I get the error message "the context is already tracking the entity". </p> <p>Is there a way to check if the context is already tracking the entity (context.Contains(CreatedEntity) isn't yet implemented)? I was thinking about attempting a try catch and just avoiding the error, but that seems to create a new CreatedEntity each pass. It is looking like I need to use a LINQ to Data Services to get that CreatedEntity each time, but that seems innefficient - any suggestions?</p>
<p>I think you should look at the <a href="http://msdn.microsoft.com/en-us/library/system.data.entitystate.aspx" rel="nofollow noreferrer">EntityState</a> property of your entity.</p> <p>Only if it is of the value EntityState.Detached than you have to add it to your context.</p> <p>Do not forget the following remark:</p> <blockquote> <p>This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.</p> </blockquote> <p>I would create a extension method:</p> <pre><code>public static class EntityObjectExtensions { public static Boolean IsTracked(this EntityObject self) { return (self.EntityState &amp; EntityState.Detached) != EntityState.Detached; } } </code></pre>
<p>When trying to check whether the context was tracking the entity that I wanted to update (or add) I was pretty disapointed when I found that the context.Entites.Contains(currentItem) didn't work.</p> <p>I got around it using:</p> <pre><code>if (context.Entities.Where(entities =&gt; entities.Entity == currentItem).Any()) { this.service.UpdateObject(currentItem); } </code></pre>
28,287
<p>I'm looking for a solid ORM for .NET that can handle over a 1000 tables and entities. What can you suggest? Any comments would be appreciated, but those from people who have actually dealt with this challenge and a description of how with what they dealt with it would be appreciated even more.</p>
<p>You can give a try <a href="http://www.llblgen.com/defaultgeneric.aspx" rel="nofollow noreferrer">LLBLGen</a> and <a href="http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx" rel="nofollow noreferrer">ADO.NET Entity Framework</a>, but for the number of tables, the entity class generation will take a while in any ORM...</p>
<p><a href="http://www.hibernate.org/343.html" rel="nofollow noreferrer">NHibernate</a> is a terrific choice. Some pointers would include to ensure you fully understand the session life-cycle as well as its lazy-loading techniques for lists and object references.</p>
25,675
<p>There are lots of widgets provided by sites that are effectively bits of JavaScript that generate HTML through <em>DOM</em> manipulation or <code>document.write()</code>. Rather than slow the browser down even more with additional requests and trust yet another provider to be fast, reliable and not change the widget output, I want to execute* the JavaScript to generate the rendered HTML, and then save that HTML source.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p> <p>Things I've looked into that seem unworkable or way too difficult:</p> <ol> <li>The Links Browser (<em>not lynx!</em>)</li> <li>Headless use of Xvfb plus Firefox plus Greasemonkey (<em>yikes</em>)</li> <li>The all-Java browser toolkit Cobra (<em>the best bet!</em>) </li> </ol> <p>Any ideas? </p> <p>** Obviously you can't really execute the JavaScript completely, as it doesn't necessarily have an exit path, but you get the idea.</p>
<p>Wikipedia's <a href="http://en.wikipedia.org/wiki/Server-side_JavaScript" rel="nofollow noreferrer">"Server-side JavaScript"</a> article lists numerous implementations, many of which are based on Mozilla's <strong>Rhino</strong> JavaScript-to-Java converter, or its cousin <strong>SpiderMonkey</strong> (the same engine as found in Firefox and other Gecko-based browsers). In particular, something simple like <a href="http://www.modjs.org/" rel="nofollow noreferrer"><strong>mod_js</strong></a> for Apache may suit your needs.</p>
<p>If you're just using plain JS, <a href="http://www.mozilla.org/rhino/" rel="nofollow noreferrer">Rhino</a> should do the trick. But if the JS code is actually calling DOM methods and so on, you're going to need a full-blown browser. <a href="http://simile.mit.edu/wiki/Crowbar" rel="nofollow noreferrer">Crowbar</a> might help you.</p> <p>Is this really going to make things faster for users without causing compatibility issues?</p>
3,576
<p>I must get two different client application talk without any kind of broker or server. What is the best method for IPC beween two process, Java and .NET?</p> <p>It must able to be work in multi-user termainl server, so no socket please. I wish that it is lightweight and simple, something plug and run, so no RMI/WS please.</p> <p>I'm now thinking about JNI to access Mutex and Named pipes, am I going to a right direction?</p> <p>Any ideas welcome!</p> <p>Thanks Dennis</p>
<p>You can access WinAPI through JNI(Java) and PInvoke(C#). Use following WinAPI functions: CreateEvent SetEvent WaitForSingleObject CreateMutex ReleaseMutex CreateFileMapping (for share memory) MapViewOfFile UnmapViewOfFile</p>
<p>I would use <a href="http://code.google.com/p/protobuf/" rel="nofollow noreferrer" title="Protocol Buffers">protobuf</a>. </p> <blockquote> <p>Protocol Buffers are a way of encoding structured data in an efficient yet extensible format. Google uses Protocol Buffers for almost all of its internal RPC protocols and file formats.</p> </blockquote>
40,988
<p>i want to call a series of .sql scripts to create the initial database structure</p> <ol> <li>script1.sql</li> <li>script2.sql etc.</li> </ol> <p>is there any way of doing this without sqlcmd or stored procedures <strong>or any other kind of code that is not sql</strong> ? just inside a .sql file.</p>
<p>you could try this:</p> <pre><code>exec master..xp_cmdshell 'osql -E -ix:\path\filename.sql' </code></pre> <p>osql must be in the path, the full filename must be known, and logins have to be set up correctly (options -E or -U)</p>
<p>There's no reason to exclude stored procedures. You don't need to include "any other kind of code that is not sql", plus</p> <p>EXEC someothersp</p> <p>which will be required (or its equivalent) in any other solution.</p> <p>What's your reason for excluding them? I would sure think it beats writing code in yet another language.</p>
25,284
<p>I'm working on a simple multiplayer game in which 2-4 players are placed at separate entrypoints in a maze and need to reach a goal point. Generating a maze in general is very easy, but in this case the goal of the game is to reach the goal before everyone else and I don't want the generation algorithm to drastically favor one player over others.</p> <p>So I'm looking for a maze generation algorithm where the optimal path for each player from the startpoint to the goal is no more than 10% more steps than the average path. This way the players are on more or less an equal playing field. Can anyone think up such an algorithm?</p> <p>(I've got one idea as it stands, but it's not well thought out and seems far less than optimal -- I'll post it as an answer.)</p>
<p>An alternative to freespace's answer would be to generate a random maze, then assign each cell a value representing the number of moves to reach the end of the maze (you can do both at once if you decide that you're starting at the 'end'). Then pick a distance (perhaps the highest one with n points at that distance?) and place the players at squares with that value.</p>
<p>The easiest solution I can come up with is to randomly generate an entire maze like normal, then randomly pick the goal point and player startpoints. Once this is done, calculate the shortest path from each startpoint to the goal. Find the average and start 'smoothing' (remove/move barriers -- don't know how this will work) the paths that are significantly above it, until all of the paths are within the proper margin. In addition, it could be possible to take the ones that are significantly below the average and insert additional barriers.</p>
13,337
<p>I have an xml file ('videofaq.xml') that defines a DTD using the following DOCTYPE</p> <pre><code>&lt;!DOCTYPE video-faq SYSTEM "videofaq.dtd"&gt; </code></pre> <p>I am loading the file from the classpath (from a JAR actually) at Servlet initialization time using:</p> <pre><code>getClass().getResourceAsStream("videofaq.xml") </code></pre> <p>The XML is found correctly, but for the DTD in the same package, Xerces gives me a FileNotFoundException, and displays the path to the Tomcat startup script with "videofaq.dtd" appended to the end. What hints, if any, can I pass on to Xerces to make it load the DTD properly?</p>
<p>A custom EntityResolver will work, but you might be able to avoid having to create a custom class by setting a SystemID to allow the processor to "find" relative paths.</p> <p><a href="http://www.onjava.com/pub/a/onjava/excerpt/java_xslt_ch5/index.html?page=5" rel="nofollow noreferrer">http://www.onjava.com/pub/a/onjava/excerpt/java_xslt_ch5/index.html?page=5</a></p> <blockquote> <p>By providing a system identifier as a parameter to the StreamSource, you are telling the XSLT processor where to look for commonFooter.xslt. Without this parameter, you may encounter an error when the processor cannot resolve this URI. The simple fix is to call the setSystemId( ) method as follows:</p> </blockquote> <pre><code>// construct a Source that reads from an InputStream Source mySrc = new StreamSource(anInputStream); // specify a system ID (a String) so the // Source can resolve relative URLs // that are encountered in XSLT stylesheets mySrc.setSystemId(aSystemId); </code></pre>
<p>When using SAX you can provide your own <code>EntityResolver</code> which then loads the resource any way you want.</p>
41,542
<p>I want to have a abstract view for any type of UI (web or window). In order to do that I must use Interface (IView ) in which I can only apply just rules about view. In fact, I want to set a some basic comple function to provide to its inheritances.</p> <p>So in this way, I must use abstract class. The problem is</p> <p>1) Interface only have rules 2) The view (web form or window form) can't inherit any more since that's already inherited from window or web form</p> <p>How can I do that? Many thanks</p>
<p>Will the functions you add change the definition of what the class is, or will you simply be creating functions to manipulate data that is already a part of the class?</p> <p>If you need to redefine aspects of the base class of these two classes then yes, you will need to change your inheritance structure. But if the functions will simply manipulate data that is already part of the class now then I would suggest you use the interface and create utility functions.</p> <p>Here is a clumsy example of what I mean:</p> <pre><code>using System; abstract class Pet { } class Dog : Pet, IPet { public String Name { get; set; } public Int32 Age { get; set; } } class Cat : Pet, IPet { public String Name { get; set; } public Int32 Age { get; set; } } interface IPet { String Name { get; set; } Int32 Age { get; set; } } static class PetUtils { public static void Print(this IPet pet) { Console.WriteLine(pet.Name + " is " + pet.Age); } } </code></pre> <p>Your two UI classes are perhaps related in this way. I would imagine that what you need to do in a cross-cutting fashion would be solved by a utility method like the one I have created. I did create the <code>PetUtils.Print</code> method as an extension method as this will create the expressive illusion of an instance method. If you are not using C# 3 just remove "<code>this</code>" from <code>public static void Print(this IPet pet)</code>.</p>
<p>what i want to do is something like this</p> <p>Public MustInherit Class ControllerBase(Of M As {ModelBase, New}, V As {IView})</p> <pre><code>Inherits BaseController Dim model As M Dim view As V Public Sub New() model = New M view.Controller = Me model.Controller = Me End Sub Public Overridable Function GetModel() As M Return model End Function Public Overridable Function GetView() As V Return view End Function </code></pre> <p>End Class</p> <p>Public Class BaseWindow</p> <pre><code>Inherits System.Windows.Forms.Form Implements IView Dim c As BaseController Public Function GetController() As BaseController Return c End Function Friend WriteOnly Property Controller() As BaseController Implements IView.Controller Set(ByVal value As BaseController) c = value End Set End Property </code></pre> <p>End Class</p> <pre><code> Public Class BaseWeb Inherits System.Web.UI.Page Implements IView Dim c As BaseController Public Function GetController() As BaseController Return c End Function Friend WriteOnly Property Controller() As BaseController Implements IView.Controller Set(ByVal value As BaseController) c = value End Set End Property </code></pre> <p>End Class</p> <p>Public Interface IView</p> <pre><code>WriteOnly Property Controller() As BaseController </code></pre> <p>End Interface</p>
47,461
<p>I want to make a simple server application where people can connect using a browser-based client (which I will make later) to watch streaming video. And I want to use C#.</p> <p>What do I need to capture video or rapid images through a webcam and send them over the network?</p>
<p>If you want a "capture/streamer in a box" component, there are several out there as others have mentioned.</p> <p>If you want to get down to the low-level control over it all, you'll need to use DirectShow as thealliedhacker points out. The best way to use DirectShow in C# is through the <a href="http://directshownet.sourceforge.net/" rel="nofollow noreferrer">DirectShow.Net</a> library - it wraps all of the DirectShow COM APIs and includes many useful shortcut functions for you.</p> <p>In addition to capturing and streaming, you can also do recording, audio and video format conversions, audio and video live filters, and a whole lot of stuff.</p> <p>Microsoft claims DirectShow is going away, but they have yet to release a new library or API that does everything that DirectShow provides. I suspect many of the latest things they have released are still DirectShow under the hood. Because of its status at Microsoft, there aren't a whole lot of books or references on it other than MSDN and what you can find on forums. Last year when we started a project using it, the best book on the subject - <a href="https://rads.stackoverflow.com/amzn/click/com/0735618216" rel="nofollow noreferrer" rel="nofollow noreferrer"><em>Programming Microsoft DirectShow</em></a> - was out of print and going for around $350 for a used copy!</p>
<p>If you want to record video from within a web browser, I think your only option is Flash. We are looking to do the same thing. We are also primarily a .NET house and I don't see a way to use .NET to capture the webcam _from_within_the_browser_. All of the other solutions mentioned here would probably work great if you are happy to settle for a desktop app</p>
44,567
<p>I'm currently busy implementing a filter of sorts for which I need to generate an INNER JOIN clausse for every "tag" to filter on.</p> <p>The problem is that after a whole bunch of SQL, I have a table that contains all the information I need to make my selection, but I need it again for every generated INNER JOIN</p> <p>This basically looks like:</p> <pre><code>SELECT * FROM search INNER JOIN search f1 ON f1.baseID = search.baseID AND f1.condition = condition1 INNER JOIN search f2 ON f2.baseID = search.baseID AND f2.condition = condition2 ... INNER JOIN search fN ON fN.baseID = search.baseID AND fN.condition = conditionN </code></pre> <p>This works but I would much prefer the "search" table to be temporary (it can be several orders of magnitude smaller if it isn't a normal table) but that gives me a very annoying error: <code>Can't reopen table</code></p> <p>Some research leads me to <a href="http://bugs.mysql.com/bug.php?id=10327" rel="noreferrer">this bug report</a> but the folks over at MySQL don't seem to care that such a basic feature (using a table more than once) does not work with temporary tables. I'm running into a lot of scalability problems with this issue.</p> <p>Is there any viable workaround that does not require me to manage potentially lots of temporary but very real tables or make me maintain a huge table with all the data in it?</p> <p>Kind regards, Kris</p> <p>[additional]</p> <p>The GROUP_CONCAT answer does not work in my situation because my conditions are multiple columns in specific order, it would make ORs out of what I need to be ANDs. However, It did help me solve an earlier problem so now the table, temp or not, is no longer required. We were just thinking too generic for our problem. The entire application of filters has now been brought back from around a minute to well under a quarter of a second.</p>
<p>A simple solution is to duplicate the temporary table. Works well if the table is relatively small, which is often the case with temporary tables.</p>
<p>I was able to change the query to a permanent table and this fixed it for me. ( changed the VLDB settings in MicroStrategy, temporary table type).</p>
44,659
<p>I've had a look at code.google.com, but I didn't find anywhere how to programatically make a search query to Google and get the results. Do you happen to know if this is possible, using some web services or any other way?</p> <p>Of course, there's always the possibility to send a search query, get the HTML content of the result page and parse it, but I'd like to avoid such trouble, if possible.</p>
<p><a href="http://blog.wired.com/monkeybites/2008/04/google-search-a.html" rel="nofollow noreferrer">Google has had a remarkable history and somewhat </a>. bumpy <a href="http://blog.programmableweb.com/2008/04/21/googles-rest-api-for-search/" rel="nofollow noreferrer">evolution of its search API</a> There have also been some attempts by third parties to <a href="http://en.wikipedia.org/wiki/Scroogle" rel="nofollow noreferrer">appropriate the content</a>. </p> <p>It may be worth it to you to do a quick background check on where Google has been, and where it is now regarding its search API (via the links above). Different people have viewpoints on how much better Google search API is over just personal-web-scraping (the option you appear to want to avoid).</p> <p>It may also be worth <em>re-emphasizing</em> that Google is <a href="http://www.programmableweb.com/api/yahoo-search" rel="nofollow noreferrer">not the only game in town</a>.</p>
<p>This is possible trough the <a href="http://code.google.com/apis/ajaxsearch/web.html" rel="nofollow noreferrer">Google AJAX Search API</a>.</p>
44,439
<p>How do you stop the designer from auto generating code that sets the value for public properties on a user control?</p>
<p>Use the DesignerSerializationVisibilityAttribute on the properties that you want to hide from the designer serialization and set the parameter to Hidden.</p> <pre><code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string Name { get; set; } </code></pre>
<p>A slight change to Erik's answer I am using VS 2013.</p> <pre><code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new string Name { get; set; } </code></pre>
4,943
<p>I have a build script and as part of that script it copies a jar file to a directory, for ease lets call it the utils jar. the utils jar is built by another build script sitting in another directory. What im trying to do have my build script run the utils build script so that I can ensure the utils jar is up to date.</p> <p>So I know I need to import the utils build file.</p> <pre><code>&lt;import file="../utils/build/build.xml" /&gt; </code></pre> <p>Which doesn't work because the import task, unlike almost every other ant taks, doesn't run from basedir, it runs from the pwd. So to get around that I have this little ditty, which does successfully import the build file</p> <pre><code> &lt;property name="baseDirUpOne" location=".." /&gt; &lt;import file="${baseDirUpOne}/utils/build/build.xml" /&gt; </code></pre> <p>So now that ive solved my import problem I need to call the task, well that should be easy right:</p> <pre><code>&lt;antcall target="utils.package" /&gt; </code></pre> <p><em>note that in the above, utils is the project name of ../utils/build/build.xml</em></p> <p>the problem I'm now running into is that ant call doesn't execute in ../utils/build so what I need, and cant find, is a runat property or something similar, essentially:</p> <pre><code>&lt;antcall target="utils.package" runat="../utils/build" /&gt; </code></pre> <p>The reason I need this is that in my utils build file the step to select which code to copy to the jar is based on relative paths so as to avoid hardcoding paths in my ant file. Any ideas? </p>
<p>I've got something similar set up: I have a main Ant build.xml which calls a separate build.xml that takes care of building my tests. This is how I do it:</p> <pre><code>&lt;target name="build-tests"&gt; &lt;subant target="build"&gt; &lt;fileset dir="${test.home}" includes="build.xml"/&gt; &lt;/subant&gt; &lt;/target&gt; </code></pre> <p>The trick is to use <a href="http://ant.apache.org/manual/Tasks/subant.html" rel="noreferrer"><code>subant</code></a> instead of <code>antcall</code>. You don't have to import the other build file.</p>
<p>You can pass params down to antcall using nested in the antcall block. So, you can pass the properties down that way (probably even basedir since properties are immutable). </p>
3,028
<p>My usage case is compiling generated source files from a java program using the ToolProvider and JavaCompiler classes provided in JDK 6. The source files contain references to classes in the context classloader (it runs in a J2EE container), but not in the system classloader. My understanding is that by default the ToolProvider will create the JavaCompiler instance with the system classloader.</p> <p>Is there a way to specify a classloader for JavaCompiler to use?</p> <p>I tried this approach, modified from something on IBM DeveloperWorks:</p> <pre><code>FileManagerImpl fm = new FileManagerImpl(compiler.getStandardFileManager(null, null, null);); </code></pre> <p>with FileManagerImpl defined as:</p> <pre><code>static final class FileManagerImpl extends ForwardingJavaFileManager&lt;JavaFileManager&gt; { public FileManagerImpl(JavaFileManager fileManager) { super(fileManager); } @Override public ClassLoader getClassLoader(JavaFileManager.Location location) { new Exception().printStackTrace(); return Thread.currentThread().getContextClassLoader(); } } </code></pre> <p>The stacktrace indicates it's only called once during annotation processing. I verified the class referenced in the source file to be compiled is not on the system classpath but is available from the context classloader.</p>
<p>If you know the classpath to the files that are known to the contextclassloader you can pass them to the compiler:</p> <pre><code> StandardJavaFileManager fileManager = compiler.getStandardFileManager(this /* diagnosticlistener */, null, null); // get compilationunits from somewhere, for instance via fileManager.getJavaFileObjectsFromFiles(List&lt;file&gt; files) List&lt;String&gt; options = new ArrayList&lt;String&gt;(); options.add("-classpath"); StringBuilder sb = new StringBuilder(); URLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader(); for (URL url : urlClassLoader.getURLs()) sb.append(url.getFile()).append(File.pathSeparator); options.add(sb.toString()); CompilationTask task = compiler.getTask(null, fileManager, this /* diagnosticlistener */, options, null, compilationUnits); task.call(); </code></pre> <p>This example assumes you're using a URLClassloader (which allows you to retrieve the classpath) but you could insert your own classpath if you wanted to. </p>
<p>You're asking two separate questions here.</p> <p>One is how to compile classes not found in the system classpath. This is easily solved by passing the "-classpath" command-line argument to the compiler (as first mentioned by Leihca).</p> <p>The second is how to instantiate ToolProvider and JavaCompiler on the thread context classloader. At the time of this writing, this is an unsolved question: <a href="https://stackoverflow.com/questions/2315719/how-to-interact-with-javax-tools-toolprovider-outside-the-system-classloader">Using javax.tools.ToolProvider from a custom classloader?</a></p>
34,578
<p>I thought it is a very simple task to export data in a view from SQL Server 2005 to a fixed width text file. But the wizard is a pain. The format is not correct. Does anybody know how to deal with it? or any better way to do that?</p>
<p>Use bcp with queryout option <a href="http://msdn.microsoft.com/en-us/library/ms162802(SQL.90).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms162802(SQL.90).aspx</a></p> <pre><code>bcp "SELECT * FROM AdventureWorks.Person.Contact" queryout Contacts.txt -c -T </code></pre> <p>Use a format file if you want fixed-width output</p> <p><a href="http://weblogs.sqlteam.com/brettk/archive/2006/07/06/10504.aspx" rel="noreferrer">http://weblogs.sqlteam.com/brettk/archive/2006/07/06/10504.aspx</a></p> <p>I just tried exporting in AdventureWorks, Fixed Width gave me a lot of issues too (compared to column delimiters) I had to ignore the GUID columns, not include column names in the first row, etc.. finally exported Sales.Customer table</p> <p>Without BCP, you may have to look into SSIS or SQLCMD</p>
<p>If the format from the wizard doesn't suit your needs, you will need to develop your own SSIS package. Are you sure you really need a fixed width file? A delimited file would probably be easier to get right as they are much more common.</p>
44,870
<p>One of my pages of my site is behaving really weird in IE6.<br> One element is ignoring its background color and border.<br> The other element is invisible (textcolor same as foreground color?)</p> <p>The elements are not always showing this behaviour, but about 50% of the loads without any pattern. When the browser window is resized or scrolled, or the elements are selected, the lay-out shows up fine all of a suddden.</p> <p>wtf...</p> <p>Anybody got an idea how I can even start to debug this?</p>
<p>Sounds like you could have been hit by the hasLayout problem/bug in IE6. Check out <a href="http://www.satzansatz.de/cssd/onhavinglayout.html" rel="nofollow noreferrer">http://www.satzansatz.de/cssd/onhavinglayout.html</a></p>
<p>Sounds like it could be the <a href="http://www.positioniseverything.net/explorer/peekaboo.html" rel="nofollow noreferrer">peekaboo bug</a>.</p>
49,871
<p>As far as I understand, if I want to get my database under source control then I need to be checking in change scripts for each change and then running them from some revision to get the correct DB.</p> <p>I am trying to make a batch file that will be checked in too, that allows other developers on the team to re-build the DB locally without too much trouble. I believe sqlcmd is the way to achieve this. I have it setup to enumerate all files in the dir of .sql files and run sqlcmd for each.</p> <p>My question is who has done this before and do you have an advice on the best way to achieve this? Is the way I intend to do this the best way or is there a better way?</p> <p>Hope that's not too vague.</p> <p>Thanks in advance,</p> <p>Martin.</p>
<p>If you are using a ORM tool like NHibernate you save yourself the trouble of having DB change scripts because the ORM can recreate the database from it's mapping files (that are under source control). </p> <p>That's a pretty easy way of having the appropriate db version for every revision. </p> <p>I also then recreate the whole schema whenever executing tests to make sure I have a consistent state.</p> <p>I recently blogged about that: <a href="http://www.tigraine.at/2008/10/30/sourcecontrol-and-databases-when-orm-comes-in-handy/" rel="nofollow noreferrer">http://www.tigraine.at/2008/10/30/sourcecontrol-and-databases-when-orm-comes-in-handy/</a></p> <p>I also once had a project that had Sql update scripts, and we just had a little helper tool built (very very basic) that opened the folder, sorted all scripts (we were naming them 1 - foo.sql, 2 - bar.sql) and executed them in order against the DB. </p> <p>If a developer had a new script he simply added it to the end (34 - bla bla.sql).</p>
<p>One thing to be aware of is that you need to create objects in the order of dependency. So you cannot simply iterate files.</p> <p>We ended up having a batch file that would list all the objects in order of dependency</p> <p>Actually we had 2 batch files one called say createDBObject.bat:</p> <pre><code>:: Parameters Required: :: %1 UserID :: %2 Password :: %3 Server :: %4 Database :: %5 file with scripted object :: echo. &gt;&gt; CreateDBObjectsLog.txt echo %5 &gt;&gt; CreateDBObjectsLog.txt osql -U%1 -P%2 -S%3 -i%5 -d%4 -n &gt;&gt; CreateDBObjectsLog.txt echo * %5 </code></pre> <p>and then the other with the list of all the db objects:</p> <pre><code>:: Parameters Required: :: %1 UserID :: %2 Password :: %3 Server :: %4 Database :: echo object in %4 database on %3 server echo Please Wait ... if exist CreateDBObjectsLog.txt del CreateDBObjectsLog.txt call createDBObject.bat %1, %2, %3, %4, ScriptedTable1 call createDBObject.bat %1, %2, %3, %4, ScriptedTable2 ... call createDBObject.bat %1, %2, %3, %4, ScriptedTableN call createDBObject.bat %1, %2, %3, %4, ScriptedView1 call createDBObject.bat %1, %2, %3, %4, ScriptedSP1 etc </code></pre> <p>Now we use <a href="http://www.red-gate.com/products/SQL_Compare/index.htm" rel="nofollow noreferrer">SQL Compare Pro</a> that automates all those tasks</p> <p>You can also check related question: <a href="https://stackoverflow.com/questions/169107/is-there-a-poor-mans-alternative-to-redgate-for-scripting-out-entire-database-s#188355">Is there a “poor man’s” alternative to RedGate for scripting out entire database schema?</a></p>
35,477
<p>If I do something like this:</p> <pre><code>using (SqlCommand cmd = new SqlCommand("SELECT * FROM TBL")) { using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { string s = reader.GetString(7); } } } </code></pre> <p>does the Read() call read the entire row into memory, or does the GetString(7) call mean that the reader only ever reads the data in column 7?</p>
<p>it reads the whole row on the read operation.</p>
<p>I think you are looking for the <a href="http://www.devguru.com/features/tutorials/AdoNet/AdoNet3.asp" rel="nofollow noreferrer">ExecuteScalar</a> method of the datareader and you want to specify your columns in your sql command.</p>
49,300
<p>I have just built a Prusa i3 MK2 printer. One of its features is automatic XYZ axes calibration done using inductive probe which is located next to the nozzle.</p> <p>In my case, this calibration procedure failed with the message: </p> <blockquote> <p><em>XYZ calibration failed. Please consult the manual.</em></p> </blockquote> <p>The <a href="http://www.prusa3d.com/downloads/manual/prusa3d_manual_mk2_en.pdf" rel="nofollow noreferrer">manual</a> on this problem reads:</p> <blockquote> <ol> <li><strong>XYZ calibration failed. Bed calibration point was not found.</strong><br> Calibration routine did not find a bed sensor point. The printer stops close to the bed point, which it failed to detect. Please verify, that the printer is assembled correctly, that all axes move freely, the pulleys do not slip and the print nozzle is clean. If everything looks good, re-run the X/Y calibration and verify with a sheet of paper between the nozzle and the print bed that the print nozzle does not touch the print bed during the calibration routine. If you feel a friction of the nozzle against the sheet of paper and the nozzle is clean, you need to screw the PINDA probe slightly lower and re-run the X/Y calibration.</li> <li><strong>XYZ calibration failed. Please consult the manual.</strong><br> The calibration points were found in positions far from what should be expected for a properly assembled printer. Please follow the instructions of case 1).</li> </ol> </blockquote> <p>My nozzle is new, therefore clean and I have already checked that all axes move without any problems. The manual does not seem to offer any additional advice.</p> <p>I tried to put the PINDA probe lower. It had helped the calibration, but at the same time the probe was lower than the nozzle, which means I couldn't print with it being on the extruder.</p> <p>What else can I check? How to find the issue? This is my first printer, so I'm totally clueless.</p>
<p>One thing, and the one that eventually solved my problem, is to update the firmware. Firmware update instructions: <a href="http://manual.prusa3d.com/Guide/Upgrading+firmware/66" rel="nofollow noreferrer">Upgrading firmware - Prusa3D</a></p> <p>The only thing you might get stuck on is selecting the right COM port.</p> <ol> <li>Go to the device manager (run <code>devmgmt.msc</code>) <img src="https://i.stack.imgur.com/yphCl.png" alt="image description"></li> <li>In COM and LPT section, you should see port for your printer by name. Select that port number in the firmware update tool.</li> </ol> <p>In my case, I had to run the calibration twice before it worked. I had no problems since then.</p>
<p>I suggest that you ask on <a href="http://shop.prusa3d.com" rel="nofollow noreferrer">shop.prusa3d.com</a> and click the Forum tab button. The folks there are very friendly and knowledgable. I'm sure you can get some help. You can also email support.</p> <p>There is also a question form at the bottom of <a href="http://www.prusa3d.com" rel="nofollow noreferrer">www.prusa3d.com</a> where you can ask questions.</p> <p>I'm sure you can get it going. I have a MK2 also and it has done very well by me!</p>
513
<p>The following shell script takes a list of arguments, turns Unix paths into WINE/Windows paths and invokes the given executable under WINE.</p> <pre><code>#! /bin/sh if [ "${1+set}" != "set" ] then echo "Usage; winewrap EXEC [ARGS...]" exit 1 fi EXEC="$1" shift ARGS="" for p in "$@"; do if [ -e "$p" ] then p=$(winepath -w $p) fi ARGS="$ARGS '$p'" done CMD="wine '$EXEC' $ARGS" echo $CMD $CMD </code></pre> <p>However, there's something wrong with the quotation of command-line arguments.</p> <pre><code>$ winewrap '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' -smt /tmp/smtlib3cee8b.smt Executing: wine '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' '-smt' 'Z: mp\smtlib3cee8b.smt' wine: cannot find ''/home/chris/.wine/drive_c/Program' </code></pre> <p>Note that:</p> <ol> <li>The path to the executable is being chopped off at the first space, even though it is single-quoted.</li> <li>The literal "\t" in the last path is being transformed into a tab character.</li> </ol> <p>Obviously, the quotations aren't being parsed the way I intended by the shell. How can I avoid these errors?</p> <p>EDIT: The "\t" is being expanded through two levels of indirection: first, <code>"$p"</code> (and/or <code>"$ARGS"</code>) is being expanded into <code>Z:\tmp\smtlib3cee8b.smt</code>; then, <code>\t</code> is being expanded into the tab character. This is (seemingly) equivalent to</p> <pre><code>Y='y\ty' Z="z${Y}z" echo $Z </code></pre> <p>which yields </p> <pre><code>zy\tyz </code></pre> <p>and <em>not</em></p> <pre><code>zy yz </code></pre> <p>UPDATE: <code>eval "$CMD"</code> does the trick. The "<code>\t</code>" problem seems to be echo's fault: "If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined." (<a href="http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html" rel="nofollow noreferrer">POSIX specification of <code>echo</code></a>)</p>
<p>I you do want to have the assignment to CMD you should use </p> <p><code>eval $CMD</code> </p> <p>instead of just <code>$CMD</code> in the last line of your script. This should solve your problem with spaces in the paths, I don't know what to do about the "\t" problem.</p>
<p>You can try preceeding the spaces with \ like so:</p> <pre><code>/home/chris/.wine/drive_c/Program Files/Microsoft\ Research/Z3-1.3.6/bin/z3.exe </code></pre> <p>You can also do the same with your \t problem - replace it with \\t.</p>
5,678
<p>It is good practice to use the main method to test a java/.net class?</p> <p>I've seen it reccommended in some text books, but to me it seems like using a unit testing framework would make more sense...</p> <p>The main method gives you one point of entry to the class and you can test one aspect of the classes functionality. You could I guess test many but it doesn't seem to make sense as much as using Junit or Nunit.</p>
<p>One obvious advantage seems to be that you can whitebox test the class. That is, you can test the internals of it (private methods for example). You can't do that with unit-tests, nor would you wan't that, they are primarily there to test the interface and the behavior from the users perspective.</p>
<p>The main method can be useful for certain situations, but using a debugger and then writing a unit test (to provide some insurance against regressions) is a more robust solution.</p>
30,675
<p>What is the best plugin for Rails that <strong>gzips</strong> my webpage output?</p> <p><strong>Edit:</strong> The company I am hosting with has stated they will not install <code>mod_deflate</code>.</p>
<p>Unless you are running your Rails application without another webserver (which usually isn't a great idea), you should probably look at your webserver. All major webservers have options to enable gzip. For example, for Apache, you can use <a href="http://httpd.apache.org/docs/2.0/mod/mod_deflate.html" rel="noreferrer">mod_deflate</a>.</p>
<p>Have you tried enabling compression in apache via <a href="http://httpd.apache.org/docs/2.0/mod/mod_deflate.html" rel="nofollow noreferrer">mod_deflate</a>?</p>
31,181
<p>Is there an easy way to find the storage card's path on a Windows Mobile device when there is a storage card and a bluetooth ftp connection?</p>
<p>Keep in mind that "\Storage Card" is english oriented. A device made for a different region may have a different name. The name of the storage card path on my device varies with how I am using the device. </p> <p>Some time ago in the MSDN forms I responded to a few questions on how to detect the storage cards in the file system and how does one get the storage card's capacity. I wrote the following could are a response to those questions and thought it would be helpful to share. Storage cards show up in the file system as temporary directories. This program examines the objects in the root of the device and any folders that have temp attribute are considered to be a positive match </p> <pre><code>using System; using System.IO; using System.Runtime.InteropServices; namespace StorageCardInfo { class Program { const ulong Megabyte = 1048576; const ulong Gigabyte = 1073741824; [DllImport("CoreDLL")] static extern int GetDiskFreeSpaceEx( string DirectoryName, out ulong lpFreeBytesAvailableToCaller, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes ); static void Main(string[] args) { DirectoryInfo root = new DirectoryInfo("\\"); DirectoryInfo[] directoryList = root.GetDirectories(); ulong FreeBytesAvailable; ulong TotalCapacity; ulong TotalFreeBytes; for (int i = 0; i &lt; directoryList.Length; ++i) { if ((directoryList.Attributes &amp; FileAttributes.Temporary) != 0) { GetDiskFreeSpaceEx(directoryList.FullName, out FreeBytesAvailable, out TotalCapacity, out TotalFreeBytes); Console.Out.WriteLine("Storage card name: {0}", directoryList.FullName); Console.Out.WriteLine("Available Bytes : {0}", FreeBytesAvailable); Console.Out.WriteLine("Total Capacity : {0}", TotalCapacity); Console.Out.WriteLine("Total Free Bytes : {0}", TotalFreeBytes); } } } } </code></pre>
<p>On Windows CE 5 (which is the base for Windows Mobile 6) the storage cards get mounted at the root file system as "Storage Card\", "Storage Card2\", etc.</p> <p>To find out if it's mounted call GetFileAttributes (or the remote version CeGetFileAttributes I believe) passing in the full path ("\Storage Card\"). If it returns INVALID_FILE_ATTRIBUTES then it's not mounted, otherwise check to make sure it's a directory before returning true.</p>
6,149
<p>I'm after some good tips for fluent interfaces in C#. I'm just learning about it myself but keen to hear what others think outside of the articles I am reading. In particular I'm after:</p> <ol> <li>when is fluent too much?</li> <li>are there any fluent patterns?</li> <li>what is in C# that makes fluent interfaces more fluent (e.g. extension methods)</li> <li>is a complex fluent interface still a fluent one?</li> <li>refactoring to arrive at a fluent interface or refactoring an existing fluent interface</li> <li>any good examples out there that you have worked with or could recommend?</li> </ol> <p>If you could post one tip or thought, or whatever per post. I want to see how they get voted on, too.</p> <p>Thank you in advance.</p>
<p>On your 4th point;</p> <p>Yes I think that a complex fluent interface can still be fluent.</p> <p>I think fluent interfaces are somewhat of a compromise. (although a good one!) There has been much research into using natural language for programming and generally natural language isn't precise enough to express programs.</p> <p>Fluent interfaces are constructed so that they write like a programming language, only a small subset of what you can express in a natural language is allowed, but they read like a natural language. </p> <p>If you look at rhino mocks for example the writing part has been complicated compared to a normal library. I took me longer to learn mostly due to the fluent interface but it makes code a lot easier to read. Because programs are usually written once and read a lot more than once this is a good tradeoff.</p> <p>So to qualify my point a bit. A fluent interface that's complex to write but easy to read can still be fluent.</p>
<p>Sometime ago I had the same doubts you are having now. I've done some research and now I'm writing some posts to help in those topics.</p> <p>Check it at my blog:</p> <p><a href="https://www.codeproject.com/articles/99542/guidelines-to-fluent-interface-design-in-c-part" rel="nofollow noreferrer">Guidelines to Fluent Interface design in C# part 1</a> </p> <p>And in the following posts I will cover every one of the points you mentioned.</p> <p>Best regards André Vianna</p>
27,775
<p>When using APIs handling asynchronous events in .Net I find myself unable to predict how the library will scale for large numbers of objects.</p> <p>For example, using the Microsoft.Office.Interop.UccApi library, when I create an endpoint it gets events when phone events happen. Now let's say I want to create 1000 endpoints. The number of events per endpoint is small, but is what's happening behind the scenes in the API able to keep up with the event flow? I don't know because it never says how it's architected.</p> <p>Let's say I want to create all 1000 objects in the main thread. Then I want to put the Login method into a large thread pool so all objects login in parallel. Then once all the objects have logged in the next phase will begin.</p> <p>Are the event callbacks the API raises happening in the original creating thread? A separate threadpool? Or the same threadpool I'm accessing with ThreadPool.QueueUserWorkItem?</p> <p>Would I be better putting each object in it's own thread? Grouping a few objects in each thread? Or is it fine just creating all 1000 objects in the main thread and through .Net magic it will all be OK?</p> <p>thanx</p>
<p>The events from interop assemblies are just wrappers around the COM connection points. The thread on which the call from the connection point arrive depends on the threading model of the object that advised on that connection point. COM will ensure the proper thread switching for this.</p> <p>If your objects are implemented on the main thread, which in .Net is usually an STA, all events should arrive on that same thread. If you want your calls to arrive on a random thread from the COM thread pool (which I think is the same as the CLR thread pool), you need to create your objects on a thread that is configured as an MTA.</p> <p>I would strongly advise against creating a thread for each object: 1) If you create these threads as STA, each of them will have a message queue, waisting system resource; 2) If you create them as MTA, nothing guarantees you the event call will arrive on your thread; 3) You'll have 1000 idle threads doing nothing and just waiting on an event to shutdown; and 4) Starting up and shutting down all these threads will have terrible perf cost on your application.</p>
<p>I just wanted to note that in .NET 2.0 and greater it's possible to programmatically increase the maximum number of threads in the thread pool using <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.setmaxthreads(VS.80).aspx" rel="nofollow noreferrer">ThreadPool.SetMaxThreads()</a>. Given this you can put a hard cap on the number of threads and so ensure the scheduler won't be brought to it's knees by the overhead.</p> <p>Even more useful in this sort of case, you can set the minimum number of threads with <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.setminthreads(VS.80).aspx" rel="nofollow noreferrer">ThreadPool.SetMinThreads()</a>. With this you can ensure that you only pay the "horrible performance price" Franci is talking about once, at application startup. You could balance this against the expected number peak of users and so ensure you won't be creating tons of new threads.</p> <p>A single new thread creation won't destroy you. What I would be worried about is the case where a lot of threads need to be created at the same time. If you can say that this will only happen at startup you would be golden.</p>
28,143
<p>There are many usability evaluation techniques that have been developed over the history of software development. But it seems to me that they are rarely used in practice.</p> <p>Why aren't usability evaluation tools and methods actually used much?</p> <p>Or are they used more than I've been led to believe?</p>
<p>They are rare, <a href="http://en.wikipedia.org/wiki/Human-computer_interaction" rel="nofollow noreferrer">HCI</a> is a specialist area in IT. I know next to nothing about it, but a friend of mine was a HCI engineer and she could recite reams of data about the topic, show websites, groups, academic papers, etc.</p> <p>HCI is still an area that (undeservedly) gets little attention, probably because its seen as less important to the business of selling software - shrinkwrapped software is sold on marketing claims, not actual usability of it, so there is little incentive for the people who pay for the software development to pay for HCI too.</p> <p>If you want to learn more (and its good you should encourage its use - I've used too many crappy interfaces, and though I try to develop better I often don't get the chance to really improve things for my users), try <a href="http://www.hcibook.com/e3/" rel="nofollow noreferrer">this website/book</a>.</p>
<p>This may be a bit of a tangent, but two of the best sources of good usability advice I know of are Steve Krug and Kathy Sierra.</p> <p>Sadly Kathy doesn't blog any longer, but you can see years of observations in the archive of her blog, "<a href="http://headrush.typepad.com/" rel="nofollow noreferrer">Creating Passionate Users</a>".</p> <p>Steve Krug's book <a href="http://www.sensible.com/" rel="nofollow noreferrer">"Don't Make Me Think"</a> may be one of the best usability bibles ever (and he spends a fair amount of time discussing usability testing tools and strategies).</p>
44,967
<p>I have an third-party applet that requires JRE v1.5_12 to work correctly. THe user is installing JRE v1.6.07 or better. It used to be with 1.5 and below, that I could have multiple JRE's on the machine and specify which one to use - but with 1.6 that apepars to be broken. How do I tell the browser I want to use v1.5_12 instead of the latest one installed?</p>
<p>For security reasons, you can no longer force it to use older JRE's. Say release 12 has a huge security hole, and everyone installs release 13 to patch it. Evil java applets could just say "run with release 12 please" and then carry out their exploits, rendering the patches useless.</p> <p>Most likely you have some code with security holes that the newer JRE is blocking, because it would cause a security risk. Fix your code, should be pretty minor changes, then you wont have to worry.</p> <p>See <a href="http://java.sun.com/javase/6/webnotes/family-clsid.html" rel="noreferrer">this page</a> for more info on the change.</p>
<p>The new applet engine (that will be shipped with 1.6u10 when Sun gets around to officially shipping it) gives you a tremendous amount of control in this area. It's going to take awhile to get enough systems on 6u10 to where you can actually rely on the functionality (unless you are corporate) - but it is coming (seems like it's about 5 years too late).</p> <p>Here's a JavaWorld article describing this at a very high level: <a href="http://www.javaworld.com/javaworld/jw-09-2008/jw-09-6u10.html" rel="nofollow noreferrer">article text</a></p> <p>6u10 also has a deployment toolkit that provides super easy to use javascript snippets that you can include in your applet deployment pages. These snippets handle JRE version checking, user notification, JRE downloading on demand, and a number of other things that are otherwise a hassle (not impossible, just a pain). The deployment kit has been designed to fail gracefully, so it does amazing things if 6u10 or above is installed, and drops back to decent behavior for older JREs.</p> <p>One really, really nice thing about the new applet engine is that it runs in a separate process space from the browser. This has a couple of very big advantages, including the ability to have multiple applets running in different versions of the JRE (yes, you can specify different required JREs, including restrictions on how old and how new of JRE you support - the applet engine will re-use JREs if it can, but it has the ability to start up a different one if it needs).</p>
20,369
<p>Does anyone know how I can achieve the following effect in OpenGL:</p> <ul> <li>Change the brightness of the rendered scene</li> <li>Or implementing a Gamma setting in OpenGL</li> </ul> <p>I have tried by changing the ambient parameter of the light and the type of light (directional and omnidirectional) but the result was not uniform. TIA.</p> <p>Thanks for your help, some additional information: * I can't use any windows specifics API. * The gamma setting should not affect the whole window as I must have different gamma for different views.</p>
<p>On win32 you can use SetDeviceGammaRamp to adjust the overall brightness / gamma. However, this affects the entire display so it's not a good idea unless your app is fullscreen.</p> <p>The portable alternative is to either draw the entire scene brighter or dimmer (which is a hassle), or to slap a fullscreen alpha-blended quad over the whole scene to brighten or darken it as desired. Neither of these approaches can affect the gamma-curve, only the overall brightness; to adjust the gamma you need grab the entire scene into a texture and then render it back to the screen via a pixel-shader that runs each texel through a gamma function.</p> <p>Ok, having read the updated question, what you need is a quad with blending set up to darken or brighten everything underneath it. Eg.</p> <pre><code>if( brightness &gt; 1 ) { glBlendFunc( GL_DEST_COLOR, GL_ONE ); glColor3f( brightness-1, brightness-1, brightness-1 ); } else { glBlendFunc( GL_ZERO, GL_SRC_COLOR ); glColor3f( brightness, brightness, brightness ); } glEnable( GL_BLEND ); draw_quad(); </code></pre>
<p><a href="http://www.gamedev.net/community/forums/topic.asp?topic_id=435400" rel="nofollow noreferrer">http://www.gamedev.net/community/forums/topic.asp?topic_id=435400</a> might be an answer to your question otherwise you could probably implement a gamma correction as a pixel shader</p>
16,826
<p>By default, when you <code>sudo gem install thegemname</code> it will install executables into <code>/usr/bin/</code></p> <p>Is there a way to change this? For example, to install them into <code>/usr/local/rubygems/bin</code> (or any other path)?</p> <p>The path doesn't seem to be hard-coded into the gemspec file, so I don't see why this shouldn't be possible (although I have very little experience with Ruby/Gems)</p>
<p>See <a href="http://www.rubygems.org/read/chapter/11" rel="nofollow noreferrer">http://www.rubygems.org/read/chapter/11</a> and specify a <code>~/.gemrc</code> which defines a gemhome variable.</p> <p>For example:</p> <pre><code>gemhome: /usr/local/rubygems </code></pre> <p>You can also place this file in <code>/etc/gemrc</code></p> <p>Alternatively you can set the <a href="http://docs.rubygems.org/read/chapter/12" rel="nofollow noreferrer"><code>GEM_HOME</code> env-variable</a>:</p> <pre><code>$ export GEM_HOME=/tmp/gemtest $ gem install bundler $ ls /tmp/gemtest/bin/ bundle </code></pre> <p><strong>Update (10 years later):</strong></p> <p>Andrey Rodionov below suggest using</p> <pre><code>gem: --bindir /usr/bin </code></pre>
<p>To install the executable to a desired directory, the command line option <code>--bindir</code> may be used:</p> <pre><code>sudo gem install thegemname --bindir /usr/local/rubygems/bin </code></pre> <p>Tried this option successfully with gem version 2.0.14.1. <BR><BR> For more command line options, run <code>gem install --help</code> on the command line.</p>
43,230
<p>When I attempt to update the code on a IIS webserver by replacing the old code with my new code, I receive 503 Service Unavailable replys when attempting to access any of the replaced pages on the server. </p> <p>What is the cause of this failure and what steps can I take to correct such errors? </p> <p>Thanks!</p>
<p>I would do a few things:</p> <p>Check the windows event logs for any web related errors.</p> <p>Check the IIS logs to see if there is anything odd with the requests.</p> <p>Double check the permissions of all the new files, make sure they match the files that do work.</p> <p>Perform an IISReset after you deployed.</p> <p>Make sure your virtual directory, or sub folders are set up correctly in IIS and didn't change in the deployment.</p>
<p>Could be lots of things. Did you try iisreset after updating the pages?</p>
21,488
<p>What is the best way to get the TAPI version and additional TAPI information with C#? </p>
<p>Interop.</p> <p>Use the <em>lpdwAPIVersion</em> parameter of the lineInitializeEx function. <a href="http://msdn.microsoft.com/en-us/library/ms735983(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms735983(VS.85).aspx</a></p> <p>"Upon successful completion of this request, this location is filled with the highest API version supported by TAPI, thereby allowing the application to detect and adapt to having been installed on a system with a different version of TAPI."</p> <p>You're going to have to start plugging away with Interop calls sooner or later when you're programming TAPI.</p>
<p>There are also some great libraries and controls (for example a set of ActiveX controls) that can make TAPI programming extremely easy. Dealing with API level code, PInvoke, callbacks, etc. can be very tedious. You can do a quick online search and see if one of those options would work for you.</p>
37,145
<p>I've got a lot of small DLLs which I would like to make into one big(er) DLL (as <a href="https://stackoverflow.com/questions/127029/comparing-cold-start-to-warm-start#129090">suggested here</a>). I can do so by merging my projects but I would like a less intrusive way. </p> <p>Can several DLLs be merged into one unit? </p> <p>A quick search found <a href="http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/22fed4ab-a3f8-4d5f-be03-6d5e7dc3db01/" rel="nofollow noreferrer">this thread</a> that claims this is not possible. Does anyone know otherwise?</p> <p><em>Note that I'm talking about native C++ code not .NET so ILMerge is out.</em></p>
<p>I don't know about merging dlls, but I'm sure you can link the intermediate object files into one dll. This would only require changes in your build script.</p>
<p>Also, there was a product that made a .LIB out of .DLLs. You could then link your exe against that .LIB and get rid of the .DLLs altogether. Perhaps you could link a .DLL out of the .LIB - I'm not sure.</p> <p>The product is here: <a href="http://www.binary-soft.com/dll2lib/dll2lib.htm" rel="nofollow noreferrer">http://www.binary-soft.com/dll2lib/dll2lib.htm</a> I'm not sure, if it works anymore, if it's supported or even sold. It sure appears pricey, but it used to have (nag-enabled) free trial period.</p>
17,542
<p>I have an images folder with a png in it. I would like to set a MenuItem's icon to that png. How do I write this in procedural code?</p>
<pre><code>menutItem.Icon = new System.Windows.Controls.Image { Source = new BitmapImage(new Uri("images/sample.png", UriKind.Relative)) }; </code></pre>
<p>You can also use your Visual Studio to insert a icon. This is the easiest way</p> <ul> <li>Right click at you project in the solution explorer</li> <li>chose Properties</li> <li>Make sure you're in the application page.</li> <li>@ recources you see: Icon and Manifest</li> <li>@ Icon: Click browse and pick your icon.</li> </ul> <p>Problem solved.</p>
5,012
<p>We've had <a href="https://stackoverflow.com/questions/94101/how-to-type-faster">this question</a> already, but I want to narrow it down to already high-speed typists. </p> <p>The original poster had hit a barrier of 75 WPM and wanted to increase his speed. I'm at a barrier where I can reliably type around 130, and I can sometimes hit 150, probably depending on the distribution of words in the text. </p> <p>I feel that methods to increase speed from this high end to higher might be different than going from 30 to 60, or even 75 to 100. Anybody have any suggestions?</p>
<p>You need to start looking at the hardware... Try out different keyboards to get the best reactionary keyboard to your typing method. I find myself typing much faster on some keyboards even though they are identically sized with identical features...the key response times are slight different.</p>
<p>If you're trying to learn how to type your favorite language faster, may I suggest that you learn a better language?</p> <p>When I typed dictation a lifetime ago, I could type over 120wpm on a dictaphone. When I type C I rarely exceed 90wpm, but when I write lisp, I don't even reach 50wpm.</p> <p>The time you're spending typing isn't being spent thinking.</p> <p>If you're trying to learn how to type copy more quickly, learning to read more quickly can help. I had great success using <a href="http://en.wikipedia.org/wiki/Rapid_Serial_Visual_Presentation" rel="nofollow noreferrer">rapid serial visual presentation</a> to increase my reading speed.</p>
36,778
<p>On Mac OS X 10.5 I downloaded the latest version of Apache 2.2.9. After the usual configure, make, make install dance I had a build of apache without mod_rewrite. This wasn't statically linked and the module was not built in the /modules folder either.</p> <p>I had to do the following to build Apache and mod_rewrite:</p> <pre><code>./configure --prefix=/usr/local/apache2 --enable-rewrite=shared </code></pre> <ul> <li>Is there a way to tell Apache to build all modules as Shared Modules (DSOs) so I can control loading from the Apache config?</li> <li>Now that I have built Apache and the mod_rewrite DSO, how can I build another shared module without building all of Apache?</li> </ul> <p>(The last time I built Apache (2.2.8) on Solaris, by default it built everything as a shared module.)</p>
<p>Try the <code>./configure</code> option <code>--enable-mods-shared="all"</code>, or <code>--enable-mods-shared="&lt;list of modules&gt;"</code> to compile modules as shared objects. See further <a href="http://httpd.apache.org/docs/2.2/programs/configure.html#otheroptfeat" rel="noreferrer">details in Apache 2.2 docs</a></p> <p>To just compile Apache with the ability to load shared objects (and add modules later), use <code>--enable-so</code>, then consult the documentation on compiling modules seperately in the <a href="http://httpd.apache.org/docs/2.2/dso.html" rel="noreferrer">Apache 2.2. DSO docs</a>.</p>
<pre><code>./configure --prefix=/usr/local/apache2 --enable-mods-shared="all" --enable-proxy=shared </code></pre> <p>To get rewrite, proxy and bunch of other modules, I used the above command. In my previous installation, using --enable-mods-shared="all" compiled/installed the proxy module as well. But in <code>v2.2.22</code> "all" did not include the proxy module.</p>
5,774
<p>If I want to construct a std::string with a line like:</p> <pre><code>std::string my_string("a\0b"); </code></pre> <p>Where i want to have three characters in the resulting string (a, null, b), I only get one. What is the proper syntax?</p>
<h3>Since C++14</h3> <p>we have been able to create <a href="https://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s" rel="noreferrer">literal <code>std::string</code></a></p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; int main() { using namespace std::string_literals; std::string s = &quot;pl-\0-op&quot;s; // &lt;- Notice the &quot;s&quot; at the end // This is a std::string literal not // a C-String literal. std::cout &lt;&lt; s &lt;&lt; &quot;\n&quot;; } </code></pre> <h3>Before C++14</h3> <p>The problem is the <code>std::string</code> constructor that takes a <code>const char*</code> assumes the input is a C-string. C-strings are <code>\0</code> terminated and thus parsing stops when it reaches the <code>\0</code> character.</p> <p>To compensate for this, you need to use the constructor that builds the string from a char array (not a C-String). This takes two parameters - a pointer to the array and a length:</p> <pre><code>std::string x(&quot;pq\0rs&quot;); // Two characters because input assumed to be C-String std::string x(&quot;pq\0rs&quot;,5); // 5 Characters as the input is now a char array with 5 characters. </code></pre> <p>Note: C++ <code>std::string</code> is <strong>NOT</strong> <code>\0</code>-terminated (as suggested in other posts). However, you can extract a pointer to an internal buffer that contains a C-String with the method <code>c_str()</code>.</p> <p>Also check out <a href="https://stackoverflow.com/questions/164168/how-do-you-construct-a-stdstring-with-an-embedded-null#164257">Doug T's answer</a> below about using a <code>vector&lt;char&gt;</code>.</p> <p>Also check out <a href="https://stackoverflow.com/a/34723611/14065">RiaD</a> for a C++14 solution.</p>
<p>Almost all implementations of std::strings are null-terminated, so you probably shouldn't do this. Note that "a\0b" is actually four characters long because of the automatic null terminator (a, null, b, null). If you really want to do this and break std::string's contract, you can do:</p> <pre><code>std::string s("aab"); s.at(1) = '\0'; </code></pre> <p>but if you do, all your friends will laugh at you, you will never find true happiness.</p>
19,847
<p>I have Drupal 5 site where a button is clicked and it calls a JavaScript function. The function basically builds a string, and then redirects to another page on our site. After clicking the button, sometimes the user gets logged out and sees the "Access Denied" screen, even though they were previously logged in. The page where they are being redirected has the same access restrictions as the previous page, but regardless of that, they shouldn't be getting logged out.</p> <p>One user has this happen about half the time (the other half it works as it should), and another user has reported always being logged out when clicking that button. However, I'm always able to run it without a hitch on the machines I use, and I suspect it has to do with them using IE6. Has anyone run across this issue before, or have any ideas on what could be causing this? I've searched and posted in the Drupal forum, and searched in this forum, and have had no luck yet.</p>
<p>Many things come to mind.</p> <ul> <li>Is the page being redirected to on the same domain? domain.com and www.domain.com are NOT the same as far as cookies are concerned (depending on how they are set)..</li> <li>Can you reproduce it 100% reliably in any browser? No offense to your users, but users are liars (or at least bad at reporting technical bugs). I wouldn't trust something a user told me as fact ("oh, well, yeah, I was closing the browser between tries. but that shouldn't matter.").</li> <li>Is there something running on the server that is clearing out session, or is the session expiration limit set too loo?</li> </ul> <p>Moral: go try and reproduce the issue first, so you can narrow down exactly what it is. I suggest Firebug + Firecookie for debugging Firefox and general cookie problems, and Fiddler2 (a proxy) for debugging IE. </p>
<p>I think to be honest, the best way would be to post the code that's causing this.</p> <p>Drupal uses PHP sessions to do this, which use cookies... do any of the users have cookies switched off?</p> <p>There are many things that can be causing this, redirecting do a different domain, something clearing out the sessions (/tmp cleanup?), but usually, I'd put something like this down to the browser.</p> <p>Ask them if they can still reproduce using another browser (try firefox)... check their cookie security settings, and more.</p>
14,412
<p>I'm currently primarily a <a href="https://en.wikipedia.org/wiki/D_(programming_language)" rel="nofollow noreferrer">D</a> programmer and am looking to add another language to my toolbox, preferably one that supports the metaprogramming hacks that just can't be done in a statically compiled language like D.</p> <p>I've read up on Lisp a little and I would love to find a language that allows some of the cool stuff that Lisp does, but without the strange syntax, etc. of Lisp. I don't want to start a language flame war, and I'm sure both Ruby and Python have their tradeoffs, so I'll list what's important to me personally. Please tell me whether Ruby, Python, or some other language would be best for me.</p> <p>Important:</p> <ol> <li>Good metaprogramming. Ability to create classes, methods, functions, etc. at runtime. Preferably, minimal distinction between code and data, Lisp style.</li> <li>Nice, clean, sane syntax and consistent, intuitive semantics. Basically a well thought-out, fun to use, modern language.</li> <li>Multiple paradigms. No one paradigm is right for every project, or even every small subproblem within a project.</li> <li>An interesting language that actually affects the way one thinks about programming.</li> </ol> <p>Somewhat important:</p> <ol> <li>Performance. It would be nice if performance was decent, but when performance is a real priority, I'll use D instead.</li> <li>Well-documented. </li> </ol> <p>Not important:</p> <ol> <li>Community size, library availability, etc. None of these are characteristics of the language itself, and all can change very quickly.</li> <li>Job availability. I am not a full-time, professional programmer. I am a grad student and programming is tangentially relevant to my research.</li> <li>Any features that are primarily designed with very large projects worked on by a million code monkeys in mind.</li> </ol>
<blockquote> <p>I've read up on Lisp a little and I would love to find a language that allows some of the cool stuff that Lisp does, but without the strange syntax, etc. of Lisp.</p> </blockquote> <p>Wouldn't we all. </p> <blockquote> <p>minimal distinction between code and data, Lisp style</p> </blockquote> <p>Sadly, the minimal distinction between code and data and "strange" syntax are consequences of each other.</p> <p>If you want easy-to-read syntax, you have Python. However, the code is <em>not</em> represented in any of the commonly-used built-in data structures. It fails—as most languages do—in item #1 of your 'important' list. That makes it difficult to provide useful help.</p> <p>You can't have it all. Remember, you aren't the first to have this thought. If something like your ideal language existed, we'd all be using it. Since the real world falls short of your ideals, you'll have to re-prioritize your wish list. The "important" section has to be rearranged to identify what's <em>really</em> important to you.</p>
<p>I suggest that you try out both languages and pick the one that appeals to you. Both Python and Ruby can do what you want.</p> <p>Also read <a href="https://stackoverflow.com/questions/143586/what-scripting-language-to-learn-after-perl">this thread</a>.</p>
17,443
<p>I would really like to see a proportional font IDE, even if I have to build it myself (perhaps as an extension to Visual Studio). What I basically mean is MS Word style editing of code that sort of looks like the typographical style in <a href="http://www.research.att.com/~bs/3rd.html" rel="nofollow noreferrer">The C++ Programming Language book</a>.</p> <p>I want to set tab stops for my indents and lining up function signatures and rows of assignment statements, which could be specified in points instead of fixed character positions. I would also like bold and italics. Various font sizes and even style sheets would be cool.</p> <p>Has anyone seen anything like this out there or know the best way to start building one?</p>
<p>I'd still like to see a popular editor or IDE implement <a href="http://nickgravgaard.com/elastictabstops/" rel="noreferrer">elastic tabstops</a>.</p>
<p>The major problem with proportional fonts is they destroy the vertical alignment of the code and this is a fairly major loss when it comes to writing code.</p> <p>The vertical alignment makes it possible to manipulate rectangular blocks of code that span multiple lines by allowing block operations like cut, copy, paste, delete and indent, unindent etc to be easily performed.</p> <p>As an example consider this snippet of code:</p> <pre><code>a1 = a111; B2 = aaaa; c3 = AAAA; w4 = wwWW; W4 = WWWW; </code></pre> <p>In a mono-spaced font the <strong><em>=</em></strong> and the <strong><em>;</em></strong> all line up.</p> <p>Now if this text is loded into <strong>Word</strong> and display using a <strong>proportional font</strong> the text effectively turns into this:</p> <p><strong>NOTE:</strong> Extra white space added to show how the <strong><em>=</em></strong> and <strong><em>;</em></strong> no longer line up:</p> <pre><code>a1 = a1 1 1; B2 = aaaa; c3 = A A A A; w4 = w w W W; W4 = W W W W; </code></pre> <p>With the vertical alignment gone those nice blocks of code effectively disappear.</p> <p>Also because the cursor is no longer guaranteed to move vertically (i.e. the column number is not always constant from one line to the next) it makes it more difficult to write throw away macro scripts designed to manipulated similar looking lines.</p>
3,532
<p>Anyone know a quick easy way to migrate a SQLite3 database to MySQL?</p>
<p>Everyone seems to starts off with a few greps and perl expressions and you sorta kinda get something that works for your particular dataset but you have no idea if it's imported the data correctly or not. I'm seriously surprised nobody's built a solid library that can convert between the two.</p> <p>Here a list of ALL the differences in SQL syntax that I know about between the two file formats: The lines starting with:</p> <ul> <li>BEGIN TRANSACTION</li> <li>COMMIT</li> <li>sqlite_sequence</li> <li>CREATE UNIQUE INDEX</li> </ul> <p>are not used in MySQL</p> <ul> <li>SQLite uses <code>CREATE TABLE/INSERT INTO &quot;table_name&quot;</code> and MySQL uses <code>CREATE TABLE/INSERT INTO table_name</code></li> <li>MySQL doesn't use quotes inside the schema definition</li> <li>MySQL uses single quotes for strings inside the <code>INSERT INTO</code> clauses</li> <li>SQLite and MySQL have different ways of escaping strings inside <code>INSERT INTO</code> clauses</li> <li>SQLite uses <code>'t'</code> and <code>'f'</code> for booleans, MySQL uses <code>1</code> and <code>0</code> (a simple regex for this can fail when you have a string like: 'I do, you don't' inside your <code>INSERT INTO</code>)</li> <li>SQLLite uses <code>AUTOINCREMENT</code>, MySQL uses <code>AUTO_INCREMENT</code></li> </ul> <p>Here is a very basic hacked up perl script which works for <em>my</em> dataset and checks for many more of these conditions that other perl scripts I found on the web. Nu guarantees that it will work for your data but feel free to modify and post back here.</p> <pre><code>#! /usr/bin/perl while ($line = &lt;&gt;){ if (($line !~ /BEGIN TRANSACTION/) &amp;&amp; ($line !~ /COMMIT/) &amp;&amp; ($line !~ /sqlite_sequence/) &amp;&amp; ($line !~ /CREATE UNIQUE INDEX/)){ if ($line =~ /CREATE TABLE \&quot;([a-z_]*)\&quot;(.*)/i){ $name = $1; $sub = $2; $sub =~ s/\&quot;//g; $line = &quot;DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n&quot;; } elsif ($line =~ /INSERT INTO \&quot;([a-z_]*)\&quot;(.*)/i){ $line = &quot;INSERT INTO $1$2\n&quot;; $line =~ s/\&quot;/\\\&quot;/g; $line =~ s/\&quot;/\'/g; }else{ $line =~ s/\'\'/\\\'/g; } $line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g; $line =~ s/THIS_IS_TRUE/1/g; $line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g; $line =~ s/THIS_IS_FALSE/0/g; $line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g; print $line; } } </code></pre>
<pre><code>echo ".dump" | sqlite3 /tmp/db.sqlite &gt; db.sql </code></pre> <p>watch out for CREATE statements</p>
3,920
<p>After printing successfully for a while I received an error saying:</p> <p>Tool 0 Failure!<br> Temp limit reached <br> Shutdown or restart.<br></p> <p>The front panel is not responsive and doesn't allow the printer to print at all. If I quickly go to monitor mode it shows tool 0 temperature in the ~700°C range; which made me think it was the thermocouple.On the motherboard I unplugged the thermocouple and the same error occurred, I then swapped the other thermocouple and put it in its place and got the same error except the tool 1 temperature showed "NC". </p> <p>I had recently taken apart the extruders to change out the nozzles and thought I had possibly smashed the wires when putting it together but now I don't think that's the case. </p> <p>I'm on the phone with FlashForge's tech support but wanted to see if someone else has had the same experience for cross reference.</p> <p>What's the underlying issue? Is there a quick solution to this that can get me printing right away (I'm under a deadline)? What's the end solution?</p>
<p>It sounds like a failed TC amp chip. But we need to rule out some other stuff. </p> <p>Some important facts about the Creator Pro temp sensor:</p> <ul> <li>If you smash and short the two thermocouple wires together, the printer will simply read room temp.</li> <li>If you cut or disconnect the thermocouple wires, the printer will report NC for "not connected."</li> <li>The thermocouple lookup table in the firmware only goes up to 300C. </li> </ul> <p>Seeing a number over 300C means either a bad thermocouple amp chip, or excess voltage on the TC wires due to a short to something else in the hot block. (However, such a short will usually fry the entire controller board to smithereens.)</p> <p>To rule out stray voltage entering the TC wires, completely detach both thermocouples from the hot blocks and lay them out not touching anything metal. Do you still get an unusually high reading on tool 0? </p> <p>To rule out an issue with the specific thermocouple, swap thermocouples between tool 0 and tool 1 and see if the problem moves with the TCs.</p> <p>If the TC is not touching anything, and the problem stays with the tool when you swap wires, and you STILL get >300C reads, the thermocouple amp chip has failed. It is possible to replace the chip if you have (or your friend has) a hot air rework station and some experience soldering. Or you can get a new mainboard from FlashForge. </p> <p>The next question is why this problem happened. You don't want to fix the symptoms with new parts but have an underlying issue cause the same failure to re-occur after you swap out parts. With the printer on but the heaters off, use a multimeter to check for voltage between the hot block and the printer's ground. Certain types of heater cartridge failure can short the hot block to +24v. This is highly dangerous and needs to be fixed before you continue using the printer. So make sure you check it before trying to repair anything else. </p>
<p>Oh yeah my printer had that. Specifically 2 Flash Forge Creator Pros, Replace the thermal couple. Done. Really fragile thermal couples they use.</p> <p>Edit I see you tried shorting the TC. Wouldn't shorting the TC, produce the same error?</p>
286
<p>Which Eclipse files is it appropriate to put under source control, aside from the sources obviously?</p> <p>In my project, specifically, I'm wondering about:</p> <blockquote> <p>.metadata/*<br> project-dir/.project<br> project-dir/.classpath<br> project-dir/.settings/* </p> </blockquote> <p>If there are any of these for which it depends, please explain your guidelines.</p>
<p>Metadata should not be managed in source control. They contain mostly data relevant to <em>your</em> workspace.</p> <p>The only exception is the <code>.launch</code> XML files (launcher definition).</p> <p>They are found in</p> <pre><code>[eclipse-workspace]\.metadata\.plugins\org.eclipse.debug.core\.launches </code></pre> <p>And they should be copied into your project directory: When your project is refreshed, those configurations will be displayed in the "Run configuration" dialog.</p> <p>That way, those launch parameter files can be also managed into the SCM.</p> <p>(Warning: Do <strong>uncheck the option "Delete configurations when associated resource is deleted"</strong> in the <em>Run</em>/<em>Launching</em>/<em>Launch Configuration</em> preference panel: It is common to soft-delete a project in order to import it back again - to force a reinitialization of the eclipse metadata. But this option, if checked, will remove your detailed launch parameters!)</p> <pre><code>project-dir/.project project-dir/.classpath project-dir/.settings/* </code></pre> <p>should be in your SCM (especially <code>.project</code> and <code>.classpath</code> according to the <a href="http://wiki.eclipse.org/FAQ_How_do_I_set_up_a_Java_project_to_share_in_a_repository%3F" rel="noreferrer">Eclipse documentation</a>).</p> <p><strong>The goal is that anyone can checkout/update his/her SCM workspace and import the Eclipse project into the Eclipse workspace.</strong></p> <p>For that, you want to use only <strong>relative paths</strong> in your .classpath, using <strong><a href="https://stackoverflow.com/questions/300328#300346">linked resources</a></strong>.</p> <p>Note: it is better if <code>project-dir</code> refers to an "external" project directory, not a directory created under the eclipse workspace. That way, the two notions (eclipse workspace vs. SCM workspace) are clearly separated.</p> <hr> <p>As <a href="https://stackoverflow.com/users/243516/ipsquiggle">ipsquiggle</a> mentions in the comment, and as I have alluded to <a href="https://stackoverflow.com/questions/452571/where-are-the-external-tools-launch-configurations-in-eclipse/452588#452588">in an old answer</a>, you can actually save the launching configuration as <strong>shared file</strong> directly in your project directory. All launching configuration can then be versioned like the other project files.</p> <p>(From the blog post <a href="http://eclipsesnippets.blogspot.com/2007/07/tip-creating-and-sharing-launch.html" rel="noreferrer">Tip: Creating and Sharing Launch Configurations</a> from KD)</p> <p><img src="https://i.stack.imgur.com/QZ26z.png" alt="alt text"></p>
<p>I have spent too many hours configuring eclipse workspace settings for new colleagues (and myself). What I ended up doing eventually was copying my own .metadata to the new developer machine.</p> <p>If you are working on a team, then I think the following are very good candidates to keep under version control:</p> <ul> <li>Installed JREs and their names</li> <li>Server Runtime Environments</li> <li>Java Editor Templates</li> <li>Version Control Keyboard Shortcuts</li> <li>Plugin settings that do not provide project specific settings</li> <li>Maven settings</li> <li>Preconfigured Perspectives</li> <li>...</li> </ul>
43,765
<p>I am a hobbyist programmer (started with VBA to make excel quicker) and have been working with VB.NET / C#.NET and am trying to learn ADO.NET.</p> <p>A facet of programming that has always frustrated me is what does 'good' look like? I am not a professional so have little to compare against. What makes a better programmer? Is it:</p> <ul> <li>They have a better understanding of all the objects / classes / methods in a given language?</li> <li>Their programs are more efficient?</li> <li>The design of their programs are much better in terms of better documentation, good choice of names for functions etc.?</li> </ul> <p>Put another way, if I were to look at the code of a professional programmer, what is the first thing that I would notice about their code relative to mine? For example, I read books like 'Professional ASP.NET' by Wrox press. Are the code examples in that book 'world class'? Is that the pinnacle? Would any top-gun programmer look at that code and think it was good code?</p>
<p>The list below is not comprehensive, but these are the things that I thought of in considering your question.</p> <ul> <li><p>Good code is well-organized. Data and operations in classes fit together. There aren't extraneous dependencies between classes. It does not look like "spaghetti."</p></li> <li><p>Good code comments explain why things are done not what is done. The code itself explains what is done. The need for comments should be minimal.</p></li> <li><p>Good code uses meaningful naming conventions for all but the most transient of objects. the name of something is informative about when and how to use the object.</p></li> <li><p>Good code is well-tested. Tests serve as an executable specification of the code and examples of its use.</p></li> <li><p>Good code is not "clever". It does things in straightforward, obvious ways.</p></li> <li><p>Good code is developed in small, easy to read units of computation. These units are reused throughout the code.</p></li> </ul> <p>I haven't read it yet, but the book I'm planning to read on this topic is <a href="https://rads.stackoverflow.com/amzn/click/com/0132350882" rel="noreferrer" rel="nofollow noreferrer">Clean Code</a> by Robert C. Martin.</p>
<p>Good code is easy to understand, easy to maintain, and easy to add to. Ideally, it is also as efficient as possible without sacrificing other indicators.</p>
47,843
<p>I've used Apache CXF to expose about ten java classes as web services.</p> <p>I've generated clients using CXF, Axis, and .NET.</p> <p>In Axis and CXF a "Service" or "Locator" is generated. From this service you can get a "Port". The "Port" is used to make individual calls to the methods exposed by the web service.</p> <p>In .NET the "Service" directly exposes the calls to the web service.</p> <p>Can someone explain the difference between a port, a service, a locator, and an endpoint when it comes to web services?</p> <p>Axis:</p> <pre><code>PatientServiceImplServiceLocator locator = new PatientServiceImplServiceLocator(); PatientService service = locator.getPatientServiceImplPort(); </code></pre> <p>CXF:</p> <pre><code>PatientServiceImplService locator = new PatientServiceImplService(); PatientService service = locator.getPatientServiceImplPort(); </code></pre> <p>.net:</p> <pre><code>PatientServiceImplService service = new PatientServiceImplService(); </code></pre>
<p>I found the information based on Kevin Kenny's answer, but I figured I'd post it here for others.</p> <p>A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:</p> <ul> <li><strong>Types</strong>– a container for data type definitions using some type system (such as XSD).</li> <li><strong>Message</strong>– an abstract, typed definition of the data being communicated.</li> <li><strong>Operation</strong>– an abstract description of an action supported by the service.</li> <li><strong>Port Type</strong>–an abstract set of operations supported by one or more endpoints.</li> <li><strong>Binding</strong>– a concrete protocol and data format specification for a particular port type.</li> <li><strong>Port</strong>– a single endpoint defined as a combination of a binding and a network address.</li> <li><strong>Service</strong>– a collection of related endpoints.</li> </ul>
<p>As you already mentioned, those terms mean different things in different stacks - there is no one right generic answer for web services.</p>
3,264
<p>When choosing which filament to use for a particular print does the color of the filament have any impact on it's performance, or is it purely a cosmetic choice?</p> <p>For example, are there any side-by-side comparisons available that demonstrate that differences do\don't exist between different color filaments from the same company\range, such as a particular filament needing a hotter bed because the pigment changes it's properties?</p>
<p>Depending on the pigment size and other additions, the melting temperature and crystalline/amorphous structure of prints vary vastly.</p> <p>Titanium white, the most common white pigment in the industry, needs to be applied in large doses to get a good coloration. This means that the brighter the white, the larger the percentage volume of the item is made up of the <em>pockets</em> in the polymer structure that contains the pigment, resulting in a more brittle structure.</p> <p>Carbon black on the other hand is one of the most effective black pigments known to man and can be used very sparingly. It also is an almost perfect UV-absorber, making such prints heat up much more than those of other colors. It also can protect the polymer itself from aging if the polymer chains degrade under UV light. ABS for example does undergo degradation in UV light.</p> <p>Some polymers also contain some kind of filler to adjust melting temperatures:</p> <p>I have encountered PLA spools from two different manufacturers in the almost exact same color before printing. However, the one brand printed well already at 190 °C, the other required 200 °C to print decently. The two filaments <em>also</em> looked vastly different after printing: the hotter printing one showed a much higher gloss after printing, which hints that they had a quite different makeup besides the PLA - either something in the one was making melting easier but reduced gloss or something that increased gloss also rose the melting point.</p> <p>Another thing I found was, that the clear PLA I got from china once printed best at 110 % flow of other PLAs in combination with only 185 °C, making me believe that something in the treatment to achieve the translucent filament also results in altering the flow behavior.</p>
<p>Yes in some cases it does.</p> <p>It is widely known in communities which are pickier about properties that white filament requires a percentage of pigments much higher than other colours, therefore white filaments are typically weaker (or significantly weaker) than most other colours.</p> <p>Another exception is black: ABS is not UV resistant, but if you use black ABS, the UV will not penetrate and, unless the surface is continuously scraped away, the UV resistance of black ABS is better than other colours.</p> <p>I remember some mentions in the Voron discord chats that red (at least from some manufacturers) is better than some other colours from the same manufacturer, but I don't remember the details. You can <a href="https://discord.com/invite/voron" rel="nofollow noreferrer">join</a> the chat yourself and search (before asking!) in the #filament chat.</p> <p>I remember reading that pure (&quot;natural&quot;) filaments are however not always better than filaments with colours added, but I cannot remember the source. It could be that some little amount of extra additives (the colour pigments) offer the polymer something to &quot;grab&quot;, so better than nothing. My guess, but I have no support for it.</p>
2,060