instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>What is a good way to perform animation using .NET?</p> <p>I would prefer not to use Flash if possible, so am looking for suggestions of ways which will work to implement different types of animation on a new site I am producing.</p> <p>The new site is for a magician, so I want to provide animated buttons (Cards turning over, etc.) and also embed video. Is it possible to do this without using Flash or is this the only real solution? I would like to keep it as cross-platform and standard as possible.</p>
<p><a href="http://silverlight.net/Default.aspx" rel="nofollow noreferrer">Silverlight</a> springs to mind as an obvious choice if you want to do animation using .NET on the web. It may not cover all platforms but will work in IE and FireFox and on the Mac.</p>
<p>JavaScript is probably the way to go if you want to avoid Flash. Check this: <a href="http://www.webreference.com/programming/javascript/java_anim/" rel="nofollow noreferrer">http://www.webreference.com/programming/javascript/java_anim/</a></p> <p>It won't work for embedded video, though, so you're stuck with Flash for that (or Silverlight, or <a href="http://en.wikipedia.org/wiki/QuickTime" rel="nofollow noreferrer">QuickTime</a>).</p>
2,878
<p>Pretty new to this scene and trying to find some documentation to adopt best practices. We're building a fairly large content site which will consist of various media catalogs and I'm trying to find some comparable data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before. Any insight / help would be greatly appreciated!</p>
<p>"data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before"</p> <p>Django imposes best practices on you. You don't have a lot of choices and can't make a lot of mistakes.</p> <p>MVC (while a noble aspiration) is implemented as follows:</p> <ul> <li>Data is defined in "models.py" files using the Django ORM models.</li> <li>urls.py file maps URL to view function. Pick your URL's wisely.</li> <li>View function does all processing, making use of models and methods in models</li> <li>Presentation (via HTML templates) invoked by View function. Essentially no processing can be done in presentation, just lightweight iteration and decision-making</li> </ul> <p>The model is defined for you. Just stick to what Django does naturally and you'll be happy.</p> <p>Architecturally, you usually have a stack like this.</p> <ul> <li><p>Apache does two things.</p> <ul> <li>serves static content directly and immediately </li> <li>hands dynamic URL to Django (via mod_python, mod_wsgi or mod_fastcgi). Django apps map URL to view functions (which access to database (via ORM/model) and display via templates.</li> </ul></li> <li><p>Database used by Django view functions.</p></li> </ul> <p>The architecture is well-defined for you. Just stick to what Django does naturally and you'll be happy.</p> <p>Feel free to read the <a href="http://docs.djangoproject.com/en/dev/" rel="noreferrer">Django documentation</a>. It's excellent; perhaps the best there is.</p>
<p>To understand django fundementals and the django take on MVC, consult the following: <a href="http://www.djangobook.com/" rel="nofollow noreferrer">http://www.djangobook.com/</a></p> <p>As a starting point to getting your hands dirty with ... "...trying to find some comparable data / architectural models"</p> <p>Here is a quick and dirty way to reverse engineer a database to get a models.py file, which you can then inspect to see how django would handle it.</p> <p>1.) get an er diagram that closely matches your target. For example something like this <a href="http://www.databaseanswers.org/data_models/product_catalogs/index.htm" rel="nofollow noreferrer">http://www.databaseanswers.org/data_models/product_catalogs/index.htm</a></p> <p>2.) create an sql script from the er diagram and create the database, I suggest Postgre, as some MySQL table type will not have forgien key constraints, but in a pinch MySQL or SQLITE will do</p> <p>3.) create and configure a django app to use that database. Then run: python manage.py inspectdb</p> <p>This will at least give you a models.py file which you can read to see how django attempts to model it.</p> <p>Note that the inspect command is intended to be a shortcut for dealing with legacy database when developing in django, and as such is not perfect. Be sure to read the following before attempting this: <a href="http://docs.djangoproject.com/en/dev/ref/django-admin/#ref-django-admin" rel="nofollow noreferrer">http://docs.djangoproject.com/en/dev/ref/django-admin/#ref-django-admin</a></p>
47,518
<p>What is the maximum number of threads that can be created by a process under Linux?</p> <p>How (if possible) can this value be modified?</p>
<p>Linux doesn't have a separate threads per process limit, just a limit on the total number of processes on the system (threads are essentially just processes with a shared address space on Linux) which you can view like this:</p> <pre><code>cat /proc/sys/kernel/threads-max </code></pre> <p>The default is the number of memory pages/4. You can increase this like:</p> <pre><code>echo 100000 &gt; /proc/sys/kernel/threads-max </code></pre> <p>There is also a limit on the number of processes (and hence threads) that a single user may create, see <code>ulimit/getrlimit</code> for details regarding these limits.</p>
<p>You can see the current value by the following command- cat /proc/sys/kernel/threads-max</p> <p>You can also set the value like</p> <p>echo 100500 > /proc/sys/kernel/threads-max</p> <p>The value you set would be checked against the available RAM pages. If the thread structures occupies more than 1/8th) of the available RAM pages, thread-max would be reduced accordingly.</p>
44,769
<p>If I modify or add an environment variable I have to restart the command prompt. Is there a command I could execute that would do this without restarting CMD?</p>
<p>You can capture the system environment variables with a vbs script, but you need a bat script to actually change the current environment variables, so this is a combined solution.</p> <p>Create a file named <code>resetvars.vbs</code> containing this code, and save it on the path:</p> <pre class="lang-vb prettyprint-override"><code>Set oShell = WScript.CreateObject("WScript.Shell") filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat") Set objFileSystem = CreateObject("Scripting.fileSystemObject") Set oFile = objFileSystem.CreateTextFile(filename, TRUE) set oEnv=oShell.Environment("System") for each sitem in oEnv oFile.WriteLine("SET " &amp; sitem) next path = oEnv("PATH") set oEnv=oShell.Environment("User") for each sitem in oEnv oFile.WriteLine("SET " &amp; sitem) next path = path &amp; ";" &amp; oEnv("PATH") oFile.WriteLine("SET PATH=" &amp; path) oFile.Close </code></pre> <p>create another file name resetvars.bat containing this code, same location:</p> <pre class="lang-vb prettyprint-override"><code>@echo off %~dp0resetvars.vbs call "%TEMP%\resetvars.bat" </code></pre> <p>When you want to refresh the environment variables, just run <code>resetvars.bat</code></p> <hr> <p><em>Apologetics</em>:</p> <p>The two main problems I had coming up with this solution were</p> <p><strong>a.</strong> I couldn't find a straightforward way to export environment variables from a vbs script back to the command prompt, and </p> <p><strong>b.</strong> the PATH environment variable is a concatenation of the user and the system PATH variables.</p> <p>I'm not sure what the general rule is for conflicting variables between user and system, so I elected to make user override system, except in the PATH variable which is handled specifically.</p> <p>I use the weird vbs+bat+temporary bat mechanism to work around the problem of exporting variables from vbs.</p> <p><strong>Note</strong>: this script does not delete variables.</p> <p>This can probably be improved.</p> <p><strong>ADDED</strong></p> <p>If you need to export the environment from one cmd window to another, use this script (let's call it <code>exportvars.vbs</code>):</p> <pre class="lang-vb prettyprint-override"><code>Set oShell = WScript.CreateObject("WScript.Shell") filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat") Set objFileSystem = CreateObject("Scripting.fileSystemObject") Set oFile = objFileSystem.CreateTextFile(filename, TRUE) set oEnv=oShell.Environment("Process") for each sitem in oEnv oFile.WriteLine("SET " &amp; sitem) next oFile.Close </code></pre> <p>Run <code>exportvars.vbs</code> in the window you want to export <strong>from</strong>, then switch to the window you want to export <strong>to</strong>, and type:</p> <pre class="lang-vb prettyprint-override"><code>"%TEMP%\resetvars.bat" </code></pre>
<p>Edit: this only works if the environment changes you're doing are as a result of running a batch file.</p> <p>If a batch file begins with <code>SETLOCAL</code> then it will always unravel back to your original environment on exit even if you forget to call <code>ENDLOCAL</code> before the batch exits, or if it aborts unexpectedly.</p> <p>Almost every batch file I write begins with <code>SETLOCAL</code> since in most cases I don't want the side-effects of environment changes to remain. In cases where I do want certain environment variable changes to propagate outside the batch file then my last <code>ENDLOCAL</code> looks like this:</p> <pre><code>ENDLOCAL &amp; ( SET RESULT1=%RESULT1% SET RESULT2=%RESULT2% ) </code></pre>
20,686
<p>I read a little of the help for my advanced installer 6.5.1 and couldn't find a way to change the version string except by hand.</p>
<p>Here is a snippet from one of our push scripts. Rob, maybe you'll find this useful too- Advanced installer provides the ability to set the ProductVersion of your installation package based on an existing compiled EXE. We use a custom build task in TFS to increment our build number and set our AssemblyInfo.cs files, then with the resulting main app EXE, we can do this:</p> <pre><code>:COMPILE_AIP SET AIP_DIR="C:\Program Files\Caphyon\Advanced Installer 7.1.3" ECHO Advanced Installer Directiry: %AIP_DIR% ECHO. ECHO ////////////////////////// ECHO //Compiling AIP Files...// ECHO ////////////////////////// ECHO. ECHO Setting version on all installers... ECHO Setting version on all installers... &gt;&gt; %DESTINATION_APP_DIR%_push_script_output.txt %AIP_DIR%\advancedinstaller /edit "&lt;pathtoaipfile&gt;\installproject.aip" /SetVersion -fromfile &lt;path to exe defining app version&gt; IF NOT ERRORLEVEL 0 GOTO ERROR_HANDLER </code></pre> <p>Hope this helps-</p>
<p>The files for creating an MSI are usually in XML format, we've created a little tool that runs as part of our build process that goes and changes the build number manually, try openning the advanced installer file in notepad and look for the "ProductVersion" string.</p> <p>Cheers, Rob.</p>
35,452
<p>I find myself writing delegates occasionally for really simple functions (take no arguments and return void for example) and am wondering if anyone knows someplace that has compiled a list of all the predefined delegates already available in the .NET framework so I can reuse them?</p> <p>To be clear I am looking for something like this:</p> <ul> <li>void System.AsyncCallback(System.IAsyncResult)</li> <li>int System.Comparison(T x, T y)</li> <li>void System.IO.ErrorEventHandler(object, System.Io.ErrorEventArgs)</li> </ul> <p>and so on</p> <p>If not, sounds like a good idea for a blog article.</p>
<p>Just look in the msdn database for (T) delegate.</p> <p>Here you got a direct link: <a href="http://social.msdn.microsoft.com/Search/en-us/?Query=(T)%20delegate" rel="noreferrer">List of delegates</a></p> <p>That should get you started.</p>
<p>In .NET 2.0 and later, use EventHandler if you have no arguments at all, and EventHandler&lt;T&gt; if you want to provide some custom data (you will need to derive a class from EventArgs with your additional data in it). If you have no EventArgs to use, pass EventArgs.Empty.</p> <p>Because EventArgs is a reference type, all instances of EventHandler&lt;T&gt; use the same JITted code.</p>
9,163
<p>A few months back I was tasked with implementing a unique and random code for our web application. The code would have to be user friendly and as small as possible, but still be essentially random (so users couldn't easily predict the next code in the sequence).</p> <p>It ended up generating values that looked something like this:</p> <pre><code>Af3nT5Xf2 </code></pre> <p>Unfortunately, I was never satisfied with the implementation. Guid's were out of the question, they were simply too big and difficult for users to type in. I was hoping for something more along the lines of 4 or 5 characters/digits, but our particular implementation would generate noticeably patterned sequences if we encoded to less than 9 characters.</p> <p>Here's what we ended up doing:</p> <p>We pulled a unique sequential 32bit id from the database. We then inserted it into the center bits of a 64bit RANDOM integer. We created a lookup table of easily typed and recognized characters (A-Z, a-z, 2-9 skipping easily confused characters such as L,l,1,O,0, etc.). Finally, we used that lookup table to base-54 encode the 64-bit integer. The high bits were random, the low bits were random, but the center bits were sequential.</p> <p>The final result was a code that was much smaller than a guid and looked random, even though it absolutely wasn't.</p> <p>I was never satisfied with this particular implementation. What would you guys have done?</p>
<p>In .NET you can use the RNGCryptoServiceProvider method GetBytes() which will "fill an array of bytes with a cryptographically strong sequence of random values" (from ms documentation).</p> <pre><code>byte[] randomBytes = new byte[4]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(randomBytes); </code></pre> <p>You can increase the lengh of the byte array and pluck out the character values you want to allow.</p>
<p>If by user friendly, you mean that a user could type the answer in then I think you would want to look in a different direction. I've seen and done implementations for initial random passwords that pick random words and numbers as an easier and less error prone string. </p> <p>If though you're looking for a way to encode a random code in the URL string which is an issue I've dealt with for awhile then I what I have done is use 64-bit encoded GUIDs.</p>
5,504
<p>Is it possible to automatically launch an application from a USB flash drive (bypassing windows prompt asking user what he wants to do)? on windows XP or vista.</p> <p>I looked into "autorun.inf" and "open" entry seems to work only for CD drives for Windows XP SP2+ and Vista. Is it possible to launch program automatically on all windows versions?</p> <p>I don't care if autorun is disabled by user in Windows settings.</p>
<p>First of all, some people choose to disable autorun for security reasons; but Windows computers up to Vista have it enabled. Edit: <strong>Apparently the functionality was removed from Windows 7 onwards.</strong></p> <p>Put a file named autorun.inf in the root of your USB flash drive. This is what's in mine:</p> <pre><code>[Autorun] Open=PStart.exe Action=Start portable apps Icon=diskicon.ico </code></pre> <p>What it does: when you insert this disk, starts <code>PStart.exe</code></p> <p>On older computers, the program specified in <code>Open=</code> will launch automatically.</p> <p>On most modern computers (Windows XP SP2+, Vista), dialog "what do you want to do" will be displayed (for security reasons), but what you have in <code>autorun.inf</code> will display as the selected default, with <code>Icon=</code> as icon and <code>Action=</code> as description. If you want to launch it, just click the "OK" button in the dialog.</p> <p>So, although I'm not aware of any way to start the application (e.g. <a href="http://pegtop.net/start/" rel="noreferrer">PStart</a>) immediately, it is possible to insert flash disk with this configuration and start application by clicking OK.</p> <p>Tested on different computers, running Windows XP without a SP, also on Windows XP sp 1, sp2, sp3, and on various Vistas (not sure which types, but should work all the way from Vista Home Basic to Vista Enterprise Super-Mega-Premium-Extended Edition) and "Windows 7". Also works on Windows 2000 (although autorun on Win2000 for removable drives is not enabled in default configuration).</p> <p>Note that some applications, in addition, may trigger the "unknown/unsigned exacutable" security dialog, as if you opened them manually.</p> <p>Edit: For more details, see also:<br> <a href="http://msdn.microsoft.com/en-us/magazine/cc301341.aspx" rel="noreferrer">Autoplay in Windows XP: Automatically Detect and React to New Devices on a System</a></p>
<p>there are also U3 usb sticks arround, they will be reconised as cdrom drives in windows. if you put an a autorun.inf on one of those, it will get executed without the user being questioned.</p> <p>regards morla</p>
31,817
<p>I would like to pass an argument(s) to a method being defined using define_method, how would I do that?</p>
<p>The block that you pass to define_method can include some parameters. That's how your defined method accepts arguments. When you define a method you're really just nicknaming the block and keeping a reference to it in the class. The parameters come with the block. So:</p> <pre><code>define_method(:say_hi) { |other| puts "Hi, " + other } </code></pre>
<p>With 2.2 you can now use keyword arguments: <a href="https://robots.thoughtbot.com/ruby-2-keyword-arguments" rel="noreferrer">https://robots.thoughtbot.com/ruby-2-keyword-arguments</a></p> <pre><code>define_method(:method) do |refresh: false| .......... end </code></pre>
11,514
<p>I am trying to load Linq on my .Net 3.5 enabled web server by adding the following to my .aspx page:</p> <pre><code>&lt;%@ Import Namespace="System.Query" %&gt; </code></pre> <p>However, this fails and tells me it cannot find the namespace.</p> <blockquote> <p>The type or namespace name 'Query' does not exist in the namespace 'System' </p> </blockquote> <p>I have also tried with no luck:</p> <ul> <li><code>System.Data.Linq</code></li> <li><code>System.Linq</code></li> <li><code>System.Xml.Linq</code></li> </ul> <p>I believe that .Net 3.5 is working because <code>var hello = "Hello World"</code> seems to work.</p> <p>Can anyone help please?</p> <p>PS: I just want to clarify that I don't use Visual Studio, I simply have a <a href="http://www.ultraedit.com/" rel="nofollow noreferrer">Text Editor</a> and write my code directly into .aspx files.</p>
<blockquote> <p>I have version 2 selected in IIS and I</p> </blockquote> <p>Well, surely that's your problem? Select 3.5.</p> <p>Actually, here's the real info:</p> <p><a href="http://www.hanselman.com/blog/HowToSetAnIISApplicationOrAppPoolToUseASPNET35RatherThan20.aspx" rel="noreferrer">http://www.hanselman.com/blog/HowToSetAnIISApplicationOrAppPoolToUseASPNET35RatherThan20.aspx</a></p>
<p>The <code>var hello</code> stuff is compiler magic and will work without Linq.</p> <p>Try adding a reference to <code>System.Core</code></p> <hr> <p>Sorry, I wasn't clear. I meant add <code>System.Core</code> to the web project's references, not to the page.</p> <p>The <code>Import</code> on the page are basically just using statements, allowing you to skip the namespace on the page.</p>
3,010
<p>Is it less efficient to use TEXT than varchar in an SQL database?</p> <p>If so why?</p> <p>If not why would you not just always use TEXT?</p> <p>I'm not targetting a specific database here but oracle is probably the most relevant, although I'm testing on MySQL for the time being as part of a proof of concept.</p>
<p>From Microsoft <a href="http://msdn.microsoft.com/en-us/library/ms187993.aspx" rel="nofollow noreferrer">here</a></p> <blockquote> <p>ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.</p> </blockquote> <p>When you use <code>varchar(max)</code> over text you can use it in the <code>WHERE</code> clause, because they work the same as their smaller counterparts, <code>varchar,nvarchar and varbinary</code>. Below is a small list of what should be used as opposed what was to be used:</p> <ul> <li>Use varchar(max) instead of text</li> <li>Use nvarchar(max) instead of ntext</li> <li>Use varbinary(max) instead of image</li> </ul>
<p>The short answer is: Yes, they are less efficient.</p> <p>The longer, more convoluted answer is:</p> <p>Yes, they are probably less efficient. It depends on which DBMS you are using and the size of your table, etc, etc. TEXT fields are variable width, and as such the DBMS has to do more work when trying to find records. How much this impacts on your performance is directly proportional to how efficient your DBMS is in general, how much data it stores about table rows, and whether it optimises fixed length tables.</p> <p>I know MySQL works faster with fixed length table rows, but you have to tell it that the table is able to be treated as a fixed length table first. I don't really have any practical experience with other DBMS's to be able to relate actual numbers. But on tables with lots (reads a million or more) of records, it can make a significant difference. Smaller tables will have little to no practical difference though.</p>
25,481
<p>say I have an asynchronous library, written in native C++, with an interface similar to this:</p> <pre><code>class connection { public: boost::signal&lt; void() &gt; sig_connection_made; boost::signal&lt; void(const std::string&amp;) &gt; sig_error; void connect(const std::string&amp; host, const std::string&amp; port); }; </code></pre> <p>that I want to wrap in C#. Does anyone know of a way, using SWIG or something similar, that will allow me to bind the signals to C# delegates?</p>
<p>I found this explanation: <code>http://www.astahost.com/info.php/max_allowed_packet-mysql_t2725.html</code></p> <blockquote> <p>It's safe to increase the value of this variable because the extra memory is allocated only when needed. For example, mysqld allocates more memory only when you issue a long query or when mysqld must return a large result row. The small default value of the variable is a precaution to catch incorrect packets between the client and server and also to ensure that you don't run out of memory by using large packets accidentally.</p> </blockquote> <p>Also note that I read you have to change the value for both the mysql client and the mysql server.</p>
<p>I suggest not touching this variable, instead adjusting your storage implementation to handle any size files using the default settings.</p> <p>Can you see <a href="http://www.dreamwerx.net/phpforum/?id=1" rel="nofollow noreferrer">here</a> for an example.</p>
37,770
<p>It appears that Directory.GetFiles() in C# modifies the Last access date of a file. I've googled for hours and can't seem to find a work around for this issue. Is there anyway to keep all the MAC (Modified, Accessed, Created) attributes of a file? I'm using Directory.GetDirectories(), Directory.GetFiles(), and FileInfo.</p> <p>Also, the fi.LastAccessTime is giving strange results -- the date is correct, however, the time is off by 2 minutes, or a few hours.</p> <pre><code>Time of function execution: 10/31/2008 8:35 AM Program Shows As Last Access Time 0_PDFIndex.html - 10/31/2008 8:17:24 AM AdvancedArithmetic.pdf - 10/31/2008 8:31:05 AM AdvancedControlStructures.pdf - 10/30/2008 1:18:00 PM AoAIX.pdf - 10/30/2008 1:18:00 PM AoATOC.pdf - 10/30/2008 12:29:51 PM AoATOC2.pdf - 10/30/2008 1:18:00 PM Actual Last Access Time 0_PDFIndex.html - 10/31/2008 8:17 AM AdvancedArithmetic.pdf - 10/30/2008 12:29 PM AdvancedControlStructures.pdf - 10/30/2008 12:29 PM AoAIX.pdf - 10/30/2008 12:29 PM AoATOC.pdf - 10/30/2008 12:29 PM AoATOC2.pdf - 10/30/2008 12:29 PM </code></pre> <p>Below is the method I'm using. If you require more information, please let me know.</p> <p>Thanks!</p> <pre><code>public void PopulateTreeView(string directoryValue, ref TreeNode parentNode) { string[] directoryArray = Directory.GetDirectories(directoryValue); string[] fileArray = Directory.GetFiles(directoryValue, "*.*", SearchOption.AllDirectories); try { #region Directories if (directoryArray.Length != 0) { foreach (string directory in directoryArray) { DirectoryInfo di = new DirectoryInfo(directory); TreeNode dirNode = parentNode.Nodes.Add(di.Name); FileNode fn = new FileNode(); fn.bIsDir = true; fn.dir = di; dirNode.Tag = fn; PopulateTreeView(directory, ref dirNode); Application.DoEvents(); } } #endregion #region Files if (fileArray.Length != 0) { foreach (string file in fileArray) { FileInfo fi = new FileInfo(file); TreeNode fileNode = parentNode.Nodes.Add(fi.Name); FileNode fn = new FileNode(); fn.bIsDir = false; fn.file = fi; fileNode.Tag = fn; fileNode.ImageIndex = 1; Console.WriteLine(fi.Name + " - " + fi.LastAccessTime); } } #endregion } catch (UnauthorizedAccessException) { parentNode.Nodes.Add("Access denied"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { Application.DoEvents(); } } </code></pre> <hr> <p>i know the differences between the attributes. What i need is for the file to remain exactly the same all attributes and meta-data, as if my program never touched the file; this includes the last access date.</p>
<p>I know this is far from ideal, but u can use fsutil (provided with Windows) to disable last access time writing:</p> <pre><code>fsutil behavior set disablelastaccess 1 </code></pre> <p>Presumably you'd set it back to 0 once done. You can invoke this using Process.Start from C#, but there must be a better programmatic way (calling into Windows API).</p> <pre><code>Process.Start("fsutil", "behavior set disablelastaccess 1").WaitForExit(); </code></pre> <p>Do note that this is a global Windows setting and would also affect disk access from outside your app...</p>
<p>Not sure if this is related or not, but from MSDN:</p> <blockquote> <p>When first called, FileSystemInfo calls Refresh and returns the cached information on APIs to get attributes and so on. On subsequent calls, you must call Refresh to get the latest copy of the information.</p> </blockquote> <p>BTW, "LastAccessTime" basically tells you the last time you "looked at" the file. In the absence of stale data, this would always be "now"... Not particularly useful, IMHO.</p>
31,593
<p>I want to find out all the subdomains of a given domain. I found a hint which tells me to dig the authoritative Nameserver with the following option:</p> <pre><code>dig @ns1.foo.example example.com axfr </code></pre> <p>But this never works. Has anyone a better idea/approach</p>
<p>The hint (using axfr) only works if the NS you're querying (<code>ns1.foo.example</code> in your example) is configured to allow AXFR requests from the IP you're using; this is unlikely, unless your IP is configured as a secondary for the domain in question.</p> <p>Basically, there's no easy way to do it if you're not allowed to use axfr. This is intentional, so the only way around it would be via brute force (i.e. <code>dig a.example.com</code>, <code>dig b.example.com</code>, ...), which I can't recommend, as it could be viewed as a denial of service attack.</p>
<p>If the DNS server is configured properly, you won't be able to get the entire domain. If for some reason is allows zone transfers from any host, you'll have to send it the correct packet to make that request. I suspect that's what the dig statement you included does.</p>
16,007
<p>I have a PHP file, Test.php, and it has two functions:</p> <pre><code>&lt;?php echo displayInfo(); echo displayDetails(); ?&gt; </code></pre> <p>JavaScript:</p> <pre><code>&lt;html&gt; ... &lt;script type="text/javascript"&gt; $.ajax({ type:'POST', url: 'display.php', data:'id='+id , success: function(data){ $("#response").html(data); } }); &lt;/script&gt; ... &lt;div id="response"&gt; &lt;/div&gt; &lt;/html&gt; </code></pre> <p>It returns the response from jQuery. The response shows as <code>&lt;a href=Another.php?&gt;Link&lt;/a&gt;</code>. When I click the Another.php link in <code>test.php</code>, it loads in another window. But I need it to load the same <code>&lt;div&gt; &lt;/div&gt;</code> area without changing the content of <code>test.php</code>, since it has <code>displayInfo(), displayDetails()</code>. Or is it possible to load a PHP page inside <code>&lt;div&gt; &lt;/div&gt;</code> elements?</p> <p>How can I tackle this problem?</p>
<p>If I understand correctly, you'd like for the <code>a</code> link to cancel navigation, but fire the AJAX function?</p> <p>In that case:</p> <pre><code>$("#mylink").click(function() { $.ajax({ type: "POST", url: "another.php", data: {id: "somedata"}, function(data) { $("#response").html(data); }); return false; }); </code></pre>
<p>You could just use <a href="http://en.wikipedia.org/wiki/MooTools" rel="nofollow noreferrer">MooTools</a> and class <a href="http://mootools.net/docs/Request/Request.HTML" rel="nofollow noreferrer">Request.HTML</a>.</p>
48,461
<p>I've almost completely installed Boost, but I have a problem with how to set my path to Boost in <em>Tools->options->projects->VC++ Directories</em>.</p> <p>I've written the path to include files and libraries (my folder contains two subfolders, <code>lib</code> and <code>include</code>), but when I try to use Boost with <code>#include boost/regex.hpp</code>, I got this linking error:</p> <pre><code>LINK : fatal error LNK1104: cannot open file 'libboost_regex-vc90-mt-gd-1_36.lib </code></pre> <p>Could you please tell me how to install Boost correctly for Visual Studio 2008?</p>
<p>Use the <a href="http://www.boostpro.com/download/" rel="nofollow noreferrer">Boost Installer</a> by the Boost consulting group.</p>
<p>You might be interested in the Visual Studio 2008 Feature pack. It adds many of the features that have only been available from Boost until now, the features that are part of the C++ TR1.</p>
31,958
<h3>Question</h3> <p>My question is how can you teach the methods and importance of tidying-up and refactoring code?</p> <h3>Background</h3> <p>I was recently working on a code review for a colleague. They had made some modifications to a long-gone colleagues work. During the new changes, my colleague had tried to refactor items but gave up as soon as they hit a crash or some other problem (rather than chasing the rabbit down the hole to find the root of the issue) and so reimplemented the problem code and built more on top of that. This left the code in a tangle of workarounds and magic numbers, so I sat down with them to go through refactoring it.</p> <p>I tried to explain how I was identifying the places we could refactor and how each refactoring can often highlight new areas. For example, there were two variables that stored the same information - why? I guessed it was a workaround for a bigger issue so I took out one variable and chased the rabbit down the hole, discovering other problems as we went. This eventually led to finding a problem where we were looping over the same things several times. This was due in no small part to the use of arrays of magic number sizes that obfuscated what was being done - fixing the initial "double-variable" problem led to this discovery (and others).</p> <p>As I went on this refactoring journey with my colleague, it was evident that she wasn't always able to grasp why we made certain changes and how we could be sure the new functionality matched the original, so I took the time to explain and prove each change by comparing with earlier versions and stepping through the changes on paper. I also explained, through examples, how to tell if a refactoring choice was a bad idea, when to choose comments instead of code changes, and how to select good variable names.</p> <p>I felt that the process of sitting together to do this was worthwhile for both myself (I got to learn a bit more about how best to explain things to others) and my colleague (they got to understand more of our code and our coding practices) but, the experience led me to wonder if there was a better way to teach the refactoring process.</p> <h3>...and finally...</h3> <p>I understand that what does or does not need refactoring, and how to refactor it are very subjective so I want to steer clear of that discussion, but I am interested to learn how others would tackle the challenge of teaching this important skill, and if others here have had similar experiences and what they learned from them (either as the teacher or the student).</p>
<p>Like most programming, refactoring skill comes with practice and experience. It would be nice to think it can be taught, but it has to be learned - and there is a significant difference in the amount of learning that can be accomplished in different environments.</p> <p>To answer your question, you can teach refactoring methods and good design in a pedagogical fashion, and that's fine. But, ultimately, you and I both know attaining a certain level is only through long hard experience.</p>
<p>Pair Programming seems to be the best way for me to get this across. This way, as we're working on real, production code, and we both encounter some code that doesn't smell right, we tackle a code refactoring together. The pair acts as the driver's conscience saying to do the right thing instead of the quick fix, and in turn, they both learn what good code looks like in the process.</p> <p>Refactoring can be an art, and just takes practice. The more you do it, the better you get at it. Keep studying the methods described in Martin Fowler's Ractoring book, and use your tools (Resharper for Visual Studio folk)</p>
28,558
<p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p> <ul> <li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li> <li>Divide it into groups based on some criteria</li> <li>Then later iterate over each of these groups separately.</li> </ul> <p>I've reviewed <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="noreferrer">the documentation</a>, but I've had trouble trying to apply them beyond a simple list of numbers.</p> <p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good &quot;prerequisite&quot; reading would also be appreciated.</p>
<p><strong>IMPORTANT NOTE:</strong> You have to <strong>sort your data</strong> first.</p> <hr /> <p>The part I didn't get is that in the example construction</p> <pre><code>groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) </code></pre> <p><code>k</code> is the current grouping key, and <code>g</code> is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the <code>groupby</code> iterator itself returns iterators.</p> <p>Here's an example of that, using clearer variable names:</p> <pre><code>from itertools import groupby things = [(&quot;animal&quot;, &quot;bear&quot;), (&quot;animal&quot;, &quot;duck&quot;), (&quot;plant&quot;, &quot;cactus&quot;), (&quot;vehicle&quot;, &quot;speed boat&quot;), (&quot;vehicle&quot;, &quot;school bus&quot;)] for key, group in groupby(things, lambda x: x[0]): for thing in group: print(&quot;A %s is a %s.&quot; % (thing[1], key)) print(&quot;&quot;) </code></pre> <p>This will give you the output:</p> <blockquote> <p>A bear is a animal.<br /> A duck is a animal.</p> <p>A cactus is a plant.</p> <p>A speed boat is a vehicle.<br /> A school bus is a vehicle.</p> </blockquote> <p>In this example, <code>things</code> is a list of tuples where the first item in each tuple is the group the second item belongs to.</p> <p>The <code>groupby()</code> function takes two arguments: (1) the data to group and (2) the function to group it with.</p> <p>Here, <code>lambda x: x[0]</code> tells <code>groupby()</code> to use the first item in each tuple as the grouping key.</p> <p>In the above <code>for</code> statement, <code>groupby</code> returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group.</p> <p>Here's a slightly different example with the same data, using a list comprehension:</p> <pre><code>for key, group in groupby(things, lambda x: x[0]): listOfThings = &quot; and &quot;.join([thing[1] for thing in group]) print(key + &quot;s: &quot; + listOfThings + &quot;.&quot;) </code></pre> <p>This will give you the output:</p> <blockquote> <p>animals: bear and duck.<br /> plants: cactus.<br /> vehicles: speed boat and school bus.</p> </blockquote>
<p>One useful example that I came across may be helpful:</p> <pre><code>from itertools import groupby #user input myinput = input() #creating empty list to store output myoutput = [] for k,g in groupby(myinput): myoutput.append((len(list(g)),int(k))) print(*myoutput) </code></pre> <p>Sample input: 14445221</p> <p>Sample output: (1,1) (3,4) (1,5) (2,2) (1,1)</p>
2,321
<p>I would like to know the best way to use a datagrid control linked to a combination (join) of data tables in a way that both simply allows both display, creation of new rows in underlying tables and deletion.</p> <p>The datagrid appears to offer the latter capabilities but I have not found a way that I am happy with to do more than just display on one grid and offer specific separate edit create and delete facilities.</p> <p>Suppose for the sake of illustration that the database contains:-</p> <p>Customer Table<br> * CustomerID<br> * CustomerName</p> <p>Order Table<br> * CustomerID<br> * OrderLineItem<br> * OrderLineQuanity</p> <p>And that I want to lose the CustomerID for display purposes but would like to be able to create new customers and delete existing ones, perhaps with a confirmatory dialog.</p>
<p>CSharpAtl is correct, use a Master-Detail control. An example of using one in a WinForm app is at <a href="http://msdn.microsoft.com/en-us/library/y8c0cxey.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/y8c0cxey.aspx</a>.</p> <p>WinForm DataGrids support add, edit, and delete of both Master and Detail records. As for your question about what happens if you change a Detail record so it matches a new Master; that is not possible. By design a Detail row only contains records that match the Master, you cannot (for example) change an order to belong to a new customer because the Detail row does not contain any customer information.</p> <p>If you want to move a Detail row to another Master, you have to create a new Detail row for the new Master, copy the data from the old Detail row, and delete the old Detail row. If you're ambitious you could support Cut and Paste or Drag and Drop of Detail rows, but internally you have to Create/Copy/Delete.</p>
<p>If the relationship is 1 to many you can go the route of using Master Detail. [link text][1]</p> <p>[1]: <a href="http://msdn.microsoft.com/en-us/library/aa479344.aspx/" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa479344.aspx/</a>"Master Detail"</p>
16,319
<p>LINQ simplifies database programming no doubt, but does it have a downside? Inline SQL requires one to communicate with the database in a certain way that opens the database to injections. Inline SQL must also be syntax-checked, have a plan built, and then executed, which takes precious cycles. Stored procedures have also been a rock-solid standard in great database application programming. Many programmers I know use a data layer that simplifies development, however, not to the extent LINQ does. Is it time to give up on the SP's and go LINQ? </p>
<p>LINQ to SQL actually presents some alarming performance problems in the database. Basically, it creates multiple execution plans based on the length of the parameter you are using. I posted about it a while back on my blog <a href="http://facility9.com/2008/08/28/linq-to-sql-may-cause-performance-problems/" rel="noreferrer">LINQ to SQL may cause performance problems</a>. </p> <p>Now, is that to say that LINQ doesn't have a place? Hardly. LINQ definitely has a place in the development toolkit, just like stored procedures. Ultimately, you want to use stored procedures when performance is absolutely necessary and use an ORM tool in any other situation.</p> <p>As far as inline SQL goes, there are ways to execute inline SQL so that the plan is only built once and is never recompiled. Most ORMs should take care of this aspect of performance tuning as well and using these methods is usually the safest way to execute your SQL since it forces you to use parameterized queries.</p> <p>Like most database solutions, the right answer depends on the problem you're trying to solve. If you favor development speed over database/application performance, then using LINQ or another DAL/ORM tool is the best way to go. If you favor performance over ease of development, then using stored procedures and pure datasets is going to be your best bet. LLBLGen even provides a LINQ to LLBLGen layer so you can use LINQ to query LLBLGen's objects and have LLBLGen actually handle building your queries and avoid some of the downfalls of LINQ.</p>
<p>It depends on what you're doing. LINQ is going to be less efficient at the actual data/set manipulation than a real database. But you'll save a lot in not having to connect to the database over a network.</p> <p>If your database is on the same machine or is formally 'well-connected', you're probably better off using it.</p> <p>But if you're getting back a large result set from a remote db that could mean significant transmission time, or if it's a really short query that won't justify the overhead, LINQ would likely be better.</p>
9,778
<p>Currently i am developing sites using DNN framework. Currently my development and staging environment is same. Client is vewing same site which I am using for development.</p> <p>I have started using tortoise svn (subversion) for maintaining versions and backup. I am using file based svn repository for it.</p> <p>The issue is svn creates .svn folder (hidden) in every folder. This folder and files inside it shows in portal system while file selection and at many different locations like FCKEditor File Browser, Icon selection for module / page, skins selection.</p> <p>I would like to hide this folder for entire application and it should not show up anywhere.</p>
<p>Do you have to have the same environment for development and staging? I would really recommend against it. Even if you have them on the same server, I think you should have them at least in separate virtual directories.</p> <p>Assuming you have then done that, it is simple to keep the '.' directories hidden, you simply <code>export</code> your svn repository from dev to staging. Staging will no longer be a working copy so the '.' directories will not be present. This also allows to test potentially breaking changes without affecting the client and it keeps the staging environment more stable.</p>
<p>You can hide the .svn folders in DNN but you'll have to modify the core. </p> <p>Probably an easier solution is to exclude the folder Portals/[PortalID] from your repository, but that depends on what you're developing. Do you need the Portal's files in your repository?</p>
13,893
<p>I'd like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I'm talking native C++ here, not managed C++, which has reflection. I realise C++ supplies some limited information using RTTI. Which additional libraries (or other techniques) could supply this information?</p>
<p>What you need to do is have the preprocessor generate reflection data about the fields. This data can be stored as nested classes. </p> <p>First, to make it easier and cleaner to write it in the preprocessor we will use typed expression. A typed expression is just an expression that puts the type in parenthesis. So instead of writing <code>int x</code> you will write <code>(int) x</code>. Here are some handy macros to help with typed expressions:</p> <pre><code>#define REM(...) __VA_ARGS__ #define EAT(...) // Retrieve the type #define TYPEOF(x) DETAIL_TYPEOF(DETAIL_TYPEOF_PROBE x,) #define DETAIL_TYPEOF(...) DETAIL_TYPEOF_HEAD(__VA_ARGS__) #define DETAIL_TYPEOF_HEAD(x, ...) REM x #define DETAIL_TYPEOF_PROBE(...) (__VA_ARGS__), // Strip off the type #define STRIP(x) EAT x // Show the type without parenthesis #define PAIR(x) REM x </code></pre> <p>Next, we define a <code>REFLECTABLE</code> macro to generate the data about each field(plus the field itself). This macro will be called like this:</p> <pre><code>REFLECTABLE ( (const char *) name, (int) age ) </code></pre> <p>So using <a href="http://www.boost.org/doc/libs/1_49_0/libs/preprocessor/doc/index.html" rel="noreferrer">Boost.PP</a> we iterate over each argument and generate the data like this:</p> <pre><code>// A helper metafunction for adding const to a type template&lt;class M, class T&gt; struct make_const { typedef T type; }; template&lt;class M, class T&gt; struct make_const&lt;const M, T&gt; { typedef typename boost::add_const&lt;T&gt;::type type; }; #define REFLECTABLE(...) \ static const int fields_n = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__); \ friend struct reflector; \ template&lt;int N, class Self&gt; \ struct field_data {}; \ BOOST_PP_SEQ_FOR_EACH_I(REFLECT_EACH, data, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) #define REFLECT_EACH(r, data, i, x) \ PAIR(x); \ template&lt;class Self&gt; \ struct field_data&lt;i, Self&gt; \ { \ Self &amp; self; \ field_data(Self &amp; self) : self(self) {} \ \ typename make_const&lt;Self, TYPEOF(x)&gt;::type &amp; get() \ { \ return self.STRIP(x); \ }\ typename boost::add_const&lt;TYPEOF(x)&gt;::type &amp; get() const \ { \ return self.STRIP(x); \ }\ const char * name() const \ {\ return BOOST_PP_STRINGIZE(STRIP(x)); \ } \ }; \ </code></pre> <p>What this does is generate a constant <code>fields_n</code> that is number of reflectable fields in the class. Then it specializes the <code>field_data</code> for each field. It also friends the <code>reflector</code> class, this is so it can access the fields even when they are private:</p> <pre><code>struct reflector { //Get field_data at index N template&lt;int N, class T&gt; static typename T::template field_data&lt;N, T&gt; get_field_data(T&amp; x) { return typename T::template field_data&lt;N, T&gt;(x); } // Get the number of fields template&lt;class T&gt; struct fields { static const int n = T::fields_n; }; }; </code></pre> <p>Now to iterate over the fields we use the visitor pattern. We create an MPL range from 0 to the number of fields, and access the field data at that index. Then it passes the field data on to the user-provided visitor:</p> <pre><code>struct field_visitor { template&lt;class C, class Visitor, class I&gt; void operator()(C&amp; c, Visitor v, I) { v(reflector::get_field_data&lt;I::value&gt;(c)); } }; template&lt;class C, class Visitor&gt; void visit_each(C &amp; c, Visitor v) { typedef boost::mpl::range_c&lt;int,0,reflector::fields&lt;C&gt;::n&gt; range; boost::mpl::for_each&lt;range&gt;(boost::bind&lt;void&gt;(field_visitor(), boost::ref(c), v, _1)); } </code></pre> <p>Now for the moment of truth we put it all together. Here is how we can define a <code>Person</code> class that is reflectable:</p> <pre><code>struct Person { Person(const char *name, int age) : name(name), age(age) { } private: REFLECTABLE ( (const char *) name, (int) age ) }; </code></pre> <p>Here is a generalized <code>print_fields</code> function using the reflection data to iterate over the fields:</p> <pre><code>struct print_visitor { template&lt;class FieldData&gt; void operator()(FieldData f) { std::cout &lt;&lt; f.name() &lt;&lt; "=" &lt;&lt; f.get() &lt;&lt; std::endl; } }; template&lt;class T&gt; void print_fields(T &amp; x) { visit_each(x, print_visitor()); } </code></pre> <p>An example of using the <code>print_fields</code> with the reflectable <code>Person</code> class:</p> <pre><code>int main() { Person p("Tom", 82); print_fields(p); return 0; } </code></pre> <p>Which outputs:</p> <pre><code>name=Tom age=82 </code></pre> <p>And voila, we have just implemented reflection in C++, in under 100 lines of code. </p>
<p>If you declare a pointer to a function like this:</p> <pre><code>int (*func)(int a, int b); </code></pre> <p>You can assign a place in memory to that function like this (requires <code>libdl</code> and <code>dlopen</code>)</p> <pre><code>#include &lt;dlfcn.h&gt; int main(void) { void *handle; char *func_name = "bla_bla_bla"; handle = dlopen("foo.so", RTLD_LAZY); *(void **)(&amp;func) = dlsym(handle, func_name); return func(1,2); } </code></pre> <p>To load a local symbol using indirection, you can use <code>dlopen</code> on the calling binary (<code>argv[0]</code>).</p> <p>The only requirement for this (other than <code>dlopen()</code>, <code>libdl</code>, and <code>dlfcn.h</code>) is knowing the arguments and type of the function.</p>
6,275
<pre><code>class Child { private override void Check_CheckedChanged(object sender, EventArgs e) { if (Check.Checked) { this.addName(this.FirstName); this.disableControls(); } else { this.addAddress(this.address); //this.activatecontrols();// gives error since it's private method in parent. } } } class Parent { private void Check_CheckedChanged(object sender, EventArgs e) { if (Check.Checked) { this.disablecontrols(); } else { this.addAddress(this.address); this.activatecontrols(); } } } </code></pre> <p>I want to fire the the child event if it satisfies if condition. But if can not I need to call the base's else condition as I activatecontrols() is private in Parent. So, how do I call the event? </p>
<p>A very simple solution would be to make the ActivateControls protected virtual on Parent and override it on the child, then you can call base.activatecontrols in the child method if not Check.Checked.</p>
<p>A very simple solution would be to make the ActivateControls protected virtual on Parent and override it on the child, then you can call base.activatecontrols in the child method if not Check.Checked.</p>
45,758
<p>I would like to know if I can install say Visual Studio 2008 Pro and Visual Studio 2008 standard on the same machine. I have tried to install the pro (trial edition available on MSDN) after the express, and it seems to require them to be installed in the same directory. Is this specific to the express edition ?</p> <p>The reason why I am asking this is to support automatic detection of VS compilers on a given machine for a build tool (scons), and I am not so familiar with non express versions of VS. IOW, I don't want to run them side by side, I only need to know if I should handle side by side installation in my detection scheme.</p>
<p>I wouldn't recommend installing multiple editions of the same version side-by-side. I can imagine it playing havoc with the registry. If you just need to have all the different editions available for testing, I'd use VMs.</p> <p>You can, however, install multiple editions (e.g. 2003, 2005 and 2008) side-by-side.</p>
<p>I know I have installed the express version and the professional version on the same machine.</p> <p>You could also use <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=04D26402-3199-48A3-AFA2-2DC0B40A73B6&amp;displaylang=en" rel="nofollow noreferrer">Microsoft Virtual PC</a> and install other versions on virtual machines.</p>
28,854
<p>If the amount of data stored within a given field of a database is unknown, and could be very large, should I store it in an external file rather than within a field in the database?</p>
<p>You should choose a database management system which has the capability to handle large data efficiently. The database system might store it within the database file or in an external file linked to from within the database. SQL Server 2008 can do both, transparently; not sure what other systems offer.</p>
<p>It depends on your task. There are pluses and minuses of storing large data on the FS instead of the DB. As for the size, you can limit it in the field definition of most databases.</p>
23,853
<p>I'd be interested in some before-and-after c# examples, some non-idiomatic vs idiomatic examples. Non-c# examples would be fine as well if they get the idea across. Thanks.</p>
<p>Idiomatic means following the conventions of the language. You want to find the easiest and most common ways of accomplishing a task rather than porting your knowledge from a different language.</p> <p>non-idiomatic python using a loop with append:</p> <pre><code>mylist = [1, 2, 3, 4] newlist = [] for i in mylist: newlist.append(i * 2) </code></pre> <p>idiomatic python using a list comprehension:</p> <pre><code>mylist = [1, 2, 3, 4] newlist = [(i * 2) for i in mylist] </code></pre>
<p>Practically speaking, it means writing code in a consistent way, i.e. all developers who work on your code base should follow the same conventions when writing similar code constructs.</p> <p>So the idiomatic way is the way that matches the style of the other code, non-idiomatic way means you are writing the kind of function but in a different way.</p> <p>e.g. if you are looping a certain number of items, you could write the loop in several ways:</p> <pre><code>for (int i = 0; i &lt; itemCount; i++) for (int i = 1; i &lt;= itemCount; i++) for (int i = 0; i &lt; itemCount; ++i) </code></pre> <p>etc</p> <p>What is most important is that the chosen style is used consistently. That way people become very familiar and confident with how to use it, and when you spy a usage which looks different it can be a sign of a mistake being introduced, perhaps an off by one error, e.g.</p> <pre><code>for (int i = 1; i &lt; itemCount; i++) </code></pre>
10,962
<p>I set up 404 handler page in web.config, but it works ONLY when extension of URL is .aspx (or other which is handled by ASP.NET). I know I can setup static HTML page in website options, but I want to have a page. Is there any options to assign ASPX handler page for all request extensions in IIS?</p>
<p>The direct question was whether or not there are options to assign the ASPX handler to all request extensions: Yes, there is. I'll discuss how to do that shortly.</p> <p>First, I think the "hidden" question -- the answer you really want -- is whether or not there's a way to redirect all 404 errors for pages other than ASPX, ASMX, etc. Yes, there is, and this is the <strong>better</strong> choice if it'll solve the issue you're having.</p> <p>To redirect all 404s in IIS 6, right click your web application root (whether it be its own site or a virtual directory in the main site), and choose "Properties." From there, choose the "Custom Errors" tab. Find 404 in the list and change it to the redirect you want.</p> <p>Now, if that won't suffice -- and I really hope it does -- yes, you can run every page through the ASPX handler. However, doing so comes at a fairly high cost in terms of efficiency -- raw HTML/image serving is considerably faster than anything dynamic.</p> <p>To do this, right click your web application root and choose "Properties." Choose the "Home Directory" tab. Click "Configuration;" a new window will pop up. Copy the path from one of the ASP.NET page serves, and then use it for a wildcard application map.</p> <p>Bear in mind, again, this is the <strong>wrong answer</strong> most of the time. It will negatively impact your performance, and is the equivalent of using a chainsaw to carve a turkey. I highly recommend the first option over this one, if it will work out for you.</p>
<ol> <li><p>You can setup wild card mapping in IIS (Application configuration/Mappings/Wildcard mappings/ - just set aspnet_isapi.dll as executable and uncheck the Verify that file exists box) that will route all incoming requests to your app - so you can control the behavior directly from it.</p></li> <li><p>You don't have to setup static page in your IIS application settings. Imho, you should be able to setup valid url (e.g. /error_handler.aspx) from your app that will be used as landing page in case of specific server error.</p></li> </ol>
16,126
<p>There are all sorts of advantages to using Emacs, but for someone comfortable with the usual Win32 applications it comes with a wall-like learning curve. With most other editors it’s possible to just start using them and then learn about their other features and enhancements as you go along. </p> <p>How to just get on with using Emacs straight away, with the aim of reaching that point where you actually prefer to use Emacs over other editors or applications?</p> <p>Edit - To try and clarify the question: I’ve done the tutorial, read some docs, etc. then soon after when I’ve wanted to quickly edit some text it’s been easier to just use another editor, that I already know. What do I need to do so that not only I don’t just go for another easier editor, but that I actually prefer to use Emacs, and how to get here as quickly as possible? What if any are the training wheels for Emacs?</p>
<p>The biggest thing about learning how to use <a href="http://en.wikipedia.org/wiki/Emacs" rel="noreferrer">Emacs</a> is ... (drumroll please) learning how to use Emacs.</p> <p>Okay, okay, okay. It's a silly answer, and it's a tautology, but it's true. If you start up Emacs, and think to yourself "How could I find every instance of the word 'foobar' in my source tree?" the worst thing you could do is hit <kbd>Alt</kbd> + <kbd>Tab</kbd> and visit Google.</p> <p>Seriously.</p> <p>Learning the help system and how it works is the best thing you can do. It's so nice to just hit C-h a find, and suddenly get all the information you need, right at your fingertips.</p> <p>The next best thing you could do is install a wonderful little package called <a href="http://www.emacswiki.org/emacs/Icicles" rel="noreferrer">Icicles</a> which has some seriously groovy completion functions. After you get it installed, just know that anytime the minibuffer is asking for some kind of input, you can now use regular expressions.</p> <p>How would this apply to finding every file in your source tree? Well, you'd hit M-x, and then type "find". After that, you could hit (for instance) <kbd>Shift</kbd> + <kbd>Tab</kbd> and Icicles would kick in, finding every command that prefixes with "find". Alternatively, you could do M-x .<em>find.</em> and it would give you any command with find in it.</p> <p>Build a cheat sheet. Just keep a saved buffer somewhere that has all of the keyboard shortcuts you use frequently in it. Remove the ones that you know off by heart, and pick up new ones. In most cases when you do a M-x command, the message buffer will tell you what the keyboard shortcut was for that command (if there was one).</p> <p>Learn. Keyboard. Macros.</p> <p>Learn. Emacs. <a href="http://en.wikipedia.org/wiki/Lisp_%28programming_language%29" rel="noreferrer">Lisp</a>.</p> <p>Steven Huwig's idea of using some killer applications is a good one. Emacs is easier to use when you want to use it. For me, it was Planner Mode. (I've just moved to <a href="https://en.wikipedia.org/wiki/Org-mode" rel="noreferrer">Org-mode</a>, and it's even better.)</p>
<p>My advice is:</p> <ul> <li>Learn the very basics (how to type, save a document, turn on syntax highlighting, maybe copy and paste). You can look up how to do these online (google "emacs tutorial" maybe)</li> <li>Start using it.</li> </ul> <p>Whenever you wish you knew how to do something, then look up how to do it. You might have to look the same thing up 3-4 times before you get it, but then you will learn it.</p> <p>Keep doing this. It'll be annoying at first, but then you'll get used to it, and then you might even enjoy using it! </p> <p>(DISCLAIMER: Personally I just use another editor).</p>
33,906
<p>I have heard the 'shard' technique mentioned several times with regard to solving scaling problems for large websites. What is this 'shard' technique and why is it so good?</p>
<p>Karl Seguin has a <a href="http://codebetter.com/blogs/karlseguin/archive/2008/06/30/scale-cheaply-sharding.aspx" rel="nofollow noreferrer">good blog</a> post about sharding.</p> <p>From the post:</p> <blockquote> <p>Sharding is the separation of your data across multiple servers. How you separate your data is up to you, but generally it’s done on some fundamental identifier.</p> </blockquote>
<p>In brief, imagine seperating your users_tbl across several servers. So Users 1-5000 and on Server 1, Users 5000-10000 on Server 2; etc. If your data model is sufficiently abstract in code, it's often not a huge change in code. </p> <p>Of course this approach becomes difficult if all your queries are similar to "SELECT COUNT(*) FROM users_tbl GROUP BY userType" but when your where is "WHERE userid = 5" then it makes more sense.</p>
11,713
<p>I want to programmatically edit file content using windows command line (<a href="http://en.wikipedia.org/wiki/Windows_command_line" rel="noreferrer">cmd.exe</a>). In *nix there is <a href="http://en.wikipedia.org/wiki/Sed" rel="noreferrer">sed</a> for this tasks. Is there any useful native equivalent in windows?</p>
<p>Today powershell saved me.</p> <p>For <code>grep</code> there is:</p> <pre><code>get-content somefile.txt | where { $_ -match &quot;expression&quot;} </code></pre> <p>or</p> <pre><code>select-string somefile.txt -pattern &quot;expression&quot; </code></pre> <p>and for <code>sed</code> there is:</p> <pre><code>get-content somefile.txt | %{$_ -replace &quot;expression&quot;,&quot;replace&quot;} </code></pre> <p>For more detail about replace PowerShell function see <a href="https://devblogs.microsoft.com/scripting/use-powershell-to-replace-text-in-strings/" rel="noreferrer">this Microsoft article</a>.</p>
<p>I needed a sed tool that worked for the Windows cmd.exe prompt. <a href="http://www.pement.org/sed/" rel="nofollow">Eric Pement's port of <strong>sed</strong> to a single DOS .exe</a> worked great for me.</p> <p>It's pretty well <a href="http://www.pement.org/sed/sedfaq.html" rel="nofollow">documented</a>.</p>
15,493
<p>How are callbacks written in PHP?</p>
<p>The manual uses the terms "callback" and "callable" interchangeably, however, "callback" traditionally refers to a string or array value that acts like a <a href="http://en.wikipedia.org/wiki/Function_pointer" rel="noreferrer">function pointer</a>, referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are:</p> <pre><code>$cb1 = 'someGlobalFunction'; $cb2 = ['ClassName', 'someStaticMethod']; $cb3 = [$object, 'somePublicMethod']; // this syntax is callable since PHP 5.2.3 but a string containing it // cannot be called directly $cb2 = 'ClassName::someStaticMethod'; $cb2(); // fatal error // legacy syntax for PHP 4 $cb3 = array(&amp;$object, 'somePublicMethod'); </code></pre> <p>This is a safe way to use callable values in general:</p> <pre><code>if (is_callable($cb2)) { // Autoloading will be invoked to load the class "ClassName" if it's not // yet defined, and PHP will check that the class has a method // "someStaticMethod". Note that is_callable() will NOT verify that the // method can safely be executed in static context. $returnValue = call_user_func($cb2, $arg1, $arg2); } </code></pre> <p>Modern PHP versions allow the first three formats above to be invoked directly as <code>$cb()</code>. <code>call_user_func</code> and <code>call_user_func_array</code> support all the above.</p> <p>See: <a href="http://php.net/manual/en/language.types.callable.php" rel="noreferrer">http://php.net/manual/en/language.types.callable.php</a></p> <p>Notes/Caveats: </p> <ol> <li>If the function/class is namespaced, the string must contain the fully-qualified name. E.g. <code>['Vendor\Package\Foo', 'method']</code></li> <li><code>call_user_func</code> does not support passing non-objects by reference, so you can either use <code>call_user_func_array</code> or, in later PHP versions, save the callback to a var and use the direct syntax: <code>$cb()</code>;</li> <li>Objects with an <a href="http://us2.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.invoke" rel="noreferrer"><code>__invoke()</code></a> method (including anonymous functions) fall under the category "callable" and can be used the same way, but I personally don't associate these with the legacy "callback" term.</li> <li>The legacy <code>create_function()</code> creates a global function and returns its name. It's a wrapper for <code>eval()</code> and anonymous functions should be used instead.</li> </ol>
<p>I cringe every time I use <code>create_function()</code> in php. </p> <p>Parameters are a coma separated string, the whole function body in a string... Argh... I think they could not have made it uglier even if they tried.</p> <p>Unfortunately, it is the only choice when creating a named function is not worth the trouble.</p>
7,139
<p>I want to be able to get an estimate of how much code &amp; static data is used by my C++ program?</p> <p>Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime?</p> <p>Will objdump &amp; readelf help?</p>
<p>"size" is the traditional tool. "readelf" has a lot of options.</p> <pre><code>$ size /bin/sh text data bss dec hex filename 712739 37524 21832 772095 bc7ff /bin/sh </code></pre>
<p><code>readelf</code> will indeed help. You can use the <code>-S</code> option; that will show the sizes of all sections. <code>.text</code> is (the bulk of) your executable code. <code>.data</code> and <code>.rodata</code> is your static data. There are other sections too, some of which are used at runtime, others only at link time.</p>
5,596
<p>I'm building some functional tests for a web site using Selenium, and I'm stuck on a bizarre browser issue where the page never seems to finish loading. The status bar reads either "Transferring data from..." or "Read...".</p> <p>Since the page never finishes loading, my selenium tests timeout.</p> <p><em>The issue only seems to happen on FireFox.</em> Our tests rely on FireFox *chrome to test file-uploads, so FireFox is crucial to our testing strategy.</p> <p>I've checked both FireBug and Fiddler, but I don't see any incomplete long-running requests. All requests complete with normal response codes (no 404 errors).</p> <p>What should I look at to address this issue? </p> <ul> <li>Doctype?</li> <li>Invalid Markup?</li> <li>Low level FireFox setting?</li> <li>Registry Hack?</li> <li>IIS setting?</li> </ul> <p>Although fixing the issue for the planet would be awesome, I only really need to fix the issue for my tests.</p> <p>If it helps, it's a .NET 3.5 solution built on MOSS and we're using Flash with sifr. Our markup is legacy (and it's a MOSS site) so it's a bit rough on the edges.</p>
<p>Hate to answer my own question, but the problem went away on its own after developers started to strip out invalid markup, unclosed tables or TR's without tables are generally bad.</p>
<p>Try the <a href="http://livehttpheaders.mozdev.org/" rel="nofollow noreferrer">Live HTTP Headers</a> extension. With this extension you can grab the request and response headers off the wire. You might also try starting Firefox in safe mode for testing. This will disable all installed extensions. Run firefox -h in a dos box to see the command line switch for safe mode.</p>
39,126
<p>I have a set of WCF web services connected to dynamically by a desktop application.</p> <p>My problem is the really detailed config settings that WCF requires to work. Getting SSL to work involves custom settings. Getting MTOM or anything else to work requires more. You want compression? Here we go again...</p> <p>WCF is really powerful - you can use a host of different ways to connect, but all seem to involve lots of detailed config. If host and client don't match perfectly you get hard to decipher errors.</p> <p>I want to make the desktop app far easier to configure - ideally some kind of auto-discovery. The users of the desktop app should just be able to enter the URL and it do the rest.</p> <p>Does anyone know a good way to do this?</p> <p>I know Visual Studio can set the config up for you, but I want the desktop app to be able to do it based on a wide variety of different server set-ups.</p> <p>I know that VS's tools can be used externally, but I'm looking for users of the desktop apps to not have to be WCF experts. I know MS made this intentionally over complicated.</p> <p>Is there any way, mechanism, 3rd party library or anything to make auto-discovery of WCF settings possible?</p>
<p>All information about the endpoint is available in metadata of a service, you can write a client what will explore the meta data of the service and will configure the client. For a code example you can look into this excellent <a href="http://www.idesign.net/idesign/DesktopDefault.aspx?tabindex=-1&amp;tabid=19&amp;download=158" rel="nofollow noreferrer">Mex Explorer</a> from Juval Lowy.</p>
<p>Thanks, that was useful code (+1).</p> <p>It's more than a little bit messy though, has some bugs (case sensitive checks that shouldn't be, for instance), has a load of UI functionality that I don't need and repeats a lot of code.</p> <p>I've taken from it the actual discovery mechanism, re-wrote it and almost got it working (connects, but needs some finessing).</p> <p>First some util functions used by the main method:</p> <pre><code>/// &lt;summary&gt;If the url doesn't end with a WSDL query string append it&lt;/summary&gt; static string AddWsdlQueryStringIfMissing( string input ) { return input.EndsWith( "?wsdl", StringComparison.OrdinalIgnoreCase ) ? input : input + "?wsdl"; } /// &lt;summary&gt;Imports the meta data from the specified location&lt;/summary&gt; static ServiceEndpointCollection GetEndpoints( BindingElement bindingElement, Uri address, MetadataExchangeClientMode mode ) { CustomBinding binding = new CustomBinding( bindingElement ); MetadataSet metadata = new MetadataExchangeClient( binding ).GetMetadata( address, mode ); return new WsdlImporter( metadata ).ImportAllEndpoints(); } </code></pre> <p>Then a method that tries different way to connect and returns the endpoints:</p> <pre><code>public static ServiceEndpointCollection Discover( string url ) { Uri address = new Uri( url ); ServiceEndpointCollection endpoints = null; if ( string.Equals( address.Scheme, "http", StringComparison.OrdinalIgnoreCase ) ) { var httpBindingElement = new HttpTransportBindingElement(); //Try the HTTP MEX Endpoint try { endpoints = GetEndpoints( httpBindingElement, address, MetadataExchangeClientMode.MetadataExchange ); } catch { } //Try over HTTP-GET if ( endpoints == null ) endpoints = GetEndpoints( httpBindingElement, new Uri( AddWsdlQueryStringIfMissing( url ) ), MetadataExchangeClientMode.HttpGet ); } else if ( string.Equals( address.Scheme, "https", StringComparison.OrdinalIgnoreCase ) ) { var httpsBindingElement = new HttpsTransportBindingElement(); //Try the HTTPS MEX Endpoint try { endpoints = GetEndpoints( httpsBindingElement, address, MetadataExchangeClientMode.MetadataExchange ); } catch { } //Try over HTTP-GET if ( endpoints == null ) endpoints = GetEndpoints( httpsBindingElement, new Uri( AddWsdlQueryStringIfMissing( url ) ), MetadataExchangeClientMode.HttpGet ); } else if ( string.Equals( address.Scheme, "net.tcp", StringComparison.OrdinalIgnoreCase ) ) endpoints = GetEndpoints( new TcpTransportBindingElement(), address, MetadataExchangeClientMode.MetadataExchange ); else if ( string.Equals( address.Scheme, "net.pipe", StringComparison.OrdinalIgnoreCase ) ) endpoints = GetEndpoints( new NamedPipeTransportBindingElement(), address, MetadataExchangeClientMode.MetadataExchange ); return endpoints; } </code></pre>
11,311
<p>Being a application developer, do I need to know Unicode?</p>
<p>Unicode is a standard that defines numeric codes for glyphs used in written communication. Or, as they say it themselves:</p> <blockquote> <p>The standard for digital representation of the characters used in writing all of the world's languages. Unicode provides a uniform means for storing, searching, and interchanging text in any language. It is used by all modern computers and is the foundation for processing text on the Internet. Unicode is developed and maintained by the Unicode Consortium.</p> </blockquote> <p>There are many common, yet easily avoided, programming errors committed by developers who don't bother to educate themselves about Unicode and its encodings.</p> <ul> <li>First, go to <a href="http://www.unicode.org/" rel="noreferrer">the source</a> for authoritative, detailed information and implementation guidelines.</li> <li>As mentioned by others, Joel Spolsky has <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="noreferrer">a good list</a> of these errors.</li> <li>I also like Elliotte Rusty Harold's <a href="http://cafe.elharo.com/programming/the-ten-commandments-of-unicode/" rel="noreferrer">Ten Commandments of Unicode</a>.</li> <li>Developers should also watch out for <a href="http://www.owasp.org/index.php/Canonicalization,_locale_and_Unicode" rel="noreferrer">canonical representation</a> attacks.</li> </ul> <p>Some of the key concepts you should be aware of are:</p> <ul> <li><a href="http://www.unicode.org/glossary/#glyph" rel="noreferrer">Glyphs</a>&mdash;concrete graphics used to represent written characters.</li> <li><a href="http://www.unicode.org/versions/Unicode5.0.0/ch03.pdf#G729" rel="noreferrer">Composition</a>&mdash;combining glyphs to create another glyph.</li> <li><a href="http://en.wikipedia.org/wiki/Character_encoding" rel="noreferrer">Encoding</a>&mdash;converting Unicode points to a stream of bytes.</li> <li><a href="http://www.unicode.org/reports/tr10/" rel="noreferrer">Collation</a>&mdash;locale-sensitive comparison of Unicode strings.</li> </ul>
<p>Unicode is a standard that enumerates characters, and gives them unique numeric IDs (called "code points"). It includes a very large, and growing, set of characters for most modern written languages, and also a lot of exotic things like ancient Greek musical notation.</p> <p>Unlike other character encoding schemes (like ASCII or the ISO-8859 standards), Unicode does not say anything about representing these characters in bytes; it just gives a universal set of IDs to characters. So it is wrong to say that Unicode is "a 16-bit replacement for ASCII".</p> <p>There are various encoding schemes that can representing arbitrary Unicode characters in bytes, including UTF-8, UTF-16, and others.</p>
27,435
<p>I have a client who had to rebuild his automated build server. He checked out his project folder from my subversion server but is now no longer able to commit - he gets this error:</p> <pre><code>Error: Commit failed (details follow): Error: Cannot write to the prototype revision file of transaction '551-1' because a Error: previous representation is currently being written by another process Finished!: </code></pre> <p>I have searched Google but although this error has been often reported there is no clear explanation - does anyone on StackOverflow have a solution?</p> <p>UPDATE: Nobody else commits to that repository, so it was not a transaction stuck (at least not from another user). In the end we found that permissions were not set correctly. Not that you would know it from this message, but that fixed the problem.</p>
<p>You can clear this error w/out a reboot:</p> <ol> <li><p>Identify (or create) a directory in the root SVN repository that was not a part of the failed commit.</p></li> <li><p>Create a new file in the directory from step 1.</p></li> <li><p>Commit the new file (and directory if created in step 1). Because the file is new, it doesn't conflict w/the previous commit and can update the revision # on the server. </p></li> <li><p>Commit the original files/directories.</p></li> <li><p>Delete the new file (and directory if created in step 1).</p></li> <li><p>Commit the entire tree.</p></li> </ol> <p>**Steps 5 &amp; 6 aren't required, but I like to keep my repository tidy... </p> <p>I get this error a lot b/c SVN frequently conks out in the middle of committing my large files, which in turn causes subsequent commits to try to write to the revision that was interrupted.</p>
<p>Mount Point for SubVersion repository was full in our case, adding more space.</p>
44,042
<p>I am planning a mechanical 40% keyboard build and are coincidentally on the home stretch of a homemade CNC project.</p> <p>The only thing the CNC needs to do for the keyboard project is to drill 7*48 holes. So what I need to do now is layout those holes in SVG. Therein lies the question. What resolution should I use for the SVG? I want to space the center of the keyboard switches 19 mm apart. An online pixel to mm converter suggested that 72 pixels is exactly 19.05 mm (which actually is what Cherry MX says should be their spacing).</p> <p>Now, I do understand that this really doesn't matter, but I am curious as I am new on CNCs and was suspecting that there is a number that will "just work". </p> <p>EDIT: For example, if I where to print the template (SVG) on a regular printer, what pixel to mm ratio should I use so that it would come out the size I want?</p>
<p><strike>I found one of those printer things that puts ink on dead trees and tested to print a simple SVG file.</p> <pre><code>&lt;svg xmlns="http://www.w3.org/2000/svg" width="400px" height="800px"&gt; &lt;rect x="10" y="10" width="72" height="72" fill="#999999" /&gt; &lt;rect x="10" y="100" width="378" height="378" fill="#999999" /&gt; &lt;/svg&gt; </code></pre> <p>As I suspected 72 pixels came out pretty much exactly 19mm. (72/19.05)*100~=378 came out 100mm.</p> <p>Given this I am going to assume that 72/19.05 is the de facto best pixel to mm ratio to use for CNC projects.</strike></p> <p>EDIT:</p> <p>Found this documentation: <a href="http://w3.org/TR/SVG/coords.html#Units" rel="noreferrer">http://w3.org/TR/SVG/coords.html#Units</a></p> <pre><code>&lt;svg xmlns="http://www.w3.org/2000/svg" width="400px" height="800px"&gt; &lt;rect x="10" y="10" width="19.05mm" height="19.05mm" fill="#999999" /&gt; &lt;rect x="10" y="100" width="100mm" height="100mm" fill="#999999" /&gt; &lt;/svg&gt; </code></pre> <p>Much simpler to use mm as units right away </p>
<p>SVG is a vector-graphics format, there's no particular reason it can't scale arbitrarily. Presumably the CNC software will allow you to select the scale of a pixel? If so, pick a scale that makes the math work out easily (so some integer number of pixels per millimeter). If not, it's probably documented somewhere for the specific tool you're using.</p>
446
<p>I'm printing a model on my Ender 3 in Mika3D Silk PLA, which (just for reference, this is not atypical) has a stated temperature of 200&nbsp;&deg;C to 235&nbsp;&deg;C. I have used this filament before and found it works best for me around 200&nbsp;&deg;C, but was not the case with this print, and I'm wondering what else I can do to fix this issue.</p> <p>I have retractions enabled, have lowered the printing temperature to 180&nbsp;&deg;C and decreased the feed rate significantly, to around 75&nbsp;%. Both of these adjustments happened gradually, making sure there was no change in stringing between adjustments.</p> <p>I do have rafts and Z hops enabled in Cura, as previous prints of this model were knocked off the base even after leveling the bed properly, and almost every time a "hop" is performed, some stringing occurs. Is there something I can do in my settings, etc, to fix this issue?</p> <p>Here is an image of the problem. <img src="https://i.stack.imgur.com/KB59T.jpg" alt="Image of print with stringing"></p> <p>Edit: did some extra research and <em>increased</em> my print speed and switched to a better testing model - same issue.</p>
<p>Stringing may depend on sub-optimal retraction settings: when retraction is fast and high enough, the string may be cut and disappear.</p> <p>You may want to at least try to optimise retraction, at least to exclude that parameter.</p> <p>There is a tool designed to properly tune retraction: <a href="http://retractioncalibration.com/" rel="nofollow noreferrer">http://retractioncalibration.com/</a></p> <p>What it does is print a tower with multiple retractions with increasing retraction distance around the perimeter. Along the Z axis the retraction speed is increased. This tool does not include Z-hopping so stringing may be less visible, but at least you can easily visualise the optimal retraction settings. At that point if the optimal settings are much different from what you had, you may want to try your model again to see if it improved.</p> <p><a href="https://i.stack.imgur.com/HVbns.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HVbns.jpg" alt="enter image description here" /></a></p>
<p>It's because the nozzle has nowhere to wipe itself, like when you don't use Z hop the nozzle wipes itself off in the inside of the print. When you have Z hop enabled the nozzle has nowhere to wipe the string off, which leaves a string when it goes over to the next print. This happens to me all the time.</p>
1,532
<blockquote> <p><strong>Possible Duplicates:</strong><br> <a href="https://stackoverflow.com/questions/370427/learn-obj-c-memory-management">Learn Obj-C Memory Management</a><br> <a href="https://stackoverflow.com/questions/710288/where-are-the-best-explanations-of-memory-management-for-iphone">Where are the best explanations of memory management for iPhone?</a> </p> </blockquote> <p>I come from a C/C++ background and the dynamic nature of Objective-C is somewhat foreign to me, is there a good resource anyone can point me to for some basic memory management techniques in Objective-C? ex. retaining, releasing, autoreleasing</p> <p>For instance, is it completely illegal to use a pointer to an Objective-C object and treat it as an array? Are you forced to use NSArray and NSMutableArray for data structures?</p> <p>I know these are pretty newbie questions, thanks for any help you can offer me.</p>
<p><a href="http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/index.html" rel="nofollow noreferrer">Here you go</a>:</p> <blockquote> <p>Application memory management is the process of allocating memory during your program’s runtime, using it, and freeing it when you are done with it. A well-written program uses as little memory as possible. In Objective-C, it can also be seen as a way of distributing ownership of limited memory resources among many pieces of data and code. When you have finished working through this guide, you will have the knowledge you need to manage your application’s memory by explicitly managing the life cycle of objects and freeing them when they are no longer needed.</p> <p>Although memory management is typically considered at the level of an individual object, your goal is actually to manage object graphs. You want to make sure that you have no more objects in memory than you actually need...</p> </blockquote>
<p>It's probably also useful to note that for class messages like NSString + (NSString *)stringWithFormat: (basically, helper messages that allocate an object for you rather than requiring you to allocate the object yourself), the resulting object is auto-released unless you explicitly retain it. </p>
13,222
<p>Is there a trade off in respect to performance, trade off in respect to memory consumption?</p>
<p>Yes, absolutely a DataTable consumes more memory than a List.</p> <p>The DataTable class has lots of objects for column definitions, the table info (name, etc), collections of row objects, the "item arrays" for each row (which is basically all the List would have), etc.</p> <p>EDIT: Also, List is more performant for adding items, itterating through, etc. (reflect the code for "Add" for generic lists, and for data tables to see more detail).</p>
<p>Oh yeah, it's fat. It can be much more efficient than List&lt;> though. It creates an index so lookups can be O(1). Rows are stored in a red-black tree so inserts and deletes can be O(log n). All these operations are O(n) for List&lt;>. To get this kind of perf, you'll have to choose your columns and queries wisely though. Same kind of considerations as a regular database table.</p>
34,695
<p>I recently wrote a DLL in C# (.Net 2.0) which contains a class that requires an IP address. A co-worker of mine altered the class to retrieve the IP from a ".dll.config" (XML) file -- This apparently is automatically generated by the "Application Settings" file he created (Settings1.settings). The benefit of this was to allow the end-user to change the IP address in the XML/config file at will.</p> <p>Unfortunately, when I check his code out of the tree and try to compile (or use) this new code, any application calling this DLL only gets the default value, rather than the value from the file.</p> <p>The constructor that calls the config file looks like this:</p> <pre><code> public class form : System.Windows.Forms.Form { public form() { // This call is required by the Windows Form Designer. InitializeComponent(); IP = IPAddress.Parse(Settings1.Default.IPAddress); } } </code></pre> <p>I found <a href="http://social.msdn.microsoft.com/Forums/en-US/clr/thread/f3a4b138-6e6c-42e3-86e8-1f86c90f8fb4/" rel="noreferrer">a reference to this problem on the MSDN forums</a> where a user said:</p> <blockquote> <p>the 'old' values (the ones you define at development time) are hard coded. If the franework isn't able to access or open the config file it will use the defaults instead. This will always happen if you use settings in a dll.</p> </blockquote> <ol> <li><p>Does this mean that I cannot store an external value for a DLL in a config file? (My co-worker has somehow made this work...)</p></li> <li><p>Since my framework appears to be unable to access or open the config file, how do I figure out why it's failing? Or even detect when this happens?</p></li> </ol> <p><b>Decker</b>: That helps a bit. Unfortunately, I am writing this DLL to a specification, so I don't actually have access to the Application's config file. As you'll note above, my co-worker created a "Settings<b>1</b>.settings" file. I didn't understand this at the time, but it seems now that adding the "1" keeps it out of the settings space of any application that calls it. </p> <p>I guess what I'm trying to figure out is why the DLL doesn't seem to find the config file sitting next to it in the same directory. Tracing thru the code step-by-step reveals nothing.</p> <p>As an aside, I can change the "Output Type" of my assembly from "Class Library" to "Windows Application" and add the following lines at the beginning of my DLL code:</p> <pre><code> [STAThread] public static void Main(string[] args) { System.Windows.Forms.Application.Run(new form()); } </code></pre> <p>When I run this, it generates a different config file (a ".exe.config") and that one I can alter and have it pull the new data from the file. So I'm a bit confused. Any ideas?</p>
<p>I use this technique all time time. Often I have a library assembly that requires certain settings, and I need them set both by testing projects as well as the primary "executable" assemblies -- be they web projects or Windows service projects.</p> <p>You're correct in that when you create a settings file for any project, it adds an application config file. The value you enter for any setting is stored in two places -- the config file AND in attributes on the classes created by the settings infrastructure. When a config file is not found, the values embedded in the attributes are used.</p> <p>Here is a snippet that shows such an attribute:</p> <p>Here is a snippet that shows the default value of the ConcordanceServicesEndpointName in the generated class:</p> <pre><code> [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("InternalTCP")] public string ConcordanceServicesEndpointName { get { return ((string)(this["ConcordanceServicesEndpointName"])); } } </code></pre> <p>What you want to do is copy the configuration section out of the app.config file from the library assembly project and merge it (carefully) into the applicable web.config or app.config for the main assembly. At runtime, that's the only config file that is used.</p> <p>Here is an example: <pre><code><code>&lt;configSections&gt; &lt;sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" &gt; &lt;section name="LitigationPortal.Documents.BLL.DocumentsBLLSettings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /&gt; &lt;/sectionGroup&gt; &lt;/configSections&gt; &lt;applicationSettings&gt; &lt;LitigationPortal.Documents.BLL.DocumentsBLLSettings&gt; &lt;setting name="ConcordanceServicesEndpointName" serializeAs="String"&gt; &lt;value&gt;InternalTCP&lt;/value&gt; &lt;/setting&gt; &lt;/KayeScholer.LitigationPortal.Documents.BLL.DocumentsBLLSettings&gt; &lt;/applicationSettings&gt; </code></pre></code></p> <p>You should copy these sections into the "true" config file. </p>
<p>The mistake I think you all make is that you apparently make referece to the DLL Settings via <code>Settings1.Default.IPAddress</code> while you are simply suppossed to do this <code>Settings1.IPAddress</code>.</p> <p>The difference is that when you use <code>Settings1.Default.IPAddress</code> the values are gotten from the hardcoded values imbeded in the assembly file (.dll or .exe) as Attribute [global::System.Configuration.DefaultSettingValueAttribute(...)]. </p> <p>While <code>Settings1.IPAddress</code> is the value that is editable in the file <code>.dll.config</code> (XML file)**. so any changes you make to the XML file, it is not reflected in hardcoded default value in the assembly.</p> <p>Not this:</p> <pre><code>IP = IPAddress.Parse(Settings1.Default.IPAddress); </code></pre> <p>But try this:</p> <pre><code>*IP = IPAddress.Parse(Settings1.IPAddress); </code></pre>
23,406
<p>There's Windows SharePoint Services (WSS) and then there is Microsoft Office SharePoint Server (MOSS). MOSS considerably more expensive than WSS (which ships as part of Microsoft Server licensing).</p> <p>My question is: what does MOSS do that makes it <i>worth</i> the extra cost? </p> <p>..and does <a href="http://www.microsoft.com/Enterprisesearch/" rel="noreferrer">Microsoft Search Server</a> not compete with the <a href="http://msdn.microsoft.com/en-us/library/ms563661.aspx" rel="noreferrer">Business Data Cache</a> (BDC)?</p> <p>Edit: The feature comparision page is helpful in illustrating the numerous features that MOSS has and WSS does not. By the looks of it, most of MOSS's feature set is Enterprise oriented. </p> <p>How would you describe the differences (or additional benefits) of MOSS over WSS in a couple of sentences? In essence, what are the "big ticket" items in MOSS (and not in WSS)?</p>
<p>About WSS vs MOSS:</p> <ul> <li>WSS in not a portal, it's only a collaborative plateform (there are no publishing features in WSS)</li> <li>MOSS allows you to use user profils, not WSS</li> <li>Search functionalities are cheap in WSS compare to MOSS (but you can extend them using Search Server Express)</li> <li>Many others: Infopath, BDC, Additional WebParts, Additional site and list templates</li> </ul> <p>About Search Server and BDC: They do not compete.</p> <p>Search Server is the MOSS search engine striped out. So you have only search functionalities (you can index SharePoint, WebSite, FileSystem).</p> <p>The BDC (Business Data Catalog) allows you to view an external business data source, such as a SQL database (not necessarily SQL Server, it can be Oracle, MySQL....) or webservices. You'll be able to view data in your portal, and integrate this data to any of your list. The BDC also allows you to index this content source if you have SharePoint Enterprise Edition.</p>
<p>There is a lot built in to WSS but MOSS has a ton of extra stuff as referenced in the other answer.</p> <p>On the second part of your question.. Search server and Business Data Connector are quite different.. Search server is about finding things... BDC is about merging datasources to be able to use them easily in sharepoint or in connected excel sheets etc.. The focus is on what is being delivered-- search results or data.</p>
21,972
<p>What is the difference between creating one index across multiple columns versus creating multiple indexes, one <em>per</em> column?</p> <p>Are there reasons why one should be used over the other?</p> <p>For example:</p> <pre><code>Create NonClustered Index IX_IndexName On TableName (Column1 Asc, Column2 Asc, Column3 Asc) </code></pre> <p>Versus:</p> <pre><code>Create NonClustered Index IX_IndexName1 On TableName (Column1 Asc) Create NonClustered Index IX_IndexName2 On TableName (Column2 Asc) Create NonClustered Index IX_IndexName3 On TableName (Column3 Asc) </code></pre>
<p>I agree with <a href="https://stackoverflow.com/a/179109/50776">Cade Roux</a>.</p> <p>This article should get you on the right track:</p> <ul> <li><a href="http://www.sqlskills.com/BLOGS/KIMBERLY/post.aspx?id=19f0ce1c-0d2f-4ad5-9b13-a615418422e0" rel="noreferrer">Indexes in SQL Server 2005/2008 – Best Practices, Part 1</a></li> <li><a href="http://www.sqlskills.com/blogs/kimberly/indexes-in-sql-server-20052008-part-2-internals/" rel="noreferrer">Indexes in SQL Server 2005/2008 – Part 2 – Internals</a> </li> </ul> <p>One thing to note, clustered indexes should have a unique key (an identity column I would recommend) as the first column. Basically it helps your data insert at the end of the index and not cause lots of disk IO and Page splits.</p> <p>Secondly, if you are creating other indexes on your data and they are constructed cleverly they will be reused. </p> <p>e.g. imagine you search a table on three columns</p> <p>state, county, zip. </p> <ul> <li>you sometimes search by state only. </li> <li>you sometimes search by state and county.</li> <li>you frequently search by state, county, zip. </li> </ul> <p>Then an index with state, county, zip. will be used in all three of these searches.</p> <p>If you search by zip alone quite a lot then the above index will not be used (by SQL Server anyway) as zip is the third part of that index and the query optimiser will not see that index as helpful. </p> <p>You could then create an index on Zip alone that would be used in this instance.</p> <p>By the way <a href="https://use-the-index-luke.com/sql/where-clause/the-equals-operator/concatenated-keys" rel="noreferrer">We can take advantage of the fact that with Multi-Column indexing the first index column is always usable for searching</a> and when you search only by 'state' it is efficient but yet not as efficient as Single-Column index on 'state'</p> <p>I guess the answer you are looking for is that it depends on your where clauses of your frequently used queries and also your group by's.</p> <p>The article will help a lot. :-)</p>
<p>If you have queries that will be frequently using a relatively static set of columns, creating a single covering index that includes them all will improve performance dramatically. </p> <p>By putting multiple columns in your index, the optimizer will only have to access the table directly if a column is not in the index. I use these a lot in data warehousing. The downside is that doing this can cost a lot of overhead, especially if the data is very volatile.</p> <p>Creating indexes on single columns is useful for lookup operations frequently found in OLTP systems.</p> <p>You should ask yourself why you're indexing the columns and how they'll be used. Run some query plans and see when they are being accessed. Index tuning is as much instinct as science.</p>
21,595
<p>I have been researching options for printing report-like data via a web application. Some options that are viable are writing PDFs, Excel XML, dumping HTML to Excel, or using a tool like activePDF webGrabber. I suppose the question is, what are some solution that give control over print from a browser (IE in my case) yet doesn't have a huge development time. Though I don't have experience with it myself, I have seen some horrid code for generating PDFs. </p> <p>The features I'm looking for in particular are to print landscape or portrait without user intervention. Also, having control over basic styling is important to translate the basic look/feel of the web app to the printed format.</p> <p>Any advice (especially from experience) is appreciated.</p>
<p>As I've <a href="https://stackoverflow.com/questions/164197/printing-labels-from-aspnet-page">asked about here already</a> and found out the hard way, you aren't going to get reliable and accurate printing results purely within the browser. Even if it is an intranet application that you've been promised must only work with IE7, IE8 will be out soon and then Firefox will be allowed and all of your careful micromanagement of CSS will be for naught (do I sound bitter?).</p> <p>The most forward looking solution is to bite the bullet and go for generating PDFs. The tools you mentioned are good. You should also look at <a href="http://www.lowagie.com/iText/" rel="nofollow noreferrer">iText</a> and <a href="http://itextsharp.sourceforge.net/" rel="nofollow noreferrer">iTextSharp</a>. Once you get the hang of it, doing the PDF layouts isn't any harder than HTML and CSS and you will know that the results will print correctly on everyone's computer, everyone's browser, and everyone's printer. I'm currently working with iTextSharp (not finished yet, but still learning and experimenting).</p> <p>I haven't found reliable ways to control the print options from within a page either, so relying on your users to change from portrait to landscape or to set or adjust margins or turn off the print headers and footers just doesn't work in the long run - you'll end up annoying them and creating more headaches for yourself when they can't (or just don't) follow instructions.</p> <p>The "Related Questions" sidebar is very useful. I saw these questions on controlling the printer from the web page (both with answers that amount to: "you can't"):</p> <p><a href="https://stackoverflow.com/questions/37162/how-do-i-make-an-html-page-print-in-landscape-when-the-user-selects-print">Programmatically Selecting Landscape Printing</a></p> <p><a href="https://stackoverflow.com/questions/206880/printing-to-a-specific-printer-from-a-web-app">Printing to a Specific Printer</a></p>
<p>It depends on whether your expected client base is known or unknown. If you want to allow 'anyone' to generate printable documents, then I concur with others that the PDF route is a good one to go down.</p> <p>We've had good success using <a href="http://www.pdflib.com/" rel="nofollow noreferrer">PDFLib</a> to easily create attractive PDF documents. Using their server side modules you can have a designer create your document in InDesign or Illustrator, then programattically drop in the dynamic fields on top (even using Acrobat to place the fields)</p> <p>It's a little trickier for reports and dynamic row data, but can be done.</p> <p>For actually printing - if you're creating an application when your user base is known (eg. an office environment) you might consider an label printing application like <a href="http://www.seagullscientific.com/" rel="nofollow noreferrer">BarTender</a>. You can either have the web server call print jobs via an API or have the BarTender application poll the app for new jobs. Handy for web applications where you want to hit 'Print' on the site and have the printer start printing (no other user intervention) as the server is actually doing the printing, not the client.</p>
28,716
<p>I'm making a webform using a <code>LoginView</code>, the problem is that because the control includes a grey bar telling you what type of control it is it throws of correctly formatting the page (it has <code>LoginView1</code> at the top).</p> <p>Is there a way to hide this on the <code>LoginView</code> as the <code>contentPlaceholder</code> does an excellent job for this.</p> <p>I've found that you can remove the ID, but that seems like a hack as it stops programatic access</p>
<p>I may have misunderstood your question but.... </p> <p>The 'grey bar telling you what type of control it is' only shows up if you are looking at the page in 'design view' in your IDE (are you using Visual Studio?).<br> Once you run the page this label is not visible. </p> <p>It is very common for pages that have dynamic/server-side content to 'not look right' when you are looking at them in 'design view'. </p> <p>Little things like the label/grey bar you are talking about are just there to help you work on the page when it is not populated with the dynamic content. </p> <p>As a result of this, I find that 99.9% of the time I use 'source view' in my IDE because as your page content becomes more dynamic, the 'design view' becomes more useless.</p>
<p>I don't know that there is a property to control this (can't find one on MSDN), but I'd think you could just iterate through the Controls property of the LoginView and hide that panel/label/whatever.</p>
2,942
<p>I want to use magnets to hold the lid of a box down tight enough to keep it relatively airtight (along with a rubber seal etc.), but I am not sure what strength of magnet to use, that will still allow it to be opened without causing damage either by having to be pried open or by crushing the print layers. I cannot seem to find any guide to how magnets are used for 3d printing at various strengths and I cannot afford to buy too many types that I am not then going to use.</p> <p>Any help that you can provide will be greatly appreciated.</p>
<p>You can vary the “strength” of the magnet by making a membrane of 3D printed plastic in between the magnets. The strength of the attraction is something like a logarithmic relationship to distance- small changes in thickness of material in between the magnets have a large effect on how strong they stick to each other. You could dial in your print by buying strong rare earth magnets and experimenting with attenuating the strength with the membrane. Could even use sheets of paper to get the right feel, then measure the thickness of the stack.</p> <p>If using an fdm printer, it could be helpful to insert the magnets with a pause in the printing, and print over the top, if there isn’t a good way to otherwise capture them.</p>
<p>I had a similar experience using magnets to hold two plates together. Currently also building a device (3d-printed) that clamps together with magnets. For both of these scenarios, I typically start by looking at what size and force you need. I would look into maybe 3 options of different magnets to start with. It could be in the range of 0.6 lbs, 4lbs and 6lbs. Do you know how much the &quot;opening force&quot; would be? As in what would keep it opening? If its substantial, I could see more the 6lbs but this is a very very very rough estimate that honestly would be best supported with trying a few ranges of magnets first. Try McMasterCarr if you're in the US. They have affordable sized magnets that I've worked with, ranging from different sizes, thicknesses and magnetic forces.</p>
2,103
<p>I am trying to use a class from a C# assembly in vb.net. The class has ambiguous members because vb.net is case insensitive. The class is something like this:</p> <pre> public class Foo { public enum FORMAT {ONE, TWO, THREE}; public FORMAT Format { get {...} set {...} } } </pre> <p>I try to access the enum: Foo.FORMAT.ONE</p> <p>This is not possible because there is also a property named 'format'.</p> <p>I can not change the C# assembly. How can I get around this and reference the enum from vb.net?</p>
<p>I don't think you can get around this. Get in touch with the author of the C# component you are trying to use and convince them to fix their code.</p> <p>Incidentally, this is the primary reason behind the <code>CLSCompliant(true)</code> attribute, which if you are writing APIs or other code that has a high probability of being used by other languages you should always set. It would have flagged this issue for the original author to be aware of and fix correctly.</p>
<p>There are a couple of ways you can work around it, but neither one is really a good option.</p> <p>One is to create a C# project and completely wrap the class, changing the ambiguous members into unambiguous ones. Depending on how big the class is, it could be a lot of work, though you only have to wrap the members you need, obviously.</p> <p>The other is to use reflection, which isn't as much work as wrapping, but is still pointless work compared to the author just writing the code correctly in the first place.</p>
25,293
<p>I want to write a small program that should print something like</p> <blockquote> <p>testing CPU... done<br> testing RAM... done</p> </blockquote> <p>and so on.</p> <p>I wrote the following program in C:</p> <pre><code>printf( "testing RAM...\t\t" ); sleep( sleep_time ); printf( "done\n\n" ); printf( "testing HDD...\t\t" ); sleep( sleep_time ); printf( "done\n\n" ); </code></pre> <p>where <code>sleep_time</code> is 2.</p> <p>However, instead of printing "testing CPU..." first, then waiting, then printing "done", it first waits, then prints the whole line, which is not exactly what I had in mind.</p> <p>I suppose this has something to do with automatic optimization by the compiler.<br> Anyway, what can I do to get the desired output?</p> <p>I am using XCode 3.1 on OSX 10.5.6</p> <p>Thank you,<br> Bastian</p>
<p>The issue is that your printings are buffered. immediately before sleeping, call fflush(stdout); to flush the buffer</p>
<p>Just using \n or an endl at the end of the first printf should suffice</p>
36,171
<p>I have 28,000 images I need to convert into a movie. I tried </p> <pre><code>mencoder mf://*.jpg -mf w=640:h=480:fps=30:type=jpg -ovc lavc -lavcopts vcodec=msmpeg4v2 -nosound -o ../output-msmpeg4v2.avi </code></pre> <p>But it seems to crap out at 7500 frames.</p> <p>The files are named webcam_2007-04-16_070804.jpg webcam_2007-04-16_071004.jpg webcam_2007-04-16_071204.jpg webcam_2007-04-16_071404.jpg Up to march 2008 or so.</p> <p>Is there another way I can pass the filenames to mencoder so it doesn't stop part way?</p> <pre><code>MEncoder 2:1.0~rc2-0ubuntu13 (C) 2000-2007 MPlayer Team CPU: Intel(R) Pentium(R) 4 CPU 2.40GHz (Family: 15, Model: 2, Stepping: 7) CPUflags: Type: 15 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1 Compiled with runtime CPU detection. success: format: 16 data: 0x0 - 0x0 MF file format detected. [mf] search expr: *.jpg [mf] number of files: 28617 (114468) VIDEO: [IJPG] 640x480 24bpp 30.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:16 fourcc:0x47504A49 size:640x480 fps:30.00 ftime:=0.0333 Opening video filter: [expand osd=1] Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1 ========================================================================== Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family Selected video codec: [ffmjpeg] vfm: ffmpeg (FFmpeg MJPEG decoder) ========================================================================== VDec: vo config request - 640 x 480 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 3) Movie-Aspect is 1.33:1 - prescaling to correct movie aspect. videocodec: libavcodec (640x480 fourcc=3234504d [MP42]) Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Pos: 251.3s 7539f ( 0%) 47.56fps Trem: 0min 0mb A-V:0.000 [1202:0] Flushing video frames. Writing index... Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Video stream: 1202.480 kbit/s (150310 B/s) size: 37772908 bytes 251.300 secs 7539 frames </code></pre>
<p>Shove the list of images in a file, one per line. Then use <code>mf://@filename</code></p>
<p>another alternative is to bypass mencoder and use ffmpeg directly</p>
10,115
<p>Unix.....>>netstat -al | grep 8787 (will see packets on port 8787)</p>
<p>What is the nature of the question here? Are you trying to see packets on port 8787? Are you looking for services listening on port 8787? Most importantly, how is this a programming-related question?</p>
<p>If you want to see the actual packets then you need to use tcpdump.</p> <p>Use the <code>-s</code> option to specify how much of the packet you want to see (<code>0</code> means the whole packet) and the <code>-X</code> option to get a Hex and ASCII dump.</p>
11,246
<p>The short version of my question is:</p> <blockquote> <p><em>Are 3D printed parts made of ABS likely to survive for <strong>one year</strong> in an incubator at <strong>80℃</strong>?</em></p> </blockquote> <p>Please read on for more details.</p> <p>I am printing some parts that will be used inside an incubator in a lab. They are likely to be used at 80℃ for at least a year, possibly even at higher temperatures than that. (But most likely under 100℃.)</p> <p>We're currently using ABS for these parts. My question is whether 3D printed ABS will degrade under those conditions. (For example: will it become soft and slump; will it discolour; will it become brittle?) The parts clip together to form quite a big object, which is basically a rack holding a lot of glass vials, so it's important that it stays rigid.</p> <p>I did find some papers on thermal degradation of ABS (for example <a href="http://www.sciencedirect.com/science/article/pii/S0141391002000459" rel="noreferrer">this one</a> looks quite comprehensive) but I don't have the experience to interpret them in terms of how my parts will behave practically. I'm also not sure if being 3D printed will make a difference.</p> <p>If ABS is not suitable for this kind of application, are there other plastics that are? We're using the Zortrax M200, so our choices are the plastics listed <a href="https://zortrax.com/materials/zortrax-m-series/" rel="noreferrer">here</a>. I note that PCABS is listed as specifically being temperature resistant, so we might go with that - but we'd prefer ABS if it will work, since it comes in white rather than ivory (which is important for our application) and we have plenty of it available.</p> <hr> <p><strong>update:</strong> we decided in the end that using ABS is too risky, so we went with PCABS and we'll just live with the yellowish colour. (We might paint it white.) It's currently in the oven on a test run, and if it doesn't fail in a few weeks we'll take the risk of running the year-long experiment with this material. However, we would still <em>very greatly</em> appreciate advice from anyone who has concrete knowledge or experience of this kind of situation.</p>
<p>To answer your question briefly: <strong>No, ABS will not survive for a duration of at least one year at 80-100°C</strong>.</p> <p><img src="https://i.stack.imgur.com/6X0uY.png" alt="1]"> If you look at the chart above (from Tiganis/Burn), you'll notice, that the blue line (ABS 90°C) is decreasing. I did an eyeball calculation of the graph and arrived at the equation (<code>J</code> for <em>break energy</em>, <code>h</code> for <em>hours</em>):</p> <pre><code>J = -0.002h + 14 </code></pre> <p>Based on that, a break energy of 0 Joule will be reached after <em>7056 hours or 294 days</em>.</p> <p>If you roam around internet forums on 3D printing, you'll find that that value is in the ballpark of people's experiences. I remember one case, where someone put out a piece of ABS in the sun and it broke down after a year.</p> <p>Tiganis; Burn: The Effects of Heat Aging on Acrylonitrile-Butadiene-Styrene (ABS) Blends. In: Lacasse; Vanier (1999): Durability of Building Materials and Components 8, pp. 912-922.</p>
<p>I would recommend <a href="http://taulman3d.com/bluprint-spec.html" rel="nofollow noreferrer">Taulman Bluprint</a>, which has a T<sub>g</sub> of 100&nbsp;°C and prints around 250&nbsp;°C. </p> <p>I got a small sample and it printed well with the recommended settings. I didn't do any thermal testing with my print (I made a knob for a lawn mower with it) but Taulman has a solid reputation for engineered filaments.</p>
753
<p>I'm trying out ASP.NET MVC routing and have of course stumbled across a problem. I have a section, /Admin/Pages/, and this is also accessible through /Pages/, which it shouldn't. What could I be missing?</p> <p>The routing code in global.asax:</p> <pre><code>public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Pages", // Route name "Admin/Pages/{action}/{id}", // URL with parameters // Parameter defaults new { controller = "Pages", action = "Index", id = "" } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters // Parameter defaults new { controller = "Home", action = "Index", id = "" } ); } </code></pre> <p>Thanks!</p>
<p>I'd suggest adding an explicit route for /Pages/ at the beginning.</p> <p>The problem is that it's being handled by the Default route and deriving:</p> <p>controller = "Pages" action = "Index" id = ""</p> <p>which are exactly the same as the parameters for your Admin route.</p>
<p>You have in you first route {action} token/parameter which gets in conflict with setting of default action. Try changing parameter name in your route, or remove default action name.</p>
9,573
<p>Can anyone tell the function to sort the columns of a gridview in c# asp.net.</p> <p>The databound to gridview is from datacontext created using linq. I wanted to click the header of the column to sort the data.</p> <p>Thanks!</p>
<p>There are 2 things you need to do to get this right.</p> <ol> <li>Keep the sorting state is viewstate(SortDirection and SortExpression)</li> <li>You generate the correct linq expression based on the current sorting state.</li> </ol> <p>Manually handle the <strong>Sorting</strong> event in the grid and use this helper I wrote to sort by SortExpression and SortDirection:</p> <pre><code>public static IQueryable&lt;T&gt; SortBy&lt;T&gt;(IQueryable&lt;T&gt; source, string sortExpression, SortDirection direction) { if (source == null) { throw new ArgumentNullException("source"); } string methodName = "OrderBy"; if (direction == SortDirection.Descending) { methodName += "Descending"; } var paramExp = Expression.Parameter(typeof(T), String.Empty); var propExp = Expression.PropertyOrField(paramExp, sortExpression); // p =&gt; p.sortExpression var sortLambda = Expression.Lambda(propExp, paramExp); var methodCallExp = Expression.Call( typeof(Queryable), methodName, new[] { typeof(T), propExp.Type }, source.Expression, Expression.Quote(sortLambda) ); return (IQueryable&lt;T&gt;)source.Provider.CreateQuery(methodCallExp); } </code></pre> <p>db.Products.SortBy(e.SortExpression, e.SortDirection)</p> <p>Check out <a href="http://weblogs.asp.net/davidfowler/archive/2008/10/21/datacontrols-101-part-2-why-you-should-love-datasource-controls.aspx" rel="noreferrer">my blog post </a> on how to do this:</p>
<p>more information on sorting in a gridview can be found here: <a href="http://msdn.microsoft.com/en-us/library/hwf94875.aspx" rel="nofollow noreferrer">MSDN Gridview sorting</a> the methodology used to get the data should not matter, you can use the same sorting.</p>
26,191
<p>I need a simple table with a user name and password field in MySQL. Since user names must be unique, it makes sense to me to make them the primary key.</p> <p>Is it better to use <code>CHAR()</code> or <code>VARCHAR()</code> as a primary key? </p>
<p>may as well just use a user ID index, it's much faster for joins vs char/varchar. the two seconds it takes to add that now could save you a lot of time later if you accidently have to expand the functionality of your schema.</p> <p>some pitfalls to think about:</p> <ul> <li>say we add a few tables at a future date, what if someone wants to change a username?</li> <li>say the app is more successful then we think, and we have to look at optimization, do you really want to redo your schema at this point to reduce the overhead of a varchar'ed index?</li> </ul>
<p>I don't see CHAR used much in any MySQL databases i've worked on. I would go with the VARCHAR</p> <p>For a CHAR(30) for example, the entire 30 characters are stored in the table meaning every entry will take up the same space, even if your username is only 10 characters long.</p> <p>Using VARCHAR(30) it will only use enough space to store the string you have entered.</p> <p>On a small table it wont make much difference, but on a larger table the VARCHAR should prove to keep it smaller overall.</p>
19,942
<p>I've been tasked (by my wife) with creating a program to allow her to track the family trees on both sides of our family.</p> <p>Does anyone know of a cost-effective (free) control to represent this type of information?</p> <p>What I'm looking for is a modified org-chart type chart/tree. The modification is that any node should have 2 parent nodes (E.G. a child should have a Mother/Father).</p> <p>The solution I've come up with so far is to have 2 trees, an ancestor tree and a descendants tree, with the individual being inspected as the root node for each tree. It works but is sort of clunky.</p> <p>I'm working primarily in c# WinForms, so .Net type controls or source code is preferable.</p>
<p><a href="http://www.geni.com/" rel="noreferrer">Geni</a> is probably what your looking for.</p>
<p>I haven't thought too hard about this, but I reckon you could get a Custom Treeview in WPF to do what you want. I was reading an <a href="http://www.codeproject.com/KB/WPF/CustomTreeViewLayout.aspx" rel="nofollow noreferrer">article on code project a while back that implemented an org chart</a> this way...</p>
2,776
<p>I've created a simple HttpModule to log the uses of my existing webservice. There's a dll containing a single class </p> <pre><code>public class TrackingModule : System.Web.IHttpModule { public TrackingModule(){} public void Init(System.Web.HttpApplication context) { context.BeginRequest+=new EventHandler(context_BeginRequest); } public void Dispose() { } private void context_BeginRequest(object sender, EventArgs e) { try { Microsoft.ApplicationBlocks.ExceptionManagement.ExceptionManager.Publish( new Exception("Log attept") ); HttpApplication app = (HttpApplication)sender; string method = app.Request.RawUrl; SaveUseToDatabase( app.Request.UserHostAddress, method ); } catch( Exception ex ) { try { Microsoft.ApplicationBlocks.ExceptionManagement.ExceptionManager.Publish( ex ); } catch{} } } } </code></pre> <p>After compiling the dll I add it to webservice's bin folder and in webservice's web.config I add:</p> <pre><code>&lt;system.web&gt; &lt;httpModules&gt; &lt;add name="TrackingModule" type="WebserviceTrackingModule.TrackingModule, WebserviceTrackingModule"/&gt; </code></pre> <p>This works fine on my computer, but when I copy it to production server, nothing happens. No new entries in database, no entries logged by ExceptionManager. As if it's not there at all.</p> <p>What can I be missing?</p> <p>Edit: After performing another test I can add that it works when I add it for a webservice that has it's own top-level virtual directory. It doesn't work for webservices that reside in virtual directories that are subfolders of another virtual directory.</p> <p>I know that HttpModules settings are being inherited by subdirectories, but it looks like the existence of parent directory gets in the way.</p>
<p>I believe I have found a better solution. Attach the module at runtime instead of in the web config. Check out <a href="http://www.west-wind.com/weblog/posts/44979.aspx" rel="nofollow noreferrer">Rick Strahl's blog post</a> for the details.</p>
<p>Does this work?</p> <pre><code>&lt;add name="TrackingModule" type="WebserviceTrackingModule.TrackingModule" /&gt; </code></pre> <p>And is the context_BeginRequest method definitely being called for each request?</p>
49,518
<p>I want to use a timer in my simple <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="nofollow noreferrer">.NET</a> application written in C#. The only one I can find is the Windows.Forms.Timer class. I don't want to reference this namespace just for my console application. </p> <p>Is there a C# timer (or timer like) class for use in console applications?</p>
<p>System.Timers.Timer</p> <p>And as MagicKat says:</p> <p>System.Threading.Timer</p> <p>You can see the differences here: <a href="http://intellitect.com/system-windows-forms-timer-vs-system-threading-timer-vs-system-timers-timer/" rel="noreferrer">http://intellitect.com/system-windows-forms-timer-vs-system-threading-timer-vs-system-timers-timer/</a></p> <p>And you can see MSDN examples here: </p> <p><a href="http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx</a></p> <p>And here:</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.threading.timer(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.threading.timer(VS.80).aspx</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx" rel="nofollow noreferrer">System.Diagnostics.Stopwatch</a> if your goal is to time how long something takes to run</p>
20,441
<p>a lot of websites like twitter, facebook and others let the users enter their email id and pwd and 'extract' the contacts based on that. </p> <p>Anyone know how this is done? </p>
<p>They login to your account and scrape the contents, or use a public API. Either way, it's not a method that I would implement or use myself because I wouldn't trust anyone else with my credentials. And I think it teaches users to be careless with the secrecy of their credentials.</p>
<p>For gmail:</p> <p><a href="http://sourceforge.net/projects/gmail-api" rel="nofollow noreferrer">http://sourceforge.net/projects/gmail-api</a></p> <p><a href="http://johnvey.com/features/gmailapi/" rel="nofollow noreferrer">http://johnvey.com/features/gmailapi/</a></p>
11,298
<p>This is a pretty simple question, at least it seems like it should be, about sudo permissions in Linux.</p> <p>There are a lot of times when I just want to append something to <code>/etc/hosts</code> or a similar file but end up not being able to because both <code>&gt;</code> and <code>&gt;&gt;</code> are not allowed, even with root.</p> <p>Is there someway to make this work without having to <code>su</code> or <code>sudo su</code> into root?</p>
<p>Use <code>tee --append</code> or <code>tee -a</code>.</p> <pre><code>echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list </code></pre> <p>Make sure to avoid quotes inside quotes.</p> <p>To avoid printing data back to the console, redirect the output to /dev/null.</p> <pre><code>echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list &gt; /dev/null </code></pre> <p>Remember about the (<code>-a</code>/<code>--append</code>) flag! Just <code>tee</code> works like <code>&gt;</code> and will overwrite your file. <code>tee -a</code> works like <code>&gt;&gt;</code> and will write at the end of the file.</p>
<p>Can you change the ownership of the file then change it back after using <code>cat &gt;&gt;</code> to append?</p> <pre><code>sudo chown youruser /etc/hosts sudo cat /downloaded/hostsadditions &gt;&gt; /etc/hosts sudo chown root /etc/hosts </code></pre> <p>Something like this work for you? </p>
11,041
<p>I want to generate a list in C#. I am missing python's list comprehensions. Is there a C# way to create collections on the fly like list comprehensions or generator expressions do in python?</p>
<p>If you are using C# 3.0 (VS2008) then LINQ to Objects can do very similar things:</p> <pre><code>List&lt;Foo&gt; fooList = new List&lt;Foo&gt;(); IEnumerable&lt;Foo&gt; extract = from foo in fooList where foo.Bar &gt; 10 select Foo.Name.ToUpper(); </code></pre>
<p>There's this:</p> <pre class="lang-cs prettyprint-override"><code>new List&lt;FooBar&gt; { new Foo(), new Bar() } </code></pre> <p>which is only a little longer than its python equivalent:</p> <pre class="lang-py prettyprint-override"><code>[Foo(), Bar()] </code></pre> <p>And then there is this:</p> <pre class="lang-cs prettyprint-override"><code>public IEnumerable&lt;FooBar&gt; myFooBarGenerator() { yield return new Foo(); yield return new Bar(); } </code></pre> <p>which is the python equivalent of:</p> <pre class="lang-py prettyprint-override"><code>def myFooBarGenerator(): yield Foo() yield Bar() </code></pre>
41,805
<p>I want to do this in code, not with ALT+F1.</p>
<p>You can also do it this way:</p> <pre><code>select columnproperty(object_id('mytable'),'mycolumn','IsIdentity') </code></pre> <p>Returns 1 if it's an identity, 0 if not.</p>
<p>As expansion on @Blogbeard's answer</p> <p>If you like pure query and not inbuilt functions</p> <pre><code>select col_name(sys.all_objects.object_id, column_id) as id from sys.identity_columns join sys.all_objects on sys.identity_columns.object_id = sys.all_objects.object_id where sys.all_objects.name = 'system_files' </code></pre>
22,920
<p>I'm making a study on refactoring limitations on improving existing software architecture and I would be interested to hear your experiences where you have found refactoring to be not enough or still too immature to accomplish your goals.</p>
<p>Refactoring can be risky</p> <p>Refactoring is often difficult because the refactorer often isn't the same person as the original designer. Therefore, he or she doesn't have the same background in the system and the decisions that went behind the original design. You always run the risk that bugs avoided in the original design may creep up in the new design.</p> <p>This may be especially true when a new or young team member, not fully experienced with this system, decides to inject new-cool-wizbang technology or ideas into an otherwise stable system. Often when the new team members are not integrated well into the team and are not given sufficient guidance, they may begin forcing the project in directions unintended by the whole team.</p> <p>This is just a risk, however, there's also a chance that the team is wrong and the new team member, if put in charge and was allowed to do his or her thing, would actually make a serious improvement.</p> <p>These problems often come up amongst a team working on legacy systems. Often there are no world-altering enhancements planned, so the team is conservative with their design. Their goal is to prevent new bugs from being injected and fix old ones with a couple extra features thrown in. A new team member might come along and upset the apple cart by insisting that, he rewrite certain subsystems of the code. New bugs are created and users of a fairly stable product are upset because the software, from there perspective is getting worst.</p> <p>So if your goal is long-term stability without major functionality changes, often major refactoring is not what you want.</p> <p>If you have larger functionality changes in the pike however, have a user-base that expects your product to not be fully baked quite yet (ie you're in some sort of beta), then its a much better situation to consider serious refactoring because the long-term benefits of the superior design will pay off and you're less likely to disrupt a large user base.</p>
<p>To Kev's excellent Answer - "Working Effectively with Legacy Code" by Michael Feathers should be required reading for people working in Software Engineering.</p>
17,602
<p>I have an external variable coming in as a string and I would like to do a switch/case on it. How do I do that in xquery?</p>
<p>Starting with XQuery 1.1, use switch:</p> <p><a href="http://www.w3.org/TR/xquery-11/#id-switch" rel="noreferrer">http://www.w3.org/TR/xquery-11/#id-switch</a></p> <pre class="lang-xquery prettyprint-override"><code>switch ($animal) case "Cow" return "Moo" case "Cat" return "Meow" case "Duck" return "Quack" default return "What's that odd noise?" </code></pre>
<p>For Saxon, you can use something like this:</p> <pre class="lang-saxon prettyprint-override"><code>declare function a:fn($i) { typeswitch ($i) case element(a:elemen1, xs:untyped) return 'a' case element(a:elemen2, xs:untyped) return 'b' default return "error;" }; </code></pre> <p><a href="https://rrusin.blogspot.com/2010/01/xquery4j-in-action.html" rel="nofollow noreferrer">https://rrusin.blogspot.com/2010/01/xquery4j-in-action.html</a></p>
11,127
<p>I need to write a program used internally where different users will have different abilities within the program.</p> <p>Rather than making users have a new username and password, how do I tie into an existing domain server's login system?</p> <p>Assume .NET (C#, VB, ASP, etc)</p> <p>-Adam</p>
<p>For WinForms, use System.Threading.Thread.CurrentPrincipal with the IsInRole() method to check which groups they are a member of. You do need to set the principal policy of the AppDomain to WindowsPrincipal first.</p> <p>Use this to get the current user name:</p> <pre><code>private string getWindowsUsername() { AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); return Thread.CurrentPrincipal.Identity.Name; } </code></pre> <p>And then something like this to check a role:</p> <pre><code>if (Thread.CurrentPrincipal.IsInRole("Domain Users") == true) {} </code></pre> <p>In ASP.NET, the thread will belong to IIS, so instead you should </p> <ol> <li>Set the virtual folder or website to require authentication</li> <li>Get the user name supplied by the browser with Request.ServerVariables("LOGON_USER")</li> <li>Use the <a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.aspx" rel="nofollow noreferrer">DirectorySearcher</a> class to find the users groups</li> </ol>
<p>Assuming this is served through IIS, I would tell IIS to authenticate via the domain, but I would keep authorization (what roles a user is associated with, accessible functionality, etc) within the application itself. </p> <p>You can retreive the username used to authenticate via </p> <pre><code>Trim(Request.ServerVariables("LOGON_USER")).Replace("/", "\").Replace("'", "''") </code></pre> <p>OR</p> <pre><code>CStr(Session("User")).Substring(CStr(Session("User")).LastIndexOf("\") + 1) </code></pre>
10,917
<p>I'm having a bit of a problem. I have a datatable in the parent form. I open a dialogbox form that gets the datatable property and creates a checkboxlist. This will be used to export those columns. But when I run the application the parentform property is null. I've tried setting it in the parent and dialogbox form (I assumed this would have been done automagically if ShowDialog() was called).</p> <p>Can someone take a look and see where I'm going wrong? From the dialogbox:</p> <pre><code>frmParent MyParentForm = (frmParent)this.ParentForm; for (int i=0; i&lt;MyParentForm.DataGridTable.Count; i++) { chkListExportItems.Add(MyParentForm.DataGrid.Columns[i].Name,true); } </code></pre> <p>From the parent form:</p> <pre><code>frmExports MyForm = new frmExports(); MyForm.MdiParent = this; if (MyForm.ShowDialog == DialogResult.OK) { MyForm.SelectedItems // Do something } </code></pre>
<p>I have a Listbox bound to an object property which is of type <code>List&lt;MyCustomType&gt;()</code> and I verified that the following code updates the listbox when the List is updated.</p> <pre><code>void On_MyObjProperty_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { MyListBox.Items.Refresh(); } </code></pre> <p>If you're still facing issues, scan the VS IDE output window (Ctrl+W, O) and see if you can spot any binding errors reported.</p>
<p>If you have an ObservableList of objects, and you're changing properties inside those objects, the notification doesn't apply since the collection is not changing directly. I have been forcing notification after changing my object properties by using Insert() to re-add my changed object to the collection, then RemoveAt() to remove the old copy. It's not pretty, but it works.</p>
31,538
<p>I'm starting a new project using Flex3 for a reasonably intricate UI getting its data from a collection of RESTful web services. I wondering what experiences others have had in structuring a moderately complex Flex project. The issues I'm thinking about include:</p> <ul> <li>I want to use our FlexBuilder licenses for visual editing of layouts and debugging code on Eclipse</li> <li>automated build script so that we can use a CI server</li> <li>testing strategies, particularly automatable unit tests</li> <li>cross-platform Linux and Windows development environments (yes, I know the Linux version of FlexBuilder doesn't do visual editing, but everything else should ideally run cross-platform)</li> <li>dependency management for at least the Java code (are there library dependency managers for Flex?)</li> </ul> <p>I've just burned a day trying and failing to get a maven2/flex/jetty build setup working smoothly (based on <a href="http://riadiscuss.jeffmaury.com/2008/09/maven-and-flex-builder-tutorial-part-i.html" rel="nofollow noreferrer">Jeff Maury's tutorial</a>). I'm not dead-against using Maven as we go forwards, but I'm sure there must be a less painful route. The main issue I had (other than maven documentation being patchy) is that maven's &quot;single artifact per build&quot; rule means that you have to jump through a lot of hoops with a complex build, and I'm not enough of a maven initiate not to trip over the hoops and fall on my face! </p> <p>Would Ant and Ivy be a better option than maven2? What other choices are there?</p>
<p>I don't know Flex development but I know CI so I'll comment on that aspect.</p> <p>I work on <a href="http://cruisecontrol.sourceforge.net/" rel="nofollow noreferrer">CruiseControl</a>, so that's what I use (when not being paid to setup something else). And there are blog entries that describe setting up Flex projects under CC for both <a href="http://www.eyefodder.com/blog/2006/05/continuous_integration_with_fl_5.shtml" rel="nofollow noreferrer">Windows</a> and <a href="http://weblogs.macromedia.com/pmartin/archives/2007/01/continous_integ.html" rel="nofollow noreferrer">Linux</a>. CC has been around for a long time so there is a large community of users and lots of <a href="http://confluence.public.thoughtworks.org/display/CC/3rdPartyCCStuff" rel="nofollow noreferrer">3rd party tools</a> that work with it.</p> <p>But other people are likely to recommend <a href="http://hudson-ci.org/" rel="nofollow noreferrer">Hudson</a> and it would be hard to argue against them. Hudson is very easy to get up and running and has a nice web based UI. This project is very active, has lots of fans and lots of buzz and has matured very rapidly. I don't have anything bad to say about it. This blog entry describes <a href="http://www.blackpepper.co.uk/black-pepper-blog/Adding-Selenium-Flex-tests-to-a-Hudson-job.html" rel="nofollow noreferrer">running acceptance tests under Hudson</a>.</p> <p>I don't know enough about Maven to offer advice there but I'm working with Ivy at a client right now and I really like it. We've got a combination of Java and C++ code and we're able to get Ivy to do what we need. </p>
<p>Well we are using maven. With some help of a lot of different web sties I have an enterprise application being built using maven.</p> <p>This article via adobe has really help a lot.<br> <a href="http://www.adobe.com/devnet/flex/articles/fullstack_pt1.html" rel="nofollow noreferrer">http://www.adobe.com/devnet/flex/articles/fullstack_pt1.html</a><br> <a href="http://www.adobe.com/devnet/flex/articles/fullstack_pt2.html" rel="nofollow noreferrer">http://www.adobe.com/devnet/flex/articles/fullstack_pt2.html</a><br> <a href="http://www.adobe.com/devnet/flex/articles/fullstack_pt3.html" rel="nofollow noreferrer">http://www.adobe.com/devnet/flex/articles/fullstack_pt3.html</a><br></p> <p>You really need a common configuration project that will be shared between both flex and java, and possibly your c++ code. This article explains how to set that all up.</p> <p>Down side, if you are not knowledgeable with maven there is a slight learning curve. </p>
40,109
<p>I have a bunch (hundreds) of files that are supposed to have Unix line endings. I strongly suspect that some of them have Windows line endings, and I want to programmatically figure out which ones do.</p> <p>I know I can just run <pre>flip -u</pre> or something similar in a script to convert everything, but I want to be able to identify those files that need changing first.</p>
<p>You can use the <a href="http://en.wikipedia.org/wiki/File_(Unix)" rel="noreferrer"><code>file</code></a> tool, which will tell you the type of line ending. Or, you could just use <code>dos2unix -U</code> which will convert everything to Unix line endings, regardless of what it started with.</p>
<p>Windows use char 13 &amp; 10 for line ending, unix only one of them ( i don't rememeber which one ). So you can replace char 13 &amp; 10 for char 13 or 10 ( the one, which use unix ).</p>
14,766
<p>Let's say I'm creating a chess program. I have a function</p> <pre><code>void foreachMove( void (*action)(chess_move*), chess_game* game); </code></pre> <p>which will call the function pointer action on each valid move. This is all well and good, but what if I need to pass more parameters to the action function? For example:</p> <pre><code>chess_move getNextMove(chess_game* game, int depth){ //for each valid move, determine how good the move is foreachMove(moveHandler, game); } void moveHandler(chess_move* move){ //uh oh, now I need the variables "game" and "depth" from the above function } </code></pre> <p>Redefining the function pointer is not the optimal solution. The foreachMove function is versatile and many different places in the code reference it. It doesn't make sense for each one of those references to have to update their function to include parameters that they don't need.</p> <p>How can I pass extra parameters to a function that I'm calling through a pointer?</p>
<p>Ah, if only C supported closures...</p> <p>Antonio is right; if you need to pass extra parameters, you'll need to redefine your function pointer to accept the additional arguments. If you don't know exactly what parameters you'll need, then you have at least three choices:</p> <ol> <li>Have the last argument in your prototype be a void*. This gives you flexibility of passing in anything else that you need, but it definitely isn't type-safe.</li> <li>Use variadic parameters (...). Given my lack of experience with variadic parameters in C, I'm not sure if you can use this with a function pointer, but this gives even more flexibility than the first solution, albeit still with the lack of type safety.</li> <li>Upgrade to C++ and use <a href="http://en.wikipedia.org/wiki/Function_object" rel="noreferrer">function objects</a>.</li> </ol>
<p>+1 to Antonio. You need to change your function pointer declaration to accept additional parameters.</p> <p>Also, please don't start passing around void pointers or (especially) arrays of void pointers. That's just asking for trouble. If you start passing void pointers, you're going to also have to pass some kind of message to indicate what the pointer type is (or types are). This technique is <em>rarely</em> appropriate.</p> <p>If your parameters are always the same, just add them to your function pointer arguments (or possibly pack them into a struct and use that as the argument if there are a lot of parameters). If your parameters change, then consider using multiple function pointers for the multiple call scenarios instead of passing void pointers.</p>
3,248
<p>What is the state of native SVG support in the most popular browsers in their latest releases?</p> <ul> <li>Internet explorer</li> <li>Firefox</li> <li>Opera</li> <li>Safari</li> <li>Chrome</li> <li>Konqueror</li> <li>Camino</li> </ul>
<ul> <li>IE has SVG support in IE9 but not in IE8 and below. The alternative is <a href="http://msdn.microsoft.com/en-us/library/bb250524.aspx" rel="nofollow noreferrer">VML</a></li> <li><a href="http://www.mozilla.org/projects/svg/" rel="nofollow noreferrer">Mozilla claims to support it on its latest version</a></li> <li><a href="http://www.opera.com/products/desktop/svg/" rel="nofollow noreferrer">Opera claims to support it since v8.0</a></li> <li><a href="http://webkit.org/projects/svg/index.html" rel="nofollow noreferrer">Safari has experimental support (probably incomplete)</a></li> <li><a href="http://www.nabble.com/Google-Chrome---SVG-support--td19268298.html" rel="nofollow noreferrer">Chrome seems to have roughly the same level of SVG support as Safari</a></li> <li><a href="http://svg.kde.org/" rel="nofollow noreferrer">Konqueror uses the same SVG engine as Safari and Chrome</a> - KSVG claims to be in beta. The fact that they have a <a href="http://svg.kde.org/tasks.php" rel="nofollow noreferrer">TODO list</a> implies it's not ready for production</li> <li><a href="http://svg.org/story/2005/12/30/231328/85" rel="nofollow noreferrer">Camino apparently supports SVG as well</a></li> </ul>
<p>It should be noted that not only does IE natively lack support but the major plugin (from Adobe) was end of lifed. While many of the browsers above offser support it is highly, highly uneven. </p>
26,515
<blockquote> <p><strong>Edit:</strong> The code here still has some bugs in it, and it could do better in the performance department, but instead of trying to fix this, for the record I took the problem over to the Intel discussion groups and got lots of great feedback, and if all goes well a polished version of Atomic float will be included in a near future release of Intel's Threading Building Blocks</p> </blockquote> <p>Ok here's a tough one, I want an Atomic float, not for super-fast graphics performance, but to use routinely as data-members of classes. And I don't want to pay the price of using locks on these classes, because it provides no additional benefits for my needs. </p> <p>Now with intel's tbb and other atomic libraries I've seen, integer types are supported, but not floating points. So I went on and implemented one, and it works... but I'm not sure if it REALLY works, or I'm just very lucky that it works.</p> <p>Anyone here knows if this is not some form of threading heresy?</p> <pre><code>typedef unsigned int uint_32; struct AtomicFloat { private: tbb::atomic&lt;uint_32&gt; atomic_value_; public: template&lt;memory_semantics M&gt; float fetch_and_store( float value ) { const uint_32 value_ = atomic_value_.tbb::atomic&lt;uint_32&gt;::fetch_and_store&lt;M&gt;((uint_32&amp;)value); return reinterpret_cast&lt;const float&amp;&gt;(value_); } float fetch_and_store( float value ) { const uint_32 value_ = atomic_value_.tbb::atomic&lt;uint_32&gt;::fetch_and_store((uint_32&amp;)value); return reinterpret_cast&lt;const float&amp;&gt;(value_); } template&lt;memory_semantics M&gt; float compare_and_swap( float value, float comparand ) { const uint_32 value_ = atomic_value_.tbb::atomic&lt;uint_32&gt;::compare_and_swap&lt;M&gt;((uint_32&amp;)value,(uint_32&amp;)compare); return reinterpret_cast&lt;const float&amp;&gt;(value_); } float compare_and_swap(float value, float compare) { const uint_32 value_ = atomic_value_.tbb::atomic&lt;uint_32&gt;::compare_and_swap((uint_32&amp;)value,(uint_32&amp;)compare); return reinterpret_cast&lt;const float&amp;&gt;(value_); } operator float() const volatile // volatile qualifier here for backwards compatibility { const uint_32 value_ = atomic_value_; return reinterpret_cast&lt;const float&amp;&gt;(value_); } float operator=(float value) { const uint_32 value_ = atomic_value_.tbb::atomic&lt;uint_32&gt;::operator =((uint_32&amp;)value); return reinterpret_cast&lt;const float&amp;&gt;(value_); } float operator+=(float value) { volatile float old_value_, new_value_; do { old_value_ = reinterpret_cast&lt;float&amp;&gt;(atomic_value_); new_value_ = old_value_ + value; } while(compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); } float operator*=(float value) { volatile float old_value_, new_value_; do { old_value_ = reinterpret_cast&lt;float&amp;&gt;(atomic_value_); new_value_ = old_value_ * value; } while(compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); } float operator/=(float value) { volatile float old_value_, new_value_; do { old_value_ = reinterpret_cast&lt;float&amp;&gt;(atomic_value_); new_value_ = old_value_ / value; } while(compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); } float operator-=(float value) { return this-&gt;operator+=(-value); } float operator++() { return this-&gt;operator+=(1); } float operator--() { return this-&gt;operator+=(-1); } float fetch_and_add( float addend ) { return this-&gt;operator+=(-addend); } float fetch_and_increment() { return this-&gt;operator+=(1); } float fetch_and_decrement() { return this-&gt;operator+=(-1); } }; </code></pre> <p>Thanks!</p> <p><strong>Edit:</strong> changed size_t to uint32_t as Greg Rogers suggested, that way its more portable</p> <p><strong>Edit:</strong> added listing for the entire thing, with some fixes.</p> <p><strong>More Edits:</strong> Performance wise using a locked float for 5.000.000 += operations with 100 threads on my machine takes 3.6s, while my atomic float even with its silly do-while takes 0.2s to do the same work. So the >30x performance boost means its worth it, (and this is the catch) if its correct.</p> <p><strong>Even More Edits:</strong> As Awgn pointed out my <code>fetch_and_xxxx</code> parts were all wrong. Fixed that and removed parts of the API I'm not sure about (templated memory models). And implemented other operations in terms of operator += to avoid code repetition</p> <p><strong>Added:</strong> Added operator *= and operator /=, since floats wouldn't be floats without them. Thanks to Peterchen's comment that this was noticed</p> <p><strong>Edit:</strong> Latest version of the code follows (I'll leave the old version for reference though)</p> <pre><code> #include &lt;tbb/atomic.h&gt; typedef unsigned int uint_32; typedef __TBB_LONG_LONG uint_64; template&lt;typename FLOATING_POINT,typename MEMORY_BLOCK&gt; struct atomic_float_ { /* CRC Card ----------------------------------------------------- | Class: atmomic float template class | | Responsability: handle integral atomic memory as it were a float, | but partially bypassing FPU, SSE/MMX, so it is | slower than a true float, but faster and smaller | than a locked float. | *Warning* If your float usage is thwarted by | the A-B-A problem this class isn't for you | *Warning* Atomic specification says we return, | values not l-values. So (i = j) = k doesn't work. | | Collaborators: intel's tbb::atomic handles memory atomicity ----------------------------------------------------------------*/ typedef typename atomic_float_&lt;FLOATING_POINT,MEMORY_BLOCK&gt; self_t; tbb::atomic&lt;MEMORY_BLOCK&gt; atomic_value_; template&lt;memory_semantics M&gt; FLOATING_POINT fetch_and_store( FLOATING_POINT value ) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::fetch_and_store&lt;M&gt;((MEMORY_BLOCK&amp;)value); //atomic specification requires returning old value, not new one return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_); } FLOATING_POINT fetch_and_store( FLOATING_POINT value ) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::fetch_and_store((MEMORY_BLOCK&amp;)value); //atomic specification requires returning old value, not new one return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_); } template&lt;memory_semantics M&gt; FLOATING_POINT compare_and_swap( FLOATING_POINT value, FLOATING_POINT comparand ) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::compare_and_swap&lt;M&gt;((MEMORY_BLOCK&amp;)value,(MEMORY_BLOCK&amp;)compare); //atomic specification requires returning old value, not new one return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_); } FLOATING_POINT compare_and_swap(FLOATING_POINT value, FLOATING_POINT compare) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::compare_and_swap((MEMORY_BLOCK&amp;)value,(MEMORY_BLOCK&amp;)compare); //atomic specification requires returning old value, not new one return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_); } operator FLOATING_POINT() const volatile // volatile qualifier here for backwards compatibility { const MEMORY_BLOCK value_ = atomic_value_; return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_); } //Note: atomic specification says we return the a copy of the base value not an l-value FLOATING_POINT operator=(FLOATING_POINT rhs) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::operator =((MEMORY_BLOCK&amp;)rhs); return reinterpret_cast&lt;const FLOATING_POINT&amp;&gt;(value_); } //Note: atomic specification says we return an l-value when operating among atomics self_t&amp; operator=(self_t&amp; rhs) { const MEMORY_BLOCK value_ = atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::operator =((MEMORY_BLOCK&amp;)rhs); return *this; } FLOATING_POINT&amp; _internal_reference() const { return reinterpret_cast&lt;FLOATING_POINT&amp;&gt;(atomic_value_.tbb::atomic&lt;MEMORY_BLOCK&gt;::_internal_reference()); } FLOATING_POINT operator+=(FLOATING_POINT value) { FLOATING_POINT old_value_, new_value_; do { old_value_ = reinterpret_cast&lt;FLOATING_POINT&amp;&gt;(atomic_value_); new_value_ = old_value_ + value; //floating point binary representation is not an issue because //we are using our self's compare and swap, thus comparing floats and floats } while(self_t::compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); //return resulting value } FLOATING_POINT operator*=(FLOATING_POINT value) { FLOATING_POINT old_value_, new_value_; do { old_value_ = reinterpret_cast&lt;FLOATING_POINT&amp;&gt;(atomic_value_); new_value_ = old_value_ * value; //floating point binary representation is not an issue becaus //we are using our self's compare and swap, thus comparing floats and floats } while(self_t::compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); //return resulting value } FLOATING_POINT operator/=(FLOATING_POINT value) { FLOATING_POINT old_value_, new_value_; do { old_value_ = reinterpret_cast&lt;FLOATING_POINT&amp;&gt;(atomic_value_); new_value_ = old_value_ / value; //floating point binary representation is not an issue because //we are using our self's compare and swap, thus comparing floats and floats } while(self_t::compare_and_swap(new_value_,old_value_) != old_value_); return (new_value_); //return resulting value } FLOATING_POINT operator-=(FLOATING_POINT value) { return this-&gt;operator+=(-value); //return resulting value } //Prefix operator FLOATING_POINT operator++() { return this-&gt;operator+=(1); //return resulting value } //Prefix operator FLOATING_POINT operator--() { return this-&gt;operator+=(-1); //return resulting value } //Postfix operator FLOATING_POINT operator++(int) { const FLOATING_POINT temp = this; this-&gt;operator+=(1); return temp//return resulting value } //Postfix operator FLOATING_POINT operator--(int) { const FLOATING_POINT temp = this; this-&gt;operator+=(1); return temp//return resulting value } FLOATING_POINT fetch_and_add( FLOATING_POINT addend ) { const FLOATING_POINT old_value_ = atomic_value_; this-&gt;operator+=(addend); //atomic specification requires returning old value, not new one as in operator x= return old_value_; } FLOATING_POINT fetch_and_increment() { const FLOATING_POINT old_value_ = atomic_value_; this-&gt;operator+=(+1); //atomic specification requires returning old value, not new one as in operator x= return old_value_; } FLOATING_POINT fetch_and_decrement() { const FLOATING_POINT old_value_ = atomic_value_; this-&gt;operator+=(-1); //atomic specification requires returning old value, not new one as in operator x= return old_value_; } }; typedef atomic_float_&lt;float,uint_32&gt; AtomicFloat; typedef atomic_float_&lt;double,uint_64&gt; AtomicDouble; </code></pre>
<p>I would seriously advise against public inheritance. I don't know what the atomic implementation is like, but im assuming it has overloaded operators that use it as the integral type, which means that those promotions will be used instead of your float in many (maybe most?) cases.</p> <p>I don't see any reason why that wouldn't work, but like you I have to way to prove that...</p> <p>One note: your <code>operator float()</code> routine does not have load-acquire semantics, and shouldn't it be marked const volatile (or definitely at least const)?</p> <p>EDIT: If you are going to provide operator--() you should provide both prefix/postfix forms.</p>
<p>From my reading of that code, I would be really mad at such a compiler as to put out assembly for this that wasn't atomic.</p>
29,976
<p>Anyone know how to do this without using a third party program? If there no way to do it with a add-on someone can recommend one?</p> <p>EDIT: I need to add this in the server so all users have the same signature.</p> <p>Thanks</p>
<p>You need to create your own exchange message sink to do this. Here's a classic VB example from MS KB:</p> <p><a href="http://support.microsoft.com/kb/317327" rel="nofollow noreferrer">http://support.microsoft.com/kb/317327</a></p> <p>and a VB Script one:</p> <p><a href="http://support.microsoft.com/kb/317680" rel="nofollow noreferrer">http://support.microsoft.com/kb/317680</a></p> <p>And lots of goodness from MSDN about Exchange 2003 Transport Event Sinks:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms526223(EXCHG.10).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms526223(EXCHG.10).aspx</a></p> <p>If you're running Exchange 2007 then you can use Transport Rules:</p> <p><a href="http://msexchangeteam.com/archive/2006/12/12/431879.aspx" rel="nofollow noreferrer">http://msexchangeteam.com/archive/2006/12/12/431879.aspx</a></p> <p><a href="http://www.msexchange.org/tutorials/Using-Transport-Rules-Creating-Disclaimers-Exchange-Server-2007.html" rel="nofollow noreferrer">http://www.msexchange.org/tutorials/Using-Transport-Rules-Creating-Disclaimers-Exchange-Server-2007.html</a></p>
<p>We used <a href="http://codetwo.com/" rel="nofollow noreferrer">CodeTwo-s</a> Exchange rules for a while on Exchange 2003.</p> <p>However there is a known problem with it: if the messages stay in the queue for 2-3 minutes, the Exchange itself sends out the message without the footer. Most of the times it's not a problem, but we have something like 700 people in our organization. If there are a lot of emails and some of them contains attachments, then the virus scanner stops them for a while (MS Antigen).</p> <p>Otherwise it's a perfect solution if you have a smaller group of users to manage.</p> <p>From other point of view: our users like to have some kind of control over the signature. We generated them and put it to their Outlooks. They like it that they know and see that the signature is there and how it looks like.</p>
3,241
<p>While cross-site scripting is generally regarded as negative, I've run into several situations where it's necessary.</p> <p>I was recently working within the confines of a very limiting content management system. I needed to include database code within the page, but the hosting server didn't have anything usable available. I set up a couple bare-bones scripts on my own server, originally thinking that I could use AJAX to import the contents of my scripts directly into the template of the CMS (thus retaining dynamic images, menu items, CSS, etc.). I was wrong.</p> <p>Due to the limitations of <code>XMLHttpRequest</code> objects, it's not possible to grab content from a different domain. So I thought <em>iFrame</em> - even though I'm not a fan of frames, I thought that I could create a frame that matched the width and height of the content so that it would appear native. Again, I was blocked by cross-site scripting "protections." While I could indeed load a remote file into the <em>iFrame</em>, I couldn't execute JavaScript to modify its size on either the host page or inside the loaded page.</p> <p>In this particular scenario, I wasn't able to point a subdomain to my server. <strong>I also couldn't create a script on the CMS server that could proxy content from my server, so my last thought was to use a remote JavaScript.</strong></p> <p>A remote JavaScript works. It breaks when the user has JavaScript disabled, which is a downside; but it works. The "problem" I was having with using a remote JavaScript was that I had to use the JS function <code>document.write()</code> to output any content. Any output that isn't JS causes script errors. In addition to using <code>document.write()</code> for every line, you also have to ensure that the content is escaped - or else you end up with more script errors.</p> <p>My solution was as follows:</p> <p>My script received a GET parameter ("page") and then looked for the file (<code>{$page}.php</code>), and read the contents into a variable. However, I had to use awkward buffering techniques in order to actually execute the included scripts (for things like database interaction) then strip the final content of all line break characters (<code>\n</code>) followed by escaping all required characters. The end result is that my original script (which outputs JavaScript) accesses seemingly "standard" scripts on my server and converts their standard output to JavaScript for displaying within the CMS template.</p> <p>While this solution works, it seems like there may be a better way to accomplish the same thing. What is the best way to make cross-site scripting work specifically for the purpose of including content from a completely different domain?</p>
<p>You've got three choices:</p> <ol> <li>Create a <a href="http://developer.yahoo.com/javascript/howto-proxy.html" rel="noreferrer">server side proxy script</a>.</li> <li><p>Create a remote script to read in remote dynamic HTML. Use a library like <a href="http://www.jquery.com" rel="noreferrer">jQuery</a> to make this easier. You can use the <a href="http://docs.jquery.com/Ajax/load" rel="noreferrer">load function</a> to inject HTML where needed. <strong>EDIT</strong> What I originally meant for example # 2 was utilizing <a href="http://en.wikipedia.org/wiki/JSON#JSONP" rel="noreferrer">JSONP</a>, which requires the server side script to recognize the "callback=?" param.</p></li> <li><p>Use a <a href="http://www.adobe.com/devnet/flash/articles/external_interface.html" rel="noreferrer">client side Flash proxy</a> and setup a <a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14213" rel="noreferrer">crossdomain.xml</a> file on your server's web root.</p></li> </ol>
<p>I've come across that <a href="http://developer.yahoo.com/javascript/howto-proxy.html" rel="nofollow noreferrer">YDN server side proxy script</a> before. It says it's built to work with Yahoo's Search APIs. </p> <p>Will it work with any domain, if you simply trim the Yahoo API code out? Or do you need to replace it with the domain you want it to work with?</p>
7,588
<p>When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors?</p>
<p>Not sure what your level of expertise is, but here are the basics. </p> <p>Below is a linker error from VS 2005 - yes, it's a giant mess if you're not familiar with it.</p> <pre><code>ByteComparator.obj : error LNK2019: unresolved external symbol "int __cdecl does_not_exist(void)" (?does_not_exist@@YAHXZ) referenced in function "void __cdecl TextScan(struct FileTextStats &amp;,char const *,char const *,bool,bool,__int64)" (?TextScan@@YAXAAUFileTextStats@@PBD1_N2_J@Z) </code></pre> <p>There are a couple of points to focus on: </p> <ul> <li>"ByteComparator.obj" - Look for a ByteComparator.cpp file, this is the source of the linker problem</li> <li>"int __cdecl does_not_exist(void)" - This is the symbol it couldn't find, in this case a function named does_not_exist()</li> </ul> <p>At this point, in many cases the fastest way to resolution is to search the code base for this function and find where the implementation is. Once you know where the function is implemented you just have to make sure the two places get linked together.</p> <p>If you're using VS2005, you would use the "Project Dependencies..." right-click menu. If you're using gcc, you would look in your makefiles for the executable generation step (gcc called with a bunch of .o files) and add the missing .o file.</p> <hr> <p>In a second scenario, you may be missing an "external" dependency, which you don't have code for. The Win32 libraries are often times implemented in static libraries that you have to link to. In this case, go to <a href="http://msdn.microsoft.com/en-us/default.aspx" rel="noreferrer">MSDN</a> or <a href="http://www.google.com/microsoft" rel="noreferrer">"Microsoft Google"</a> and search for the API. At the bottom of the API description the library name is given. Add this to your project properties "Configuration Properties->Linker->Input->Additional Dependencies" list. For example, the function timeGetTime()'s <a href="http://msdn.microsoft.com/en-us/library/ms713418(VS.85).aspx" rel="noreferrer">page on MSDN</a> tells you to use Winmm.lib at the bottom of the page.</p>
<p>One of the common linking errors I've run into is when a function is used differently from how it's defined. If you see such an error you should make sure that every function you use is properly declared in some .h file.<br> You should also make sure that all the relevant source files are compiled into the same lib file. An error I've run into is when I have two sets of files compiled into two separate libraries, and I cross-call between libraries.</p> <p>Is there a failure you have in mind?</p>
5,535
<p>I want a method of the class: "<code>One</code>" ("<code>AccessibleWithinSameNamespace</code>") to be accessible by the class: "<code>Two</code>", without having "<code>Two</code>" extending "<code>One</code>".</p> <p>Both classes are in the same namespace, so I'm thinking that maybe there's an access-modifier that emulates the "<em>protected</em>" modifyer, but for namespaces.</p> <p>Some code:</p> <pre><code>namespace Test { class One { public void AccessibleToAll() { } protected void AccessibleWithinSameNamespace() { // I am not public // I can be accessed from other classes // within the same namespace of my class } } } namespace Test { class Two { public Two() { One one = new One(); // I am able to access this method because my class // is in the same namespace as the class: "One" one.AccessibleWithinSameNamespace(); } } } </code></pre>
<p>You can use the <a href="http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx" rel="nofollow noreferrer">internal</a> modifier if both classes are in the same assembly.</p> <p>With your example:</p> <pre><code>namespace Test { class One { public void AccessibleToAll() { } internal void AccessibleWithinSameNamespace() { // I am not public // I can be accessed from other classes // within the same namespace of my class } } } namespace Test { class Two { public Two() { One one = new One(); // I am able to access this method because my class // is in the same namespace as the class: "One" one.AccessibleWithinSameNamespace(); } } } </code></pre>
<p>C# and .NET have no concept of "within the same namespace". Internal is the closest equivalent.</p>
27,064
<p>I need to invoke a c# application within my c# control, as I do not feel like rewriting the application as a control. </p> <p>I am able to launch the application using System.Diagnostics.Process.Start.</p> <p>Now how do I call the methods in my application from/via the c# control as this is where I invoked the application using System.Diagnostics.Process.Start</p>
<p>The easiest way is to change the application from .exe to .dll and then just reference the application in your project like a normal library.</p>
<p>You can't call "methods" of another process because its running in an entirely different OS process. You would have to essentially ask the process to execute a method for you, wait for the result, and then marshall the information back into your process. Of course, you would have to have to expose the methods through some kind of interprocess communication technology like WCF, COM+, etc. If you've got that kind of access to the executing program, you can also just use the assembly directly. </p> <p>You really don't want to go through that if you can help it. It's going to be a lot more hassle.</p>
30,827
<p>I thought this was asked before, but 15 minutes of searching on Google and the site search didn't turn anything up...so:</p> <p>Where can I obtain free (as in beer and/or as in speech) dictionary files? I'm mainly interested in English, but if you know of any dictionary files, please point them out.</p> <p>Note: This question doesn't have a right/wrong answer, so I made it community-wiki. However, I feel that it might be valuable to not only myself, but anyone who wishes to implement or use a spell checker with various dictionary files.</p>
<p>I have found a <a href="http://wordlist.sourceforge.net/" rel="nofollow noreferrer">SourceForge project called Word List</a>, which appears to have a number of dictionaries. I have downloaded a couple and am currently checking them out.</p>
<p>I don't know what your target platform is but here is a solution that is for VB.NET. It uses the Office libraries which Office in itself isn't free but if your users are all internal and have Office then you could leverage these libs. There is a zip file with the example source code you can download as well.</p> <p><a href="http://www.devcity.net/PrintArticle.aspx?ArticleID=89" rel="nofollow noreferrer" title="DevCity Spellcheck">Check spelling and grammar</a></p>
32,358
<p>How can I split long commands over multiple lines in a batch file?</p>
<p>You can break up long lines with the caret <code>^</code> as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. <em>(<a href="https://stackoverflow.com/a/21000752/157247">More on that below.</a>)</em></p> <p>Example:</p> <pre><code>copy file1.txt file2.txt </code></pre> <p>would be written as:</p> <pre><code>copy file1.txt^ file2.txt </code></pre>
<p>Though the carret will be preferable way to do this here's one more approach using macro that constructs a command by the passed arguments:</p> <pre><code>@echo off :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: set &quot;{{=setlocal enableDelayedExpansion&amp;for %%a in (&quot; &amp; set &quot;}}=&quot;::end::&quot; ) do if &quot;%%~a&quot; neq &quot;::end::&quot; (set command=!command! %%a) else (call !command! &amp; endlocal)&quot; ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: %{{% echo &quot;command&quot; written on a few lines %}}% </code></pre> <p>command is easier to read without the carets but using special symbols e.g. brackets,redirection and so on will break it. So you can this for more simpler cases. Though you can still enclose parameters in double quotes</p>
9,452
<p>How do I check the type of a value on runtime?</p> <p>I'd like to find out where I'm creating doubles.</p>
<p>If you're using Objective-C classes, then the <code>[myObject isKindOfClass: [InterestingClass class]]</code> test is available. If you're using primitive types (which your question, quoting the "double" type, suggests), then you can't. However unless you're doing some very funky stuff, the compiler can tell you when primitive types do or don't match up, and when it doesn't will perform implicit promotion to the desired type.</p> <p>It would be beneficial to know a little more about what the specific problem is that you're trying to solve, because it may be that the solution doesn't involve detecting the creation of doubles at all :-).</p>
<p>With very few exceptions, you never need to check type at runtime. Typed variables can only hold their assigned types, and type promotion is determined at compile time.</p>
46,197
<p>I am trying to write a unix command line utility that will extract the "application" icon from a Windows Mobile executable. When I look inside the .exe with <a href="http://www.nongnu.org/icoutils/" rel="nofollow noreferrer">wrestool</a> from the icoutils package, I see multiple icon and group_icon resources. I am trying to figure out which icon the Windows Mobile Programs view would choose to display to the end user.</p> <p>At first, I figured it would be the icon with name 32512 (IDI_APPLICATION), but then I found several Windows Mobile binaries that lacked this icon resource, but sure enough had visible icons in the Programs view.</p> <p>Is there a simple but correct algorithm? like lowest resource id? Is there another resource in the .exe that tells me what is the application icon? Is there something obvious that I am missing?</p> <p>Any insight would be appreciated.</p>
<p>MySQL doesn't support milliseconds in any of the time / date columns, or return it in <code>NOW()</code> so unfortunately, no.</p> <p>If you have a string in a date / time + microseconds format you can use <code>SELECT MICROSECOND('1997-12-31 23:59:59.000010');</code> to extract the microseconds.</p>
<p>Just wanted to share it since I recently needed milliseconds for a MySQL project as well.</p> <p>You can write a UDF - <a href="http://dev.mysql.com/doc/refman/5.5/en/adding-udf.html" rel="nofollow noreferrer">User Defined Function</a> - to get you the system time down to a fairly small fraction of a second:</p> <p><img src="https://i.stack.imgur.com/bqIKP.png" alt="enter image description here"></p> <p>You can grab the sourcecode, as well as the pre-compiled binary <a href="https://github.com/CarnotInteractive/MySQL-udf-microtime" rel="nofollow noreferrer">here on github</a>.</p>
40,164
<p>I've noticed that a few Wordpress blogs have query statistics present in their footer that simply state the number of queries and the total time required to process them for the particular page, reading something like:</p> <blockquote> <p>23 queries. 0.448 seconds</p> </blockquote> <p>I was wondering how this is accomplished. Is it through the use of a particular Wordpress plug-in or perhaps from using some particular php function in the page's code?</p>
<p>Try adding this to the bottom of the footer in your template:</p> <pre><code>&lt;?php echo $wpdb-&gt;num_queries; ?&gt; &lt;?php _e('queries'); ?&gt;. &lt;?php timer_stop(1); ?&gt; &lt;?php _e('seconds'); ?&gt; </code></pre>
<p>wordpress has a easy solution now</p> <p>There is a function called <a href="http://codex.wordpress.org/Function_Reference/get_num_queries" rel="nofollow"><code>get_num_queries()</code></a> and as specified in other answers <a href="http://codex.wordpress.org/Function_Reference/timer_stop" rel="nofollow"><code>timer_stop()</code></a>.</p> <pre><code>&lt;?php echo get_num_queries(); _e(' queries'); ?&gt; in &lt;?php timer_stop(1); _e(' seconds'); ?&gt;&lt;/p&gt; </code></pre> <p><code>get_num_queries()</code> - returns the number of database queries during the WordPress execution and accepts no parameters </p>
3,565
<p>I'd like to make it easy for users to forward a port on their NAT to their local machine for my C++ app. I'd like to make this work on OSX &amp; Windows. Linux would be a great bonus, but Linux users are probably more comfortable forwarding ports manually, so it is less of a concern. LGPL type code is OK, but I can't use anything that is straight GPL. </p> <p>I'd love to hear any thoughts or experiences anyone has had in this area, but a few specific questions come to mind:</p> <ul> <li>Is there a recognized best library for UPNP? The <a href="http://miniupnp.free.fr/" rel="noreferrer">MiniUPNP</a> client looks like it might work, but is there anything else out there? </li> <li>What about <a href="http://en.wikipedia.org/wiki/Bonjour_(software)" rel="noreferrer">Bonjour</a>? Can I rely on it for OSX computers? </li> <li>All the big bittorrent apps have to deal with this, so is there an existing survey of how they do it? What about Skype? </li> </ul>
<p>MiniUPNP is used by at least one bittorrent client (Transmission) and should work fine.</p>
<p>Bonjour on both OS X and Windows can be used to do port mappings with routers that support uPNP or NAT-PMP. I haven't used the <a href="http://developer.apple.com/DOCUMENTATION/Networking/Reference/DNSServiceDiscovery_CRef/dns_sd/CompositePage.html#//apple_ref/c/func/DNSServiceNATPortMappingCreate" rel="nofollow noreferrer">API (DNSServiceNATPortMappingCreate)</a> but I have successfully published wide-area services on both Windows and OS X behind a NAT-PMP router. I'm not sure if your Windows users will want to install Bonjour (although they may already have it if they use iTunes or Safari) to use your app but on OS X support shouldn't be an issue. </p>
19,786
<p>The second question is: When do I use what of these two?</p>
<p>When not specified, C++ is unmanaged C++, compiled to machine code. In unmanaged C++ you must manage memory allocation manually.</p> <p>Managed C++ is a language invented by Microsoft, that compiles to bytecode run by the .NET Framework. It uses mostly the same syntax as C++ (hence the name) but is compiled in the same way as C# or VB.NET; basically only the syntax changes, e.g. using '->' to point to a member of an object (instead of '.' in C#), using '::' for namespaces, etc.</p> <p>Managed C++ was made to ease transition from classic C++ to the .NET Framework. It is not intended to be used to start new projects (C# is preferred).</p>
<p>Managed C++ means that memory allocation, management, garbage collection is handled by the virtual machine. Whereas in "regular" C++ you would have to allocate and deallocate memory.</p>
13,953
<p>When trying to link some well established tools to my company's active directory, I hit a roadblock. I was told that:</p> <blockquote> <p>"Sorry, I cannot trust our domain admin password to [F/OSS] software...".</p> </blockquote> <p>This question deals specifically with <strong>how to convince IT that F/OSS software isn't (automatically) less trustworthy than any other software just because it's free/oss</strong>. </p> <p>I'm doing fine with adopting OSS software (I'm a linux ninja at heart) so to put it another way: <strong>How can I promote the <em>acceptance</em> of OSS at my company?</strong></p> <p>The technical issue of tying into AD without an admin account is for another post.</p> <hr> <p><strong>EDIT:</strong></p> <p>I got some clarification on these issues. This really has little to do with the active directory and all to do with trust of F/OSS in general. So I think my original bolded questions are still valid, just ignore the part about the "admin password".</p>
<p>Any IT person worth their salt will be well aware of the benefits of open source software.</p> <p>The answer that has been given sounds to me like a palm off answer, some possibilities of why they don't want to implement it could be:</p> <ul> <li>Possible lack of enterprise level support for that specific software open source software</li> <li>Not wanting non-IT department employees to be modifying the active directory (you)</li> <li>The software you have found doesn't have the industry recognition that other similar products have</li> <li>There is no perceived benefit for the IT department for the work it would require them to do (both in the initial setup and ongoing maintenance)</li> </ul>
<p>You're talking about Windows admins. Just point out how MSFT has handled recent security issues (like the recent IE holes that have mainstream media telling people to use alternate browsers) and ask how OSS can be any worse.</p>
49,167
<p>Is it possible to close parent window in Firefox 2.0 using JavaScript. I have a parent page which opens another window, i need to close the parent window after say 10 seconds. I have tried Firefox tweaks "dom.allow_scripts_to_close_windows", tried delay but nothing seems to work.</p> <p>Any help will be really appreciated.</p> <p>Thanks</p>
<p>Scissored from <a href="http://www.quirksmode.org/js/croswin.html" rel="nofollow noreferrer">quirksmode</a> (EDIT: added a bit of context, as suggested by Diodeus):</p> <p>Theoretically</p> <pre><code>opener.close() </code></pre> <p>should be the code from the popup: close the window that has opened this popup.</p> <p>However, in some browsers it is not allowed to automatically close windows that have not been opened by JavaScript. The line above works fine in Explorer on Mac, Mozilla, Opera and OmniWeb, but not in Explorer on Windows, Netscape 4 and lower and iCab. In these browsers the user is asked to confirm the closing of the window. As to Safari, it does absolutely nothing.</p> <p>Rather to my surprise it's very easy to get around this confirm box in Explorer 5.5 and 6 on Windows. Explorer merely looks if the page has an opener. If it doesn't the window has been opened by the user and may not be closed without a confirm. So what we need to do is trick Explorer into thinking the opening page has an opener:</p> <pre><code>opener.opener = top; // or whatever, as long as opener.opener has a value; opener.close() </code></pre> <p>This trick doesn't work in Netscape 4 and lower and iCab, these browsers have more sophisticated ways to determine whether a window has been opened by JavaScript.</p>
<p>Generally, you can't close a window which you didn't open yourself using javascript.</p>
44,708
<p>I'm trying to configure an ejabberd installation, using LDAP authentication, but I just can't login, even with the admin user. This is part of my ejabberd.cfg file:</p> <pre><code>%... {auth_method, ldap}. {ldap_servers, ["server2000.tek2000.local"]}. {ldap_port,389}. {ldap_uidattr, "uid"}. {ldap_base, "dc=server2000,dc=tek2000,dc=com"}. {ldap_rootdn, "tempadm@tek2000.local"}. {ldap_password, "secret"}. %... </code></pre> <p>What am I missing?</p> <p>I must say that, with OpenFire, I can connect using this credentials/configuration.</p> <p>I'm using Spark as my client application.</p> <p>Thanks</p>
<p>Use a <a href="http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html" rel="noreferrer">ByteArrayOutputStream</a> and then get the data out of that using <a href="http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html#toByteArray()" rel="noreferrer">toByteArray()</a>. This won't test <em>how</em> it writes to the stream (one byte at a time or as a big buffer) but usually you shouldn't care about that anyway.</p>
<p>If you can pass a Writer to XmlWriter, I would pass it a <code>StringWriter</code>. You can query the <code>StringWriter</code>'s contents using <code>toString()</code> on it.</p> <p>If you have to pass an <code>OutputStream</code>, you can pass a <code>ByteArrayOutputStream</code> and you can also call <code>toString()</code> on it to get its contents as a String.</p> <p>Then you can code something like:</p> <pre><code>public void testSomething() { Writer sw = new StringWriter(); XmlWriter xw = new XmlWriter(sw); ... xw.writeString("foo"); ... assertEquals("...&lt;aTag&gt;foo&lt;/aTag&gt;...", sw.toString()); } </code></pre>
27,820
<p>I'm supposed to learn how to use <a href="http://www.ni.com/labview/" rel="nofollow noreferrer">LabVIEW</a> for my new job, and I'm wondering if anybody can recommend some good books or reference/tutorial web sites.</p> <p>I'm a senior developer with lots of Java/C#/C++ experience.</p> <p>I realize that this question is perhaps more vague than is intended on stack overflow, so how about this? Please answer with one book or web site and a brief description. Then people can vote up their favourites.</p>
<p><strong>It will take some <em>training</em> and some <em>time</em> to learn the style needed to develop maintainable code</strong>.</p> <p>Coming from Java/C#/C++, you probably have a good idea of good software architecture. Now you just need to learn the peculiarities of LabView and the common pitfalls.</p> <p>For the basics, National Instruments offers <a href="http://www.ni.com/training/" rel="nofollow noreferrer">training courses</a>. See if your new employer can send you to a Basics I/II class to get your feet wet. They offer some online classes as well. Following classes, you can sign up to take tests for certification.</p> <p>Get an <a href="http://www.ni.com/labview/try/daq.htm" rel="nofollow noreferrer">evaluation copy</a> of Labview from National Instruments; they have a well maintained help file that you can dive right into, with example code included. Look at "Getting Started" and "LabVIEW Environment". You should be able to jump right in and become familiar with the dev environment pretty quickly.</p> <p>LabVIEW, being graphical is nice, but don't throw out your best practices from an application design point of view. It is common to end up with code looking like rainbow sphaghetti, or code that stretches several screens wide. Use subvi's and keep each vi with a specific purpose and function. </p> <p>The official NI support forums and knowledgebase are probably the best resources out there at the moment.</p> <p>Unofficial sites like <a href="http://www.cipce.rpi.edu/programs/remote_experiment/labview/" rel="nofollow noreferrer">Tutorials in G</a> have a subset of the information found on the official site and documentation, but still may be useful for cross reference if you get stuck.</p> <p><strong>Edit:</strong> <a href="http://sine.ni.com/nips/cds/view/p/lang/en/nid/2241" rel="nofollow noreferrer">Basics I/II</a> are designed to be accessible to users without prior software development experience. Depending on how you feel after using the evaluation version, you may be able to move directly into <a href="http://sine.ni.com/nips/cds/view/p/lang/en/nid/12769" rel="nofollow noreferrer">Intermediate I/II</a>. NI has the course outlines available on their website as well, so you know what you're going to cover in each.</p>
<p>When I started with LabVIEW a few years ago I was given a link to the <a href="http://cnx.rice.edu/content/col10241/latest/" rel="nofollow noreferrer">LabVIEW Graphical Programming Course</a>. It covers the basics and having a sound knowledge of other programming languages I think helped me pick things up quickly.</p>
6,912
<p>Do you know of any .NET library which can decode several types of audio files? Ideally, it should be platform agnostic, so it can be used with .NET and Mono - on Windows and *NIX.</p> <p>I already tortured Google searching for a library which meets my needs, but unfortunately I could not find anything. So before writing a lot of wrapper classes for GStreamer and friends, I thought I could ask here. :)</p> <p>Supported audio files should be (at least)</p> <ul> <li>MP3,</li> <li>OGG Vorbis, and</li> <li>FLAC (optional).</li> </ul> <p>As the application I would need this for is just for fun, the library should be open source - or at least free. Also, a nag screen displayed to a user would probably be bad or impractical, because I am planning on putting this into a service process.</p> <p>I would need use this library/these libraries in order to decoding audio files and passing a byte[] to my libOFA wrapper, so that I can produce a MusicDNS fingerprint for it. My experimental application would most likely run on a Linux based server.</p>
<p>There is the <a href="http://ffmpeg.mplayerhq.hu/" rel="nofollow noreferrer">ffmpeg</a> library and utilities that converts audio and video formats. Then, couple with the <a href="http://www.codeplex.com/ffmpegdotnet" rel="nofollow noreferrer">FFmpeg.NET</a> library, you can do the encoding/decoding in .NET. All the formats you mentioned are supported.</p>
<p>If you are talking about decoding the files to play them (i.e. for listening), I'd suggest jumping into the Windows Media Player SDK.</p> <p>It will play anything that has a codec installed and doesn't cost anything.</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa969732.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa969732.aspx</a></p> <p>If you want something closer to the metal (i.e. for learning), you might also check out the Windows Media Format SDK.</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa387410.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa387410.aspx</a></p>
17,360
<p>All I want is to be able to change the color of a bullet in a list to a light gray. It defaults to black, and I can't figure out how to change it.</p> <p>I know I could just use an image; I'd rather not do that if I can help it.</p>
<p>The bullet gets its color from the text. So if you want to have a different color bullet than text in your list you'll have to add some markup.</p> <p>Wrap the list text in a span:</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;span&gt;item #1&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;span&gt;item #2&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;span&gt;item #3&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Then modify your style rules slightly:</p> <pre><code>li { color: red; /* bullet color */ } li span { color: black; /* text color */ } </code></pre>
<p>You'll want to set a "list-style" via CSS, and give it a color: value. Example:</p> <pre><code>ul.colored {list-style: color: green;} </code></pre>
10,219
<p>Has anyone found a way to get around this? Or a better technique to conglomerate logging from multiple web servers reliably?</p> <p>Any ideas on good log4net log file analysis tools too (plain text not XML) - apart from good 'ol grep of course :)</p>
<p>The 1024 byte limit is part of the syslog <a href="http://www.ietf.org/rfc/rfc3164.txt" rel="nofollow noreferrer">RFC</a> (section 4.1), as is UDP transport which doesn't have guaranteed delivery (in case you worry about log lines lost in the ether). I think syslog-ng can solve both these issues, but I'm not a syslog expert.</p>
<p>The limitation is imposed by the syslog itself, not the appender.</p> <p>I do not know about log4net, but <a href="http://www.nlog-project.org/" rel="nofollow noreferrer">NLog</a> works perfectly ok with "shared" file target - i.e. multiple processes can write in one and the same <a href="http://www.nlog-project.org/target.File.html" rel="nofollow noreferrer">file</a>.</p>
10,951
<p>I have a working LINQ to SQL model. I want to be able to use the same model but with a connection to a DataSet object, instead of SQL Server.</p> <p>I need to be able to query the model, modify fields, as well as do insert and delete operations. Is there an easy way to accomplish this?</p> <p>I noticed <a href="https://stackoverflow.com/questions/142762/is-there-a-datacontext-in-linq-to-entities-not-linq-to-sql">another question</a> mentions a similar scenario, but I'm not sure if this applies to my question.</p>
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/bb386977.aspx" rel="nofollow noreferrer">LINQ to DataSet</a> directly but the LINQ to SQL query translator converts expression trees into SQL statements and that can't be changed.</p> <p>For lists of inserts/updates/deletes for a given DataContext, you can call <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.getchangeset.aspx" rel="nofollow noreferrer"><strong><code>DataContext.GetChangeSet()</code></strong></a></p>
<p>You want a DataContext that is backed by a DataSet. No, this does not exist unless you build it.</p>
19,174
<p>I would like to enable/disable some code based on a custom solution configuration I added in Visual Studio. How do I check this value at runtime?</p>
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx" rel="noreferrer">precompiler directives</a> within Visual Studio. The #if directive will allow you to determine if you are going to include code or not based on your custom solution configuration.</p>
<p>I'm not sure if you can figure out the exact name of the build configuration. Howerver, if you use Debug.Assert(...), that code will only be run when you compile in debug mode. Not sure it that helps you at all.</p>
5,144
<p>Microsoft's new <a href="http://msdn.microsoft.com/en-us/library/cc305108.aspx" rel="nofollow noreferrer">Windows Live Application Based Storage API</a> is a RESTful API.</p> <p>More info is <a href="http://msdn.microsoft.com/en-us/library/cc305108.aspx" rel="nofollow noreferrer">here</a>.</p> <p>Why did they choose not to support WebDAV?</p>
<p>WebDAV is for managing files on a remote server, but perhaps is not generic enough for what Microsoft was trying to accomplish.</p> <p>There's also a lot of hype around REST lately and they are probably in competition with S3 from Amazon which offers a REST API.</p> <p>It would have been good of them to provide their RESTful API as well as WebDAV.</p>
<p>Im been using WebDav on some other project like android and see all kind of scenario compare from REST Api.</p> <p>Using WebDav, when you had multiple files like 5 thousand files or more and getting there value from the webdav server, open the file take time because of streaming or reading each of them, using REST Api in one content for all records in good format of json is faster than webdav.</p>
31,877
<p>When an Event is triggered by a user in IE, it is set to the <code>window.event</code> object. The only way to see what triggered the event is by accessing the <code>window.event</code> object (as far as I know)</p> <p>This causes a problem in ASP.NET validators if an event is triggered programmatically, like when triggering an event through jQuery. In this case, the <code>window.event</code> object stores the last user-triggered event.</p> <p>When the <code>onchange</code> event is fired programmatically for a text box that has an ASP.NET validator attached to it, the validation breaks because it is looking at the element that fired last event, which is not the element the validator is for.</p> <p>Does anyone know a way around this? It seems like a problem that is solvable, but from looking online, most people just find ways to ignore the problem instead of solving it.</p> <hr> <p><strong>To explain what I'm doing specifically:</strong><br> I'm using a jQuery time picker plugin on a text box that also has 2 ASP.NET validators associated with it. When the time is changed, I'm using an update panel to post back to the server to do some things dynamically, so I need the onchange event to fire in order to trigger the postback for that text box.</p> <p>The jQuery time picker operates by creating a hidden unordered list that is made visible when the text box is clicked. When one of the list items is clicked, the "change" event is fired programmatically for the text box through jQuery's <code>change()</code> method.</p> <p>Because the trigger for the event was a list item, IE sees the <em>list item</em> as the source of the event, not the text box, like it should.</p> <p>I'm not too concerned with this ASP.NET validator working as soon as the text box is changed, I just need the "<code>change</code>" event to be processed so my postback event is called for the text box. The problem is that the validator throws an exception in IE which stops any event from being triggered.</p> <p>Firefox (and I assume other browsers) don't have this issue. Only IE due to the different event model. Has anyone encountered this and seen how to fix it?</p> <hr> <p>I've found this problem reported several other places, but they offer no solutions: </p> <ul> <li><a href="http://groups.google.com/group/jquery-en/browse_thread/thread/a8902f2774edc05a/d119026f561ca528?lnk=raot" rel="noreferrer">jQuery's forum, with the jQuery UI Datepicker and an ASP.NET Validator</a></li> <li><a href="http://forums.asp.net/t/1326208.aspx" rel="noreferrer">ASP.NET forums, bug with ValidatorOnChange() function</a></li> </ul>
<p>I had the same problem. Solved by using this function:</p> <pre><code>jQuery.fn.extend({ fire: function(evttype){ el = this.get(0); if (document.createEvent) { var evt = document.createEvent('HTMLEvents'); evt.initEvent(evttype, false, false); el.dispatchEvent(evt); } else if (document.createEventObject) { el.fireEvent('on' + evttype); } return this; } }); </code></pre> <p>So my "onSelect" event handler to datepicker looks like:</p> <pre><code>if ($.browser.msie) { datepickerOptions = $.extend(datepickerOptions, { onSelect: function(){ $(this).fire("change").blur(); } }); } </code></pre>
<p>This is how I solved a simlar issue. Wrote an onSelect() handler for the datepicker. <a href="http://docs.jquery.com/UI/Datepicker/datepicker#options" rel="nofollow noreferrer">link text</a> In that function, called __doPostBack('textboxcontrolid',''). This triggered a partial postback for the textbox to the server, which called the validators in turn.</p>
20,355
<p>In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?</p>
<pre><code>using System.Configuration; Configuration config = ConfigurationManager.OpenExeConfiguration("C:\Test.exe"); </code></pre> <p>You can then access the app settings, connection strings, etc from the config instance. This assumes of course that the config file is properly formatted and your app has read access to the directory. Notice the path is <strong><em>not</em></strong> "C:\Test.exe.config" The method looks for a config file associated with the file you specify. If you specify "C:\Test.exe.config" it will look for "C:\Test.exe.config.config" Kinda lame, but understandable, I guess.</p> <p>Reference here: <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx</a></p>
<pre><code>AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ConfigurationFile = @"D:\Mine\Company\"; string browserName = ConfigurationManager.AppSettings["browser"]; </code></pre>
10,163
<p>Quite often in ANSI C code I can see parenthesis sorrounding a single return value. </p> <p>Like this:-</p> <pre><code>int foo(int x) { if (x) return (-1); else return (0); } </code></pre> <p>Why use () around the return value in those cases? Any ideas? I can see no reason for that.</p>
<p>There really isn't a reason...it's just old convention.</p> <p>To save space, programmers would often do the final math in the return line instead of on it's own line and the parens ensure are mostly there to make it easier to see that it is a single statement that is returned, like this:</p> <pre><code>return (x+i*2); </code></pre> <p>instead of</p> <pre><code>int y = x+i*2; return y; </code></pre> <p>The parenthesis became a habit and it stuck.</p>
<p>Using parentheses in a return statement shows a deficient grasp of <code>C/C++</code> syntax. It's as simple as that. But it's not as bad as putting everything in curly braces:</p> <pre><code>int foo(int x) { if (x) { return (-1); } else { return (0); } } </code></pre> <p>So many programmers do this. If one of you reads this, perhaps you might like to explain.</p>
19,575
<p>I have windows 2003 terminal servers, multi-core. I'm looking for a way to monitor individual CPU core usage on these servers. It is possible for an end-user to have a run-away process (e.g. Internet Explorer or Outlook). The core for that process may spike to near 100% leaving the other cores 'normal'. Thus, the overall CPU usage on the server is just the total of all the cores or if 7 of the cores on a 8 core server are idle and the 8th is running at 100% then 1/8 = 12.5% usage.</p> <p>What utility can I use to monitor multiple servers ? If the CPU usage for a core is "high" what would I use to determine the offending process and then how could I automatically kill that process if it was on the 'approved kill process' list?</p> <p>A product from <a href="http://www.packettrap.com/" rel="nofollow noreferrer">http://www.packettrap.com/</a> called PT360 would be perfect except they use SMNP to get data and SMNP appears to only give total CPU usage, it's not broken out by an individual core. Take a look at their Dashboard option with the CPU gauge 'gadget'. That's exactly what I need if only it worked at the core level.</p> <p>Any ideas?</p>
<p>Individual CPU usage is available through the standard windows performance counters. You can monitor this in perfmon.</p> <p>However, it won't give you the result you are looking for. Unless a thread/process has been explicitly bound to a single CPU then a run-away process will not spike one core to 100% while all the others idle. The run-away process will bounce around between all the processors. I don't know why windows schedules threads this way, presumably because there is no gain from forcing affinity and some loss due to having to handle interrupts on particular cores.</p> <p>You can see this easily enough just in task manager. Watch the individual CPU graphs when you have a single compute bound process running.</p>
<p>perfmon from Microsoft can monitor each individual CPU. perfmon also works remote and you can monitor farious aspects of Windows.</p> <p>I'm not sure if it helps to find run-away processes because the Windows scheduler dos not execute a process always on the same CPU -> on your 8 CPU machine you will see 12.5 % usage on all CPU's if one process runs away.</p>
7,051
<p>When I changed the rankdir of my graph from LR to TD, my record nodes also changed their layout direction so they no longer look like a 'record'. I tried applying a separate rankdir to the nodes, but this had no effect.</p> <p>How does one keep the record nodes with the correct layout?</p> <pre><code>digraph sample { graph [rankdir=TD]; node [shape=record]; A [label="ShouldBeTop | ShouldBeBottom"]; B [label="Top | Bottom"]; A -&gt; B; } </code></pre>
<p>Taking into account that rankdir effectively replaces the notion of "top" and "bottom" for the given graph, that's not surprising. </p> <p>I am afraid that there is no easy remedy for this, save hacking the source (and that would not be easy at all). You can surround your labels in "{}" with some kind of mass search-replace solution to get the requested effect:</p> <pre><code>digraph sample { graph [rankdir=TD]; node [shape=record]; A [label="{ShouldBeTop | ShouldBeBottom}"]; B [label="{Top | Bottom}"]; A -&gt; B; } </code></pre>
<p>You can use html table like labels instead of records. IIRC the table based labels do not rotate with the rank direction. See <a href="http://www.graphviz.org/doc/info/shapes.html#html" rel="noreferrer">http://www.graphviz.org/doc/info/shapes.html#html</a></p>
32,408
<p>I'm trying to learn about Expression trees, and I've created a method that takes an</p> <pre><code>Expression&lt;Func&lt;bool&gt;&gt; </code></pre> <p>and executes it if it satisfies some conditions - see the code below.</p> <pre><code> private static void TryCommand(Expression&lt;Func&lt;bool&gt;&gt; expression) { var methodCallExpression = expression.Body as MethodCallExpression; if (methodCallExpression == null) { throw new ArgumentException("expression must be a MethodCallExpression."); } if (methodCallExpression.Object.Type != typeof (MyClass)) { throw new ArgumentException("expression must be operating on an instanceof MyClass."); } var func = expression.Compile(); var success = func.Invoke(); if(!success) { Console.WriteLine(methodCallExpression.Method.Name + "() failed with error code " + (func.Target as MyClass).GetError()); } } </code></pre> <p>The problem that</p> <pre><code>(func.Target as MyClass) </code></pre> <p>is null. Clearly I'm doing something wrong! How do I access the instance that the method is operating on?</p>
<p>The target of the method call is an instance of MyClass, but the delegate itself isn't the method call. It's something which will perform the method call when it's executed.</p> <p>If you look at func.Target, you'll see it's a <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.executionscope.aspx" rel="nofollow noreferrer">System.Runtime.CompilerServices.ExecutionScope</a>.</p> <p>Now you <em>could</em> test for that, cast to it, and then fetch either the Locals or the Globals (not sure which) to get the target. However, I suspect it would be cleaner just to change to use a <code>Func&lt;int&gt;</code> (or whatever type your error code is) and return the error code when you execute the delegate in the first place. Then you wouldn't even need an expression tree.</p> <p>EDIT: Given your comments, I'd suggest:</p> <pre><code>public static void TryCommand(Expression&lt;Func&lt;MyClass,bool&gt;&gt; command, MyClass c) { // Code as before to find the method name etc. Func&lt;MyClass, bool&gt; compiled = command.Compile(); if (!compiled(c)) { Console.WriteLine(methodCallExpression.Method.Name + "() failed with error code " + c.GetError()); } } </code></pre> <p>You'd then call it with:</p> <pre><code>TryCommand(x =&gt; x.SomeMethod(), myClass); </code></pre>
<p>The target is null because the method is static. In reflection Invoke(..) on a static MethodInfo will ignore the target. This is likely an extension method, in which case the first argument is the inferred target.</p> <p>Since most of LINQ is based on extension methods you'll see this quite often going forward with reflection.</p>
44,245
<p>I am currently using Windows Server 2008 Standard and have several Hyper V machines. These are development VM's and I want to now switch back Vista x64 because I am missing Aero.</p> <p>I know Windows Server 2008 can have aero but the host performance is very very bad when I run VM in Hyper V.</p> <p>I want to export my Hyper V machines so that I can use it in Virtual PC. Anyone know an easy way?</p>
<p>VPC to Hyper-V is one way.</p>
<p>You should review Windows 2008 R2 SP1 upgrade with RemoteFX, it comes with a new video driver for VM's that allow 3D, extended desktops and more. It will help resolve some of the issues you are seeing today.</p> <p>Both the Host server and VM need to be running SP1 of Windows 2008 R2.</p> <p><a href="http://blogs.technet.com/b/virtualization/archive/2010/03/18/explaining-microsoft-remotefx.aspx" rel="nofollow">http://blogs.technet.com/b/virtualization/archive/2010/03/18/explaining-microsoft-remotefx.aspx</a></p>
6,477
<p>We need to programatically burn files to CD in a C\C++ Windows XP/Vista application we are developing using Borlands Turbo C++.</p> <p>What is the simplest and best way to do this? We would prefer a native windows API (that doesnt rely on MFC) so as not to rely on any third party software/drivers if one is available.</p>
<p>We used the following: </p> <p>Store files in the directory returned by GetBurnPath, then write using Burn. GetCDRecordableInfo is used to check when the CD is ready.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;imapi.h&gt; #include &lt;windows.h&gt; struct MEDIAINFO { BYTE nSessions; BYTE nLastTrack; ULONG nStartAddress; ULONG nNextWritable; ULONG nFreeBlocks; }; //============================================================================== // Description: CD burning on Windows XP //============================================================================== #define CSIDL_CDBURN_AREA 0x003b SHSTDAPI_(BOOL) SHGetSpecialFolderPathA(HWND hwnd, LPSTR pszPath, int csidl, BOOL fCreate); SHSTDAPI_(BOOL) SHGetSpecialFolderPathW(HWND hwnd, LPWSTR pszPath, int csidl, BOOL fCreate); #ifdef UNICODE #define SHGetSpecialFolderPath SHGetSpecialFolderPathW #else #define SHGetSpecialFolderPath SHGetSpecialFolderPathA #endif //============================================================================== // Interface IDiscMaster const IID IID_IDiscMaster = {0x520CCA62,0x51A5,0x11D3,{0x91,0x44,0x00,0x10,0x4B,0xA1,0x1C,0x5E}}; const CLSID CLSID_MSDiscMasterObj = {0x520CCA63,0x51A5,0x11D3,{0x91,0x44,0x00,0x10,0x4B,0xA1,0x1C,0x5E}}; typedef interface ICDBurn ICDBurn; // Interface ICDBurn const IID IID_ICDBurn = {0x3d73a659,0xe5d0,0x4d42,{0xaf,0xc0,0x51,0x21,0xba,0x42,0x5c,0x8d}}; const CLSID CLSID_CDBurn = {0xfbeb8a05,0xbeee,0x4442,{0x80,0x4e,0x40,0x9d,0x6c,0x45,0x15,0xe9}}; MIDL_INTERFACE("3d73a659-e5d0-4d42-afc0-5121ba425c8d") ICDBurn : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetRecorderDriveLetter( /* [size_is][out] */ LPWSTR pszDrive, /* [in] */ UINT cch) = 0; virtual HRESULT STDMETHODCALLTYPE Burn( /* [in] */ HWND hwnd) = 0; virtual HRESULT STDMETHODCALLTYPE HasRecordableDrive( /* [out] */ BOOL *pfHasRecorder) = 0; }; //============================================================================== // Description: Get burn pathname // Parameters: pathname - must be at least MAX_PATH in size // Returns: Non-zero for an error // Notes: CoInitialize(0) must be called once in application //============================================================================== int GetBurnPath(char *path) { ICDBurn* pICDBurn; int ret = 0; if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&amp;pICDBurn))) { BOOL flag; if (pICDBurn-&gt;HasRecordableDrive(&amp;flag) == S_OK) { if (SHGetSpecialFolderPath(0, path, CSIDL_CDBURN_AREA, 0)) { strcat(path, "\\"); } else { ret = 1; } } else { ret = 2; } pICDBurn-&gt;Release(); } else { ret = 3; } return ret; } //============================================================================== // Description: Get CD pathname // Parameters: pathname - must be at least 5 bytes in size // Returns: Non-zero for an error // Notes: CoInitialize(0) must be called once in application //============================================================================== int GetCDPath(char *path) { ICDBurn* pICDBurn; int ret = 0; if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&amp;pICDBurn))) { BOOL flag; WCHAR drive[5]; if (pICDBurn-&gt;GetRecorderDriveLetter(drive, 4) == S_OK) { sprintf(path, "%S", drive); } else { ret = 1; } pICDBurn-&gt;Release(); } else { ret = 3; } return ret; } //============================================================================== // Description: Burn CD // Parameters: None // Returns: Non-zero for an error // Notes: CoInitialize(0) must be called once in application //============================================================================== int Burn(void) { ICDBurn* pICDBurn; int ret = 0; if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&amp;pICDBurn))) { if (pICDBurn-&gt;Burn(NULL) != S_OK) { ret = 1; } pICDBurn-&gt;Release(); } else { ret = 2; } return ret; } //============================================================================== bool GetCDRecordableInfo(long *FreeSpaceSize) { bool Result = false; IDiscMaster *idm = NULL; IDiscRecorder *idr = NULL; IEnumDiscRecorders *pEnumDiscRecorders = NULL; ULONG cnt; long type; long mtype; long mflags; MEDIAINFO mi; try { CoCreateInstance(CLSID_MSDiscMasterObj, 0, CLSCTX_ALL, IID_IDiscMaster, (void**)&amp;idm); idm-&gt;Open(); idm-&gt;EnumDiscRecorders(&amp;pEnumDiscRecorders); pEnumDiscRecorders-&gt;Next(1, &amp;idr, &amp;cnt); pEnumDiscRecorders-&gt;Release(); idr-&gt;OpenExclusive(); idr-&gt;GetRecorderType(&amp;type); idr-&gt;QueryMediaType(&amp;mtype, &amp;mflags); idr-&gt;QueryMediaInfo(&amp;mi.nSessions, &amp;mi.nLastTrack, &amp;mi.nStartAddress, &amp;mi.nNextWritable, &amp;mi.nFreeBlocks); idr-&gt;Release(); idm-&gt;Close(); idm-&gt;Release(); Result = true; } catch (...) { Result = false; } if (Result == true) { Result = false; if (mtype == 0) { // No Media inserted Result = false; } else { if ((mflags &amp; 0x04) == 0x04) { // Writable Media Result = true; } else { Result = false; } if (Result == true) { *FreeSpaceSize = (mi.nFreeBlocks * 2048); } else { *FreeSpaceSize = 0; } } } return Result; } </code></pre>
<p>You should be able to use the shell's ICDBurn interface. Back in the XP day MFC didn't even have any classes for cd burning. I'll see if I can find some examples for you, but it's been a while since I looked at this.</p>
10,867