instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Omnicompletion is working, but it automatically inserts the first result.</p> <p>What I'd like to do is open the omnicomplete menu, then be able to type to narrow down the results, then hit enter or tab or space or something to insert the selected menu item.</p> <p>Is this possible?</p>
<p>The command you are looking for is:</p> <pre><code>:set completeopt+=longest </code></pre> <p>It will insert the longest common prefix of all the suggestions, then you can type and delete to narrow down or expand results.</p>
<p>This plugin might do what you are after: <strong><a href="http://www.vim.org/scripts/script.php?script_id=1879" rel="nofollow noreferrer">autocomplpop</a></strong></p> <p>Or you can try and make Vim completion popup menu <a href="http://vim.wikia.com/wiki/Make_Vim_completion_popup_menu_work_just_like_in_an_IDE" rel="nofollow noreferrer">work just like in an IDE</a>.</p>
40,011
<p>Anyone visiting a torrent tracker is sure to find droves of "cracked" programs ranging from simple shareware to software suites costing thousands of dollars. It seems that as long as the program does not rely on a remote service (e.g. an MMORPG) that any built-in copy protection or user authentication is useless.</p> <p>Is it effectively not possible to prevent a cracker from circumventing the copy protection? Why?</p>
<p>Copy-protection is like security -- it's impossible to achieve 100% perfection but you can add layers that make it successively more difficult to crack.</p> <p>Most applications have some point where they ask (themselves), "Is the license valid?" The hacker just needs to find that point and alter the compiled code to return "yes." Alternatively, crackers can use brute-force to try different license keys until one works. There's also social factors -- once one person buys the tool they might post a valid license code on the Internet.</p> <p>So, code obfuscation makes it more difficult (but not impossible) to find the code to alter. Digital signing of the binaries makes it more difficult to change the code, but still not impossible. Brute-force methods can be combated with long license codes with lots of error-correction bits. Social attacks can be mitigated by requiring a name, email, and phone number that is <em>part of the license code itself</em>. I've used that method to great effect.</p> <p>Good luck!</p>
<p>This is one occasion where quality software is a bad thing, because if no one whats your software then they will not spend time trying to crack it, on the other hand things like Adobe's Master Collection CS3, were available just days after release.</p> <p>So the moral of this story is if you don't want someone to steal your software there is one option: don't write anything worth stealing.</p>
24,864
<p>I'm using nhibernate to store some user settings for an app in a SQL Server Compact Edition table.</p> <p>This is an excerpt the mapping file:</p> <pre><code>&lt;property name="Name" type="string" /&gt; &lt;property name="Value" type="string" /&gt; </code></pre> <p>Name is a regular string/nvarchar(50), and Value is set as ntext in the DB</p> <p>I'm trying to write a large amount of xml to the "Value" property. I get an exception every time:</p> <pre><code>@p1 : String truncation: max=4000, len=35287, value='&lt;lots of xml..../&gt;' </code></pre> <p>I've googled it quite a bit, and tried a number of different mapping configurations:</p> <pre><code>&lt;property name="Name" type="string" /&gt; &lt;property name="Value" type="string" &gt; &lt;column name="Value" sql-type="StringClob" /&gt; &lt;/property&gt; </code></pre> <p>That's one example. Other configurations include "ntext" instead of "StringClob". Those configurations that don't throw mapping exceptions still throw the string truncation exception.</p> <p>Is this a problem ("feature") with SQL CE? Is it possible to put more than 4000 characters into a SQL CE database with nhibernate? If so, can anyone tell me how?</p> <p>Many thanks!</p>
<p>Okay, with many thanks to Artur in <a href="http://groups.google.com/group/nhusers/browse_thread/thread/4f865f0f516234ca" rel="nofollow noreferrer">this thread</a>, here's the solution: Inherit from the SqlServerCeDriver with a new one, and override the InitializeParamter method:</p> <pre><code>using System.Data; using System.Data.SqlServerCe; using NHibernate.Driver; using NHibernate.SqlTypes; namespace MySqlServerCeDriverNamespace { /// &lt;summary&gt; /// Overridden Nhibernate SQL CE Driver, /// so that ntext fields are not truncated at 4000 characters /// &lt;/summary&gt; public class MySqlServerCeDriver : SqlServerCeDriver { protected override void InitializeParameter( IDbDataParameter dbParam, string name, SqlType sqlType) { base.InitializeParameter(dbParam, name, sqlType); if (sqlType is StringClobSqlType) { var parameter = (SqlCeParameter)dbParam; parameter.SqlDbType = SqlDbType.NText; } } } } </code></pre> <p>Then, use this driver instead of NHibernate's in your app.config</p> <pre><code>&lt;nhibernateDriver&gt;MySqlServerCeDriverNamespace.MySqlServerCeDriver , MySqlServerCeDriverNamespace&lt;/nhibernateDriver&gt; </code></pre> <p>I saw a lot of other posts where people had this problem, and solved it by just changing the sql-type attribute to "StringClob" - as attempted in this thread.</p> <p>I'm not sure why it wouldn't work for me, but I suspect it is the fact that I'm using SQL CE and not some other DB. But, there you have it!</p>
<pre><code>&lt;property name="Value" type="string" /&gt; &lt;column name="Value" sql-type="StringClob" /&gt; &lt;/property&gt; </code></pre> <p>I'm assuming this is a small typo, since you've closed the property tag twice. Just pointing this out, in case it wasn't a typo.</p>
14,648
<p>I've read a couple of things about MVCs but I still don't understand when they should be used and when they shouldn't be used. I am looking for clear examples that say things like "<i>if you're developing this then you should use MVC, like this</i>" and "<i>if you're developing this, you shouldn't use MVC.</i>" Most of the examples I've seen rely on complex frameworks which have already implemented everything and you have to learn the framework and use it a lot to understand what's really happening. To many programmers, phrasings such as "<i>UI business logic</i>" sound like marketing terms &mdash; for example, the words "<i>Instead the View binds directly to a Presentation Model</i>" are used in <a href="https://stackoverflow.com/questions/2056/what-are-mvp-and-mvc-and-what-is-the-difference#101561">this post.</a></p> <p>I am aware of the dangers that may lurk in the shadows as MVC is a concept and everyone feels like they know it best, yet nobody really knows exactly how to use it because there may be a lot of variables involved and everyone is allowed to have a different perspective on how to dissect a project into the Model, the View and the Controller. There is a lot of theory out there but very few clear examples. What I'm looking for are not "the best" ways of doing it so this should not be considered as subjective; I'm looking for different <b>simple</b> implementations that would allow me to decide on my own which are the best approaches.</p> <p>Succinctly: What are good on-line resources that present pro and con arguments to using MVC in various situations and provide clear examples to help the reader understand the concept?</p>
<p>IMO, the best examples are with code and/or starter kits. </p> <p><a href="http://blog.wekeroad.com/" rel="noreferrer">Rob Conery</a> has a <a href="http://blog.wekeroad.com/mvc-storefront/" rel="noreferrer" title="Mvc posts by Rob">great number of posts</a> that explain how to to create an MVC site with ASP.NET MVC. Each one of these has a <a href="http://www.asp.net/learn/mvc-videos/#MVCStorefrontStarterKit" rel="noreferrer">video tutorial</a> which runs through the blog post discussion.</p> <p>The official <a href="http://www.asp.net/mvc/" rel="noreferrer">ASP.NET MVC</a> site also has some <a href="http://www.asp.net/learn/mvc-videos/" rel="noreferrer">video posts</a>, starter kits (<a href="http://www.codeplex.com/mvcsamples/SourceControl/ListDownloadableCommits.aspx" rel="noreferrer" title="Rob Conery&#39;s Storefront Starter Kit @ Codeplex">here</a>, <a href="http://haacked.com/archive/2008/05/23/updated-northwind-demo.aspx" rel="noreferrer" title="Phil Haack&#39;s Demo magic">here</a> and <a href="http://codeplex.com/kigg" rel="noreferrer" title="Digg clone mvc love @ Codeplex">here</a>) and <a href="http://forums.asp.net/1146.aspx" rel="noreferrer" title="ASP.NET MVC Forums .. clicky click!">extra sauce</a> to help.</p> <p>IMO, MVC is the way to go for Web Sites. Without spewing all the jargon and marketing speak, it really breaks down your code into nice, separate and defined sections. Each of these sections can also be tested .. which really helps protect the development process because you have peace of mind knowing that touching one part of the system doesn't break another (because the tests all pass after your latest change).</p> <p>Other blogs which you should check out:</p> <ul> <li><a href="http://haacked.com/" rel="noreferrer">Phil Haack</a></li> <li><a href="http://weblogs.asp.net/stephenwalther/default.aspx" rel="noreferrer">Stephen Walther</a></li> <li><a href="http://weblogs.asp.net/scottgu/default.aspx" rel="noreferrer">Scott Guthrie</a> (aka Guru Gu, ScottGu, The Gu, Gu...)</li> </ul>
<p>Its often hard to clearly separate your view logic with your business logic. If you read up abit on JSF &amp; JSP examples you can see clear examples of MVC in use. Completely seperating the view from the business logic.</p> <p>If your looking for good information about MVC I can suggest <a href="http://en.wikipedia.org/wiki/Model-view-controller" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Model-view-controller</a></p> <p>This is an important topic and I really like the idea of sepperating the different logics. It helps the programmer and everyone else working on the project.</p>
39,188
<p>I'm writing a Perl script and would like to use a n-ary tree data structure.</p> <p>Is there a good implementation that is available as source code (rather than part of a Perl library) ?</p>
<p>Adding to what Matthew already said, it looks like the following modules would be suitable:</p> <p><a href="http://search.cpan.org/perldoc?Tree::Nary" rel="nofollow noreferrer">Tree::Nary</a><br> <a href="http://search.cpan.org/perldoc?Tree::Simple" rel="nofollow noreferrer">Tree::Simple</a><br> <a href="http://search.cpan.org/perldoc?Tree" rel="nofollow noreferrer">Tree</a></p>
<p>I don't really understand why you want it was "source" rather than as a perl library, but you can download the source for any CPAN module. </p> <p>I haven't used it, but <a href="http://search.cpan.org/~rkinyon/Tree-1.01/lib/Tree.pm" rel="nofollow noreferrer">Tree</a> looks to fill your requirements.</p>
5,844
<p>I'm used to work with Java where large amounts of examples are available. For various reasons I had to switch to C# and trying to do the following in SharpDevelop:</p> <pre><code>// Form has a menu containing a combobox added via SharpDevelop's GUI // --- Variables languages = new string[2]; languages[0] = "English"; languages[1] = "German"; DataSet myDataSet = new DataSet(); // --- Preparation DataTable lTable = new DataTable("Lang"); DataColumn lName = new DataColumn("Language", typeof(string)); lTable.Columns.Add( lName ); for( int i=0; i&lt;languages.Length; i++ ) { DataRow lLang = lTable.NewRow(); lLang["Language"] = languages[i]; lTable.Rows.Add(lLang); } myDataSet.Tables.Add(lTable); // --- Handling the combobox mnuActionLanguage.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView; mnuActionLanguage.ComboBox.DisplayMember = "Language"; </code></pre> <p>One would assume to see some values in the dropdown, but it's empty. Please tell me what I'm doing wrong ;(</p> <p><em>EDIT: mnuActionLanguage.ComboBox.DataBind() is what I also found on the net, but it doesn't work in my case.</em></p> <p><strong>SOLUTION</strong></p> <pre><code>mnuActionLanguage.ComboBox.BindingContext = this.BindingContext; </code></pre> <p>at the end solved the problem!</p>
<p>You need to set the binding context of the ToolStripComboBox.ComboBox.</p> <p>Here is a slightly modified version of the code that I have just recreated using Visual Studio. The menu item combo box is called toolStripComboBox1 in my case. Note the last line of code to set the binding context.</p> <p>I noticed that if the combo is in the visible are of the toolstrip, the binding works without this but not when it is in a drop-down. Do you get the same problem?</p> <p>If you can't get this working, drop me a line via my contact page and I will send you the project. You won't be able to load it using SharpDevelop but will with C# Express.</p> <pre><code>var languages = new string[2]; languages[0] = "English"; languages[1] = "German"; DataSet myDataSet = new DataSet(); // --- Preparation DataTable lTable = new DataTable("Lang"); DataColumn lName = new DataColumn("Language", typeof(string)); lTable.Columns.Add(lName); for (int i = 0; i &lt; languages.Length; i++) { DataRow lLang = lTable.NewRow(); lLang["Language"] = languages[i]; lTable.Rows.Add(lLang); } myDataSet.Tables.Add(lTable); toolStripComboBox1.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView; toolStripComboBox1.ComboBox.DisplayMember = "Language"; toolStripComboBox1.ComboBox.BindingContext = this.BindingContext; </code></pre>
<p>This line</p> <pre><code>mnuActionLanguage.ComboBox.DisplayMember = "Lang.Language"; </code></pre> <p>is wrong. Change it to</p> <pre><code>mnuActionLanguage.ComboBox.DisplayMember = "Language"; </code></pre> <p>and it will work (even without DataBind()).</p>
32,046
<p>I have written a small ASP.NET application. It runs fine when running it with the small IIS installation that comes with Visual Studio 2005, but not when trying with IIS. I created the virtual directory in IIS where the application is located (done it though both IIS and VS 2005), but it does not work. In the beginning I thought it might be caused by the web.config file, but after a few tests, I think that the problem lies with IIS (not certain about it).</p> <p>Some of the errors that I get are</p> <blockquote> <p>Unable to start debugging on the web server. The underlying connection was closed: An unexpected error ocurred on a receiver. Click help for more information</p> </blockquote> <p>Can anybody give me a suggestion of what to try next?</p>
<p>Have you run <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/187d0e2c-8e89-49ad-a89d-e26e4d76ee68.mspx?mfr=true" rel="nofollow noreferrer">aspnet_regiis</a>?</p> <p>Here's an <a href="http://msdn.microsoft.com/en-us/library/ms178477.aspx" rel="nofollow noreferrer">overview site for different IIS versions</a> setup and should help if there are other questions/issues</p>
<p>The site won't load at all or you can't debug remotely?</p>
19,160
<p>When I asked for tools to profile Rails apps, someone <a href="https://stackoverflow.com/questions/350470/what-tools-do-you-recommend-to-profile-rails-apps#351842">pointed at DTrace</a>. Since I work on MacOSX stations and deploy on OpenSolaris, it is a valid way to go. But I have little knowledge of DTrace.</p> <p>Besides the usual suspect, Sun DTrace page and the avaliable info there, is there any other killer pointer to learn Dtrace out there?</p>
<p>I did a 35 min video and showed some DTrace starter examples that you can find here: <a href="http://cocoasamurai.blogspot.com/2008/05/dtrace-for-cocoa-developers.html" rel="noreferrer">http://cocoasamurai.blogspot.com/2008/05/dtrace-for-cocoa-developers.html</a> which were intended for introducing DTrace to Cocoa Developers, but it can work for anybody really</p>
<p>I found that reading dtrace version of the usual admin monitoring tools of Mac OS X was a great help <code>truss</code> -> <code>dtruss</code>. There are at least a dozen different scripts that you can read. (Most begining by "d".)</p> <p>There also is <code>/Developer/Applications/Instruments.app</code> which is a graphical app which generates dtrace scripts.</p> <p>Also, Wikipedia's <a href="http://en.wikipedia.org/wiki/DTrace" rel="nofollow noreferrer">DTrace</a> page has loads of links which should help.</p>
45,953
<p>I have a MasterPage and a Content Page</p> <p>My Content Page has a number of controls, - dropdownlist, text boxes, radio buttons.</p> <p>I want to loop through all the control and if its one of the controls above then i want to obtain the selectedvalue, text etc</p> <p>I know I can access the control directly by name, but as this is my learning experience on asp.net, I want to be able to go through the Controls collection</p> <p>I tried</p> <pre><code>foreach(Controls ctrl in Master.Controls) { } </code></pre> <p>but I wasnt able to get to the controls I needed.</p> <p>Edit:: I guess i drew the gun a bit too quick as my intellisense kept failing on me. I solved my issue with this in code behind on my content page</p> <pre><code>protected void btnSearch_Click(object sender, EventArgs e) { foreach (Control ctrl in Master.Controls) { if (ctrl is HtmlForm) { foreach(Control formControl in ctrl.Controls) { if (formControl is ContentPlaceHolder) { foreach (Control placeHolderControl in formControl.Controls) { if (placeHolderControl is DropDownList) { string test = "AA"; } } } } } } } </code></pre> <p>Now to build a recursive routine</p>
<p>The Controls are in a heirarchy. The only control in the page is usually a Form (but not always). The form contains controls that appear in the <code>&lt;form&gt;</code> tag. If the form has for example a <code>&lt;p runat="server"&gt;</code> in it, the <code>&lt;p&gt;</code> will contains all controls that appear inside it.</p> <p>For instance,</p> <pre><code>&lt;form runat="server"&gt; &lt;p runat="server"&gt; &lt;asp:Label runat="server" /&gt; &lt;asp:TextBox runat="server" /&gt; &lt;/p&gt; &lt;p runat="server"&gt; &lt;asp:Button runat="server" /&gt; &lt;/p&gt; &lt;/form&gt; </code></pre> <p>will result in the following structure:</p> <pre><code>form - p - label - textbox - p - button </code></pre> <p>Thus, you must loop through the controls in the directly containing control.</p> <p>-- EDIT:</p> <p>Also, to loop through all controls you would need to either recursively or iteratively loop into the heirarchy</p> <pre><code>// This is the recursive version public void LoopControl(Control parent) { foreach (Control control in parent) { // do stuff LoopControl(control); } } // And then LoopControl(Page); </code></pre>
<p>If you are trying to access the content page controls from the master page, you need to access the controls through the appropriate ContentPlaceHolder (on the master page). something like this:</p> <pre><code>foreach (Control c in ContentPlaceHolder1.Controls) { Response.Write(c.ID ); } </code></pre>
40,574
<p>I received an error when an referenced .NET Framework 2.0 assembly tried to execute the following line of code in an IIS hosted WCF service:</p> <p>Error Message:</p> <blockquote> <p>exePath must be specified when not running inside a stand alone exe.</p> </blockquote> <p>Source Code:</p> <pre><code>ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); </code></pre> <p>Has anyone experienced this issue and do they know how to resolve it?</p> <p><b>EDIT:</b> My question is, what is the best way to open a configuration file (app.config and web.config) from a WCF service that is backwards compatible with a .NET 2.0 assembly?</p>
<p>I was able to resolve the configuration issue by removing the existing code from my provious answer and replacing it with the following ConfigurationManager implementation:</p> <pre><code>string MySetting = ConfigurationManager.AppSettings.Get("MyAppSetting"); </code></pre> <p>If works for ASP.NET applications, WinForms applications and WCF Services. I just over-engineered the initial implementation of my class library 3 years ago....</p>
<p>It depends on what you're trying to accomplish. On ASP.NET, you'd normally wouldn't use ConfigurationManager for stuff like this, but WebConfigurationManager instead. That said, there's no exact equivalent, since, in reality, the user/roaming/etc stuff that OpenExeConfiguration allows doesn't make sense on a web application.</p> <p>What do you need it for?</p>
29,166
<p>Ideally something that will work with Oracle, MS SQL Server, MySQL and Posgress.</p>
<p>if you mean common lisp by lisp, then there's <strong><a href="http://common-lisp.net/project/cl-rdbms/" rel="noreferrer">cl-rdbms</a></strong>. it is heavily tested on postgres (uses <a href="http://common-lisp.net/project/postmodern/" rel="noreferrer">postmodern</a> as the backend lib), it has a toy sqlite backend and it also has an OCI based oracle backend. it supports abstracting away the different sql dialects, has an sql quasi-quote syntax extension installable on e.g. the [] characters.</p> <p>i'm not sure if it's the best, and i'm biased anyway... :) but we ended up rolling our own lib after using <a href="http://clsql.b9.com/" rel="noreferrer">clsql</a> for a while, which is i think the most widely used sql lib for cl.</p> <p>see <a href="http://www.cliki.net/SQL" rel="noreferrer">cliki page about sql</a> for a further reference.</p>
<p>Allegro Common Lisp has an <a href="http://www.franz.com/support/documentation/8.1/doc/aodbc.htm" rel="nofollow noreferrer">ODBC</a> library and a <a href="http://franz.com/support/documentation/8.1/doc/mysql.htm" rel="nofollow noreferrer">MySQL-specific</a> library, both exhaustively documented. I've used the MySQL one; no surprises.</p>
14,995
<p>I distribute my application using a VS2008 install package, which normally works great. When I create new versions of the app, I go in and increment the <code>Version</code> property on the install package and verify the <code>RemovePreviousVersions</code> property is set to True.</p> <p>This works just fine most of the time - I just run the install package for the newer version and the older version is uninstalled and the newer version replaces it.</p> <p>However, occasionally the install package will run successfully, but when I start the program the old version starts up. Apparently the old version of the .exe is still present.</p> <p>I end up having to completely uninstall the software and install the new version, which always works, but is a pain.</p> <p>The file isn't in use as far as I can tell and the install package doesn't tell me to reboot.</p> <p>Any ideas about what's going on here?</p>
<p>Not a direct answer, but the key difference between an upgrade and an uninstall+ a reinstall is that any custom uninstall steps are not called in 2k8 but are in 2k5.</p> <p>This is referenced in <a href="https://stackoverflow.com/questions/370940/visual-studio-2008-service-installer-project-upgrade-issue">Visual Studio 2005 -&gt; 2008/10 Service Installer Project Upgrade issue</a></p> <p>The other difference related to this is that in 2k8, the files get upgraded based on the version info resource - if your modules dont have newer versions, they dont get replaced. </p> <p>In some cases whether you strong name also has effects, but I'm pretty confident the last paragraph covers the issue you're seeing.</p>
<p>We need to set REINSTALLMODE property of our msi file to amus.</p> <p>Following is the link to know more about the meaning of 'amus' <a href="http://msdn.microsoft.com/en-us/library/aa371182%28VS.85%29.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa371182%28VS.85%29.aspx</a></p> <p>There are two ways to do that.</p> <ol> <li>By using msiexec.exe which comes with .NET SDK (if you have VS 2005 or VS 2008 it will come with it, just browse to command prompt of visual studio and you will find it there)</li> </ol> <p>once you find msiexec.exe just type following command to set REINSTALLMODE property to amus for your installer.</p> <p>msiexec.exe /i foo.msi REINSTALLMODE=amus</p>
36,954
<p>I work on an application that has a both a GUI (graphical) and API (scripting) interface. Our product has a very large installed base. Many customers have invested a lot of time and effort into writing scripts that use our product.</p> <p>In all of our designs and implementation, we (understandably) have a very strict requirement to maintain 100% <strong>backwards compatibility</strong>. A script which ran before must continue to run in exactly the same way, without any modification, when we introduce a new software version.</p> <p>Unfortunately, this requirement sometimes ties our hands behind our back, as it really restricts our ability to <strong>innovate</strong> and come up with new and better ways of doing things.</p> <p>For example, we might come up with a better (and more usable) way of achieving a task which is already possible. It would be desirable to make this better way the default way, but we can't do this as it may have backwards compatibility implications. So we are stuck with leaving the new (better) way as a mode, that the user must "turn on" before it becomes available to them. Unless they read the documentation or online help (which many customers don't do), this new functionality will remain hidden forever.</p> <p>I know that Windows Vista annoyed a lot of people when it first came out, because of all the software and peripherals which didn't work on it, even when they worked on XP. It received a pretty bad reception because of this. But you can see that Microsoft have also succeeded in making some great innovations in Vista, at the expense of backwards compatibility for a lot of users. They took a risk. Did it pay off? Did they make the right decision? I guess only time will tell.</p> <p>Do you find yourself balancing the conflicting needs of innovation and backwards compatibility? How do you handle the juggling act?</p>
<p>As far is my programming experience is concerned, if I'm going to fundamentally change something that will prevent past incoming data to be used correctly, I need to create an abstraction layer for the old data where it can be converted for use in the new format.</p> <p>Basically I set the &quot;improved&quot; way as default and make sure through a converter it can read data of the old format, but save or store data as the new format.</p> <p>I think the big thing here is test, test, test. Backwards compatibility shouldn't hinder forward progress.</p>
<p>You could alawys look for innovative ways to maintain backwards compatibilty.</p>
19,453
<p>I'm trying to design a data model that denotes one user being the friend of another user. This is what i've come up with so far, but it seems clunky, is there a better solution?</p> <pre><code>User ===== Id Name etc... UserFriend =========== UserId FriendId IsMutual IsBlocked </code></pre>
<pre><code>UserRelationship ==== RelatingUserID RelatedUserID Type[friend, block, etc] </code></pre> <p>Agree that mutuality doesn't belong as a column; breaks normalization.</p>
<p>I think you should be create two table:<br></p> <p> 1. user<br> u_id int<br> u_username string<br> balahhh............<br> </p> <p> 2. friendship<br> fs_id int<br> relating_id int<br> related_id int<br> </p>
49,680
<p>I am working on C++ and COM/ATL in Windows from last few years. Now I want to shift to Linux Programming. I know basic architecture of Linux. I did some of the projects which are using ncurses, sockets and audio libraries(Terminal Applications). On which tool I should be familiar to start with projects. In windows I have started with Win32 Programming then moved to COM and ATL. Win32 Programming gave me the insights of Windows.</p> <p>Can you give me the steps to start with Linux Programming?</p>
<p>Depends what you're trying to do...</p> <p>Are you going to be doing GUI apps? Learn Qt or GTK or wxWidgets. Are you going to be doing device driver development? Learn straight C, not just C++. A lot of the exciting software development under Linux happens in Python and Perl (and other dynamic languages to a lesser extent), so you should almost certainly learn one of those.</p>
<p>I would recommend you to start by using Gentoo, it should be hard the first weeks, but after a while (say 2 months and less if you have basic linux understand ) you will be able to use every distribution and you will know exactly what will happen and how on your system when you press/digit something, I think that you will be re-paid for this more time (learn gentoo is a bit harder then other distros) spent on Gentoo. And this I think will be helpful when programming for linux.</p>
25,689
<p>I'm using PHP's PDO layer for data access in a project, and I've been reading up on it and seeing that it has good innate support for persistent DB connections. I'm wondering when/if I should use them. Would I see performance benefits in a CRUD-heavy app? Are there downsides to consider, perhaps related to security?</p> <p>If it matters to you, I'm using MySQL 5.x.</p>
<p>You could use this as a rough "ruleset":</p> <p><strong>YES</strong>, use persistent connections, if:</p> <ul> <li>There are only few applications/users accessing the database, i.e. you will not result in 200 open (but probably idle) connections, because there are 200 different users shared on the same host.</li> <li>The database is running on another server that you are accessing over the network</li> <li>An (one) application accesses the database very often</li> </ul> <p><strong>NO</strong>, don't use persistent connections, if:</p> <ul> <li>Your application only needs to access the database 100 times an hour. </li> <li>You have many webservers accessing one database server</li> <li>You're using Apache in prefork mode. It uses one connection for each child process, which can ramp up fairly quickly. (via @Powerlord in the comments)</li> </ul> <p>Using persistent connections is considerable faster, especially if you are accessing the database over a network. It doesn't make so much difference if the database is running on the same machine, but it is still a little bit faster. However - as the name says - the connection is persistent, i.e. it stays open, even if it is not used.</p> <p>The problem with that is, that in "default configuration", MySQL only allows 1000 parallel "open channels". After that, new connections are refused (You can tweak this setting). So if you have - say - 20 Webservers with each 100 Clients on them, and every one of them has just one page access per hour, simple math will show you that you'll need 2000 parallel connections to the database. That won't work. </p> <p>Ergo: Only use it for applications with lots of requests.</p>
<p>I was going to ask this same question but rather than ask the same question again I'll just add some information that I've found.</p> <ul> <li><a href="http://www.mysqlperformanceblog.com/2006/11/12/are-php-persistent-connections-evil/" rel="nofollow noreferrer">Are PHP persistent connections evil ?</a></li> <li><a href="http://us2.php.net/manual/en/features.persistent-connections.php" rel="nofollow noreferrer">Persistent Database Connections</a></li> </ul> <p>It is also worth noting that the newer mysqli extension does not even include the option to use persistent database connections.</p> <p>I'm still using persitent connections at the moment but plan to switch to non-persistent in the near future.</p>
7,301
<p>I need to be able to get at the full URL of the page I am on from a user control. Is it just a matter of concatenating a bunch of Request variables together? If so which ones? Or is there a more simpiler way?</p>
<p>I usually use <code>Request.Url.ToString()</code> to get the full url (including querystring), no concatenation required.</p>
<p>If you need the port number also, you can use</p> <pre><code>Request.Url.Authority </code></pre> <p>Example:</p> <pre><code>string url = Request.Url.Authority + HttpContext.Current.Request.RawUrl.ToString(); if (Request.ServerVariables["HTTPS"] == "on") { url = "https://" + url; } else { url = "http://" + url; } </code></pre>
6,191
<p>Delphi strings use single quotes, for example '<code>a valid string</code>'. How does one specify the <code>'</code> character within a literal string? How would one refer to the null byte (Unicode code point <code>U+0000</code>)? </p>
<p>To add a single quote to a string, you include two <code>'</code> marks e.g. </p> <pre><code>str := '''test string'''; Writeln(str) </code></pre> <p>In the string above, you have the normal single quotation to start a string and then two for the single quote. Same goes for the end of the string. </p> <p>You can also use <code>#</code> followed by a number for other escape character e.g.<br> For a new line:</p> <pre><code>str := 'Newline' + #13 + #10 </code></pre> <p>or just </p> <pre><code>str := 'Newline'#13#10 </code></pre> <p>Of course, using the platform-dependent constant for newline is better.</p>
<p>For <code>'</code> character put it twice. For example: <code>'Don''t'</code>. Null byte type as #0.</p>
38,829
<p>I have a couple of buttons of which I modified how they look. I have set them as flat buttons with a background and a custom border so they look all pretty and nothing like normal buttons anymore (actually, they look like Office 2003 buttons now ;-). The buttons have a border of one pixel.</p> <p>However when the button gets selected (gets the focus through either a click or a keyboard action like pressing the tab key) the button suddenly gets and extra border around it of the same colour, so making it a two pixel border. Moreover when I disable the one pixel border, the button does not get a one pixel border on focus.</p> <p>On the net this question is asked a lot like 'How can I disable focus on a Button', but that's not what I want: the focus should still <em>exist</em>, just not <em>display</em> in the way it does now.</p> <p>Any suggestions? :-)</p>
<p>Is this the effect you are looking for?</p> <pre><code>public class NoFocusCueButton : Button { protected override bool ShowFocusCues { get { return false; } } } </code></pre> <p>You can use this custom button class just like a regular button, but it won't give you an extra rectangle on focus.</p>
<p>I've had good luck merely setting the Focusable property of the button to be false:</p> <pre><code>&lt;Button HorizontalAlignment="Left" Margin="0,2" Command="{Binding OpenSuspendedJobCommand, Mode=OneWay}" Focusable="False" Style="{StaticResource ActionButton}" Content="Open Job..." /&gt; </code></pre>
17,916
<p>This is in C#, I have a class that I am using from some else's DLL. It does not implement IEnumerable but has 2 methods that pass back a IEnumerator. Is there a way I can use a foreach loop on these. The class I am using is sealed.</p>
<p><code>foreach</code> does <em>not</em> require <code>IEnumerable</code>, contrary to popular belief. All it requires is a method <code>GetEnumerator</code> that returns any object that has the method <code>MoveNext</code> and the get-property <code>Current</code> with the appropriate signatures.</p> <p>/EDIT: In your case, however, you're out of luck. You can trivially wrap your object, however, to make it enumerable:</p> <pre><code>class EnumerableWrapper { private readonly TheObjectType obj; public EnumerableWrapper(TheObjectType obj) { this.obj = obj; } public IEnumerator&lt;YourType&gt; GetEnumerator() { return obj.TheMethodReturningTheIEnumerator(); } } // Called like this: foreach (var xyz in new EnumerableWrapper(yourObj)) …; </code></pre> <p>/EDIT: The following method, proposed by several people, does <em>not</em> work if the method returns an <code>IEnumerator</code>:</p> <pre><code>foreach (var yz in yourObj.MethodA()) …; </code></pre>
<p>You could always wrap it, and as an aside to be "foreachable" you only need to have a method called "GetEnumerator" with the proper signature. </p> <pre><code> class EnumerableAdapter { ExternalSillyClass _target; public EnumerableAdapter(ExternalSillyClass target) { _target = target; } public IEnumerable GetEnumerator(){ return _target.SomeMethodThatGivesAnEnumerator(); } } </code></pre>
15,481
<p>What is actually the difference between these two casts?</p> <pre><code>SomeClass sc = (SomeClass)SomeObject; SomeClass sc2 = SomeObject as SomeClass; </code></pre> <p>Normally, shouldn't they both be explicit casts to the specified type?</p>
<p>The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a null reference, but no exception.</p> <p>[Edit]</p> <p>My original answer is certainly the most pronounced difference, but as Eric Lippert <a href="http://blogs.msdn.com/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx" rel="noreferrer">points out</a>, it's not the only one. Other differences include:</p> <ul> <li>You can't use the 'as' operator to cast to a type that doesn't accept 'null' as a value</li> <li>You can't use 'as' to <em>convert</em> things, like numbers to a different representation (float to int, for example).</li> </ul> <p>And finally, using 'as' vs. the cast operator, you're also saying "I'm not sure if this will succeed." </p>
<p>The parenthetical cast throws an exception if the cast attempt fails. The "as" cast returns null if the cast attempt fails.</p>
2,458
<p>I have a SQL Server 2000 install on a server that I am having weird connection issues with. </p> <p>Using SSMS I can't connect to it using an Alias I have setup on Configuration Manager. The Alias is set to use TCPIP which is the first protocol in the order below shared memory. If I use the exact same server name I put into the Alias then I can connect just fine.</p> <p>I see the exact same behavior in my ASP.NET application, using the alias I get a connection failure, using the name it connects just fine. The ASP.NET connection string is not specifying a protocol. </p>
<p>Using the server name will use the default connection protocol for the client. This may be named pipes or tcp/ip (MDAC version, upgrade vs install etc).</p> <blockquote> <p>The Alias is set to use TCPIP which is the first protocol in the order below shared memory</p> </blockquote> <p>I assume that if the client alias is set to use tcp, then the server is only configured to listen on named pipes so it only works with server name. The client will eventually find named pipes in it's list of protocols to use.</p> <p>To test, replace servername with np:servername and tcp:servername to change the protocol <em>without</em> using the alias.</p> <p>Or check what the server is listening on and fix that...</p> <p>The other option is a non-standard TCP port (server, not 1433) or firewall preventing access to port 1433/1434.</p> <p><a href="http://doc.ddart.net/mssql/sql2000/html/" rel="nofollow noreferrer">SQL 2000 Books</a></p>
<p>Does the alias specify a protocol? Is that protocol accepted by the server? Is that the protocol being used when you are connecting by name? (i.e. what is the order of client protocols)</p>
36,123
<p>I have an email subject of the form:</p> <pre><code>=?utf-8?B?T3.....?= </code></pre> <p>The body of the email is utf-8 base64 encoded - and has decoded fine. I am current using Perl's Email::MIME module to decode the email.</p> <p>What is the meaning of the =?utf-8 delimiter and how do I extract information from this string?</p>
<p>The <a href="http://en.wikipedia.org/wiki/MIME#Encoded-Word" rel="noreferrer"><code>encoded-word</code></a> tokens (as per <a href="http://www.faqs.org/rfcs/rfc2047.html" rel="noreferrer">RFC 2047</a>) can occur in values of some headers. They are parsed as follows:</p> <pre><code>=?&lt;charset&gt;?&lt;encoding&gt;?&lt;data&gt;?= </code></pre> <p>Charset is UTF-8 in this case, the encoding is <code>B</code> which means base64 (the other option is <code>Q</code> which means Quoted Printable).</p> <p>To read it, first decode the base64, then treat it as UTF-8 characters.</p> <p>Also read the various Internet Mail RFCs for more detail, mainly <a href="http://www.faqs.org/rfcs/rfc2047.html" rel="noreferrer">RFC 2047</a>.</p> <p>Since you are using Perl, <a href="https://metacpan.org/pod/Encode::MIME::Header" rel="noreferrer">Encode::MIME::Header</a> could be of use:</p> <blockquote> <p>SYNOPSIS</p> <pre><code>use Encode qw/encode decode/; $utf8 = decode('MIME-Header', $header); $header = encode('MIME-Header', $utf8); </code></pre> <p>ABSTRACT</p> <p>This module implements RFC 2047 Mime Header Encoding. There are 3 variant encoding names; MIME-Header, MIME-B and MIME-Q. The difference is described below</p> <pre><code> decode() encode() MIME-Header Both B and Q =?UTF-8?B?....?= MIME-B B only; Q croaks =?UTF-8?B?....?= MIME-Q Q only; B croaks =?UTF-8?Q?....?= </code></pre> </blockquote>
<p>This is a standard extension for charset labeling of headers, specified in <a href="http://www.rfc-archive.org/getrfc.php?rfc=2047" rel="nofollow noreferrer">RFC2047</a>.</p>
15,329
<p>In my project I have functionality that is being used as a web application and as a console application (to be started from the task scheduler). To do that I put the common code in a DLL that is being used by both the web application and the console application. This works fine.</p> <p>However, the console and web applications now have an App.config and Web.config that are mostly the same. Is it possible to put this configuration in the DLL as well and make it available to both applications?</p>
<p>Yes, you can and should put the common configuration settings in the config file for your DLL. Just add an app.config file to the DLL project, and make sure you read the configuration settings from inside the DLL. When deployed, your config file needs to have the name "MyDLL.dll.config" (assuming your DLL is named "MyDLL.dll") and be in the same folder as the DLL.</p>
<p>you could put the common configuration under the windows registry, accessible wherever you like</p>
19,558
<p>Let X be the set of all sets that do not contain themselves. Is X a member of X?</p>
<p>In <strong>ZFC</strong>, either the axiom of foundation [as mentioned] or the axiom (scheme) of comprehension will prohibit this. The first, for obvious reasons; the second, since it basically says that for given <em>z</em> and first-order property <em>P</em>, you can construct { <em>x</em> ∈ <em>z</em> : <em>P</em>(<em>x</em>) }, but to generate the Russell set, you would need <em>z</em> = <em>V</em> (the class of all sets), which is not a set (i.e. cannot be generated from any of the given axioms).</p> <p>In New Foundations (<strong>NF</strong>), "<em>x</em> ∉ <em>x</em>" is not a stratified formula, and so again we cannot define the Russell set. Somewhat amusingly, however, <em>V</em> <em>is</em> a set in <strong>NF</strong>.</p> <p>In von Neumann--Bernays--Gödel set theory (<strong>NBG</strong>), the class <em>R</em> = { <em>x</em> : <em>x</em> is a set and <em>x</em> ∉ <em>x</em> } is definable. We then ask whether <em>R</em> ∈ <em>R</em>; if so, then also <em>R</em> ∉ <em>R</em>, giving a contradiction. Thus we must have <em>R</em> ∉ <em>R</em>. But there is no contradiction here, since for any given class <em>A</em>, <em>A</em> ∉ <em>R</em> implies either <em>A</em> ∈ <em>A</em> or <em>A</em> is a proper class. Since <em>R</em> ∉ <em>R</em>, we must simply have that <em>R</em> is a proper class.</p> <p>Of course, the class <em>R</em> = { <em>x</em> : <em>x</em> ∉ <em>x</em> }, without the restriction, is simply not definable in <strong>NBG</strong>.</p> <p>Also of note is that the above procedure is formally constructable as a proof in <strong>NBG</strong>, whereas in <strong>ZFC</strong> one has to resort to meta-reasoning.</p>
<p>The question is ill-posed in the standard <a href="http://en.wikipedia.org/wiki/Zermelo-Fraenkel_set_theory" rel="nofollow noreferrer">ZFC</a> (Zermelo-Fraenkel + axiom of Choice) set theory because the object thus defined is not a set.</p> <p>Since (again, assuming standard ZFC) your <em>class</em> {x : x\not\in x} is not a set, the answer becomes no, it's not an element of itself (even as a class) since only sets can be elements of classes or sets.</p> <p>By the way, as soon as you agree to the <a href="http://en.wikipedia.org/wiki/Axiom_of_foundation" rel="nofollow noreferrer">axiom of foundation</a>, no set can be an element of itself.</p> <p>Of course the nice thing about math is you can choose whichever axioms you want :) but believing in paradoxes is just weird.</p>
5,580
<p>I have seen <a href="https://stackoverflow.com/questions/87030/where-to-find-java-6-jssejce-source-code">Where to find Java 6 JSSE/JCE Source Code?</a> and asked the question myself <a href="https://stackoverflow.com/questions/150849/how-to-get-jrejdk-with-matching-source">How to get JRE/JDK with matching source?</a> but I don't either of these was specific enough to get the answer I was really after, so I'm going to try a way more specific version of the question.</p> <p>Basically the problem that I am trying to solve is that I would like to be able to use my Eclipse debugger on Windows and step into the Java SSL classes (JSSE) to help me debug SSL issues as well as to just understand the SSL process better. BTW I am familiar with (and use) the javax.net.debug=ssl|all system property to get SSL tracing and, while this is very helpful, I'd still like to be able to step through that pesky code.</p> <p>So what I think I specifically need is:</p> <ol> <li>An executable JRE / JDK implementation (not wanting to build one)...</li> <li>That runs on my Windows platform (XP)...</li> <li>That includes source...</li> <li>And that source includes the SSL "bits" (JSSE, etc.)...</li> <li>And ideally the SSL implementation is Sun's or the OpenJDK version.</li> </ol> <p>I think the closest thing (as noted in PW's answer <a href="https://stackoverflow.com/questions/87030/where-to-find-java-6-jssejce-source-code#87106">StackOverflow: 87106</a>) is the OpenJDK source openjdk-6-src-b12-28_aug_2008.tar.gz found at <a href="http://download.java.net/openjdk/jdk6/" rel="noreferrer">OpenJDK 6 Source Release</a>, but I'm not sure there's a matching executable JDK / JRE for that that would run on Windows.</p>
<p>You can get the source code of JSSE lib (Open JDK implementation) here - <a href="http://hg.openjdk.java.net/jdk8u/jdk8u-dev/jdk/file/4d6c03fb1039/src/share/classes/sun/security/ssl" rel="noreferrer">http://hg.openjdk.java.net/jdk8u/jdk8u-dev/jdk/file/4d6c03fb1039/src/share/classes/sun/security/ssl</a></p> <p>Steps to create a source jar file for attaching to an IDE for debugging. </p> <ol> <li>Go a little above in the directory structure i.e. to <a href="http://hg.openjdk.java.net/jdk8u/jdk8u-dev/jdk/file/4d6c03fb1039/src/share/classes/" rel="noreferrer">http://hg.openjdk.java.net/jdk8u/jdk8u-dev/jdk/file/4d6c03fb1039/src/share/classes/</a> repo.</li> <li>Download the source package by clicking on the "zip" or "gz" links that you see at the left pane.</li> <li>But this package is huge and contains thousands of *.java files. You do not normally want all of these to just debug jsse.jar code. </li> <li>So better copy only the <strong>sun.security.rsa</strong> , <strong>sun.security.ssl</strong> , <strong>sun.security.provider</strong> &amp; <strong>com.sun.net.ssl</strong> packages to a new folder (lets say jsse-code) on your computer.</li> <li>Go to that folder from command line &amp; create the source jar on your own.<br> e.g. <b>jar -cvf jsse-src.jar * </b></li> <li>You are done. You now have your jsse source lib that you can attach to your preferred IDE (e.g. - Eclipse) to debug the JSSE code.</li> </ol> <p>Thanks <br> Ayas</p>
<p>The Sun implementation is not open source as far as I know. You can download an open source JCE here:</p> <p><a href="http://www.bouncycastle.org/java.html" rel="nofollow noreferrer">http://www.bouncycastle.org/java.html</a></p>
19,773
<p>I got a little curious after reading <a href="http://it.slashdot.org/it/08/09/09/1558218.shtml" rel="noreferrer">this /. article</a> over hijacking HTTPS cookies. I tracked it down a bit, and a good resource I stumbled across lists a few ways to secure cookies <a href="http://casabasecurity.com/content/using-aspnet-session-handling-secure-sites-set-secure-flag" rel="noreferrer">here</a>. Must I use adsutil, or will setting requireSSL in the httpCookies section of web.config cover session cookies in addition to all others (<a href="http://msdn2.microsoft.com/en-us/library/ms228262.aspx" rel="noreferrer">covered here</a>)? Is there anything else I should be considering to harden sessions further?</p>
<p>Typically I have always done this using a 3rd party aggregator. The messages are compiled into SMIL, which is the description language for the MMS messages. These are then sent on to the aggregator who will then send them through the MMS gateway of the Network Operator. They are typically charged on a per message basis and the aggregators will buy the messages in a block from the operators.</p> <p>If you are trying to send an MMS message without getting charged then I am not sure how to do this, or if it is possible.</p>
<p>You could use Twilio to accomplish this. You can <a href="https://www.twilio.com/docs/quickstart/csharp/sms/sending-via-rest" rel="nofollow">dive into the docs</a> for specific implementation details but using the <a href="https://www.twilio.com/docs/csharp/install" rel="nofollow">C# helper library</a> the code to send an MMS would look like this:</p> <pre><code> // Send a new outgoing MMS by POSTing to the Messages resource */ client.SendMessage( "YYY-YYY-YYYY", // From number, must be an SMS-enabled Twilio number person.Key, // To number, if using Sandbox see note above // message content string.Format("Hey {0}, Monkey Party at 6PM. Bring Bananas!", person.Value), // media url of the image new string[] {"https://demo.twilio.com/owl.png" } ); </code></pre> <p>Disclaimer: I work for Twilio.</p>
7,770
<p>We had a discussion here at work regarding why <em>fread()</em> and <em>fwrite()</em> take a size per member and count and return the number of members read/written rather than just taking a buffer and size. The only use for it we could come up with is if you want to read/write an array of structures which aren't evenly divisible by the platform alignment and hence have been padded but that can't be so common as to warrant this choice in design.</p> <p>From <a href="https://man7.org/linux/man-pages/man3/fread.3.html" rel="noreferrer">fread(3)</a>:</p> <blockquote> <p>The function fread() reads nmemb elements of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.</p> </blockquote> <blockquote> <p>The function fwrite() writes nmemb elements of data, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr.</p> </blockquote> <blockquote> <p>fread() and fwrite() return the number of items successfully read or written (i.e., not the number of characters). If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).</p> </blockquote>
<p>The difference in <code>fread(buf, 1000, 1, stream)</code> and <code>fread(buf, 1, 1000, stream)</code> is, that in the first case you get only one chunk of 1000 bytes or nothing, if the file is smaller and in the second case you get everything in the file less than and up to 1000 bytes.</p>
<p>I think it is because C lacks function overloading. If there was some, size would be redundant. But in C you can't determine a size of an array element, you have to specify one.</p> <p>Consider this:</p> <pre><code>int intArray[10]; fwrite(intArray, sizeof(int), 10, fd); </code></pre> <p>If fwrite accepted number of bytes, you could write the following:</p> <pre><code>int intArray[10]; fwrite(intArray, sizeof(int)*10, fd); </code></pre> <p>But it is just inefficient. You will have sizeof(int) times more system calls.</p> <p>Another point that should be taked into consideration is that you usually don't want a part of an array element be written to a file. You want the whole integer or nothing. fwrite returns a number of elements succesfully written. So if you discover that only 2 low bytes of an element is written what would you do?</p> <p>On some systems (due to alignment) you can't access one byte of an integer without creating a copy and shifting.</p>
37,852
<p>I have an MSI file that I have created using a Visual Studio Setup Project. The installed generates an .InstallState file in the application directory. Is there a way to have this file generated in a different location rather than the default location?</p>
<p>You need to set the value of InstallStateDir.<br> You need to override the Commit/Install/Rollback/Uninstall and set the value of InstallStateDir (I.E. Context["InstallStateDir"] = @"c:\mydir") . </p>
<p>This should also work by specifying /InstallStateDir="c:\myfolder" from the commandline (see KB946503). However, InstallContext is converting all parameter names to lowercase which breaks the following code from AssemblyInstaller, expecting to find the mixed case parameter name:</p> <pre><code>private string GetInstallStatePath(string assemblyPath) { string str2 = base.Context.Parameters["InstallStateDir"]; assemblyPath = Path.ChangeExtension(assemblyPath, ".InstallState"); if (!string.IsNullOrEmpty(str2)) { return Path.Combine(str2, Path.GetFileName(assemblyPath)); } return assemblyPath; } </code></pre> <p>Setting <code>Context["InstallStateDir"]</code> would possibly work for saving the state; however, as the state is loaded before <code>Uninstall</code> can modify the context, this is no viable solution until Microsoft fixes the above <code>AssemblyInstaller.GetInstallStatePath</code> method.</p>
33,779
<p>Is it possible to initialize an array of pointers to structs? Something like:</p> <pre><code>struct country_t *countries[] = { {"United States of America", "America"}, {"England", "Europe"}, {"Ethiopia", "Africa"} } </code></pre> <p>I want to do that in order to get the entities in not-contiguous memory, and the pointers to them in contiguous memory... But I can't use dynamic memory, so I wonder if it is possible without it.</p>
<p>Well, your code uses structures rather than pointers to structures. There are ways to do what you seek, including:</p> <pre><code>static struct country_t us = { "United States of America", "America" }; static struct country_t uk = { "England", "Europe" }; static struct country_t et = { "Ethiopia", "Africa" }; struct country_t *countries[] = { &amp;us, &amp;uk, &amp;et, }; </code></pre> <p>There are other ways to do it with designated initializers and compound literals in C99. Section 6.5.2.5 'Compound Literals' shows the way:</p> <pre><code>struct country_t *countries[] = { &amp;(struct country_t) { "United States of America", "America" }, &amp;(struct country_t) { "England", "Europe" }, &amp;(struct country_t) { "Ethiopia", "Africa" }, }; </code></pre> <p>The standard illustrates pointers to structures with a function call. Be aware that not all C compilers accept C99 syntax, and these compound literals were not present in C89 (aka C90).</p> <p><em>Edit:</em> Upgraded to use 2-letter ISO 3166 country codes. Also made the named structures into static variables - those symbols were not visible outside the file before (because they did not exist), and now they aren't visible outside the file after, either. I debated whether to make anything const and decided not to - but using const when you can is generally a good idea. Also, in the example, there are 3 countries in 3 continents. Were you to have multiple countries in a single continent (the norm), you might want to be able to share the continent strings. However, whether you can do that safely (or at all) depends on the details of the <code>struct country_t</code> (which were not given), and on whether the program is allowed to update the table (which comes back to the const-ness question).</p>
<p>This works for me:</p> <pre><code> struct country_t { char *fullname; char *shortname; }; struct country_t countries[] = { {"United States of America", "America"}, {"England", "Europe"}, {"Ethiopia", "Africa"} }; int main(int argc, char *argv[]) { return 0; } </code></pre> <p>You could be more terse and use:</p> <pre><code> struct country_t { char *fullname; char *shortname; } countries[] = { {"United States of America", "America"}, {"England", "Europe"}, {"Ethiopia", "Africa"} }; int main(int argc, char *argv[]) { return 0; } </code></pre> <p><strong>Edit:</strong> I found this information at <a href="http://publications.gbdirect.co.uk/c_book/chapter6/initialization.html" rel="nofollow noreferrer">The C Book</a></p>
23,672
<p>Has anyone else seen people do this:</p> <pre><code>private string _name; public string Name{ get{ return _name; } set{ _name = value;}}</code></pre> <p>I understand using accessors if you are going to exercise some sort of control over how it gets set or perform some sort of function on it when there is a get. But if you are just going to do this, why not just make the variable public to begin with? Am I missing something?</p>
<p>If you make the member a public field, then you can't later refactor it into a property without changing the interface to your class. If you expose it as a property from the very beginning, you can make whatever changes to the property accessor functions that you need and the class's interface remains unchanged.</p> <p>Note that as of C# 3.0, you can implement a property without creating a backing field, e.g.:</p> <pre><code>public string Name { get; set; } </code></pre> <p>This removes what is pretty much the only justification for not implementing public fields as properties in the first place.</p>
<p>Preparation. You never know when you'll want to removed the set accessor down the road, perform additional operations in the setter, or change the data source for the get.</p>
20,307
<p>I've got an app on the iTunes store, and Apple provides daily (and weekly) sales reports. I'd like to download these in an automated fashion (say, via script attached to a cron job), but I'm not sure how to get around all their https-forms, Web-objects controls, session-IDs, etc.</p> <p>Does anyone have a plug &amp; play solution for this?</p> <p>Thanks!</p>
<p>There's a thread in the Dev Forums about this: https://devforums.apple.com/thread/1253?start=0&amp;tstart=0'>Sales Reports Script</p> <p>Link: <a href="https://devforums.apple.com/thread/1253?start=0&amp;tstart=0" rel="nofollow noreferrer">https://devforums.apple.com/thread/1253?start=0&amp;tstart=0</a></p>
<p>There's no API but you cant "scrape" it, there are various open source scripts online.</p> <p>Instead though you can use <a href="http://www.appfigures.com" rel="nofollow noreferrer">www.appfigures.com</a> which downloads reports automatically, turns them into interactive sales/downloads reports and sends parsed reports by email automatically as well as shows your reviews from all 77 app stores around the world and rank trending from 6 major app stores.</p> <p>For security reasons I'd use a sub iTC account when signing up.</p> <p>And its completely free (while in beta)</p>
41,284
<p>I am getting ready to completely overhaul my web server. I use it for both development and to present product to clients. It also hosts my company website. I will be loading MS Server 2008 and MS SQL 2008. I want it to have the latest .NET Framework as well as the latest MVC templates. I want it to use SubSonic. I also want to start using some sort of SourceSafe (or whatever a good one is).I plan to use VS 2008 as my development tool.</p> <p>I figure there are a lot of people out there who have recently gone through this and will have good suggestions.</p> <p>It is a good stout machine with lots of memory and storage, so, please let me know anything that will help me become a better developer.</p> <p>Scott and the Dev Team</p>
<p>Well, sounds like you've already got a good list going. Though I'd recommend against SourceSafe. <a href="http://www.highprogrammer.com/alan/windev/sourcesafe.html" rel="nofollow noreferrer">See here for details</a>. SubVersion is a free alternative. Or perhaps git or something like that if you're up for a challenge.</p> <p>[edit to add] If you can afford it, TFS is a nice product that gives you bug tracking, version control, and a build environment. All of those will help you be a better developer. </p> <p>To pimp one of this site's founders, check out the <a href="http://www.joelonsoftware.com/articles/fog0000000043.html" rel="nofollow noreferrer">Joel Test</a> and see what you should implement.</p>
<p>I would recommend to not use the same machine to host apps and develop on. You should at least make a VM to develop in so that there is no accidental interference between dev and live content. </p> <p>Make sure you have all of the known vulerabilites (sp) patched, with all that software there are going to be several exploitable endpoints. </p>
23,302
<p>What are your best usability testing tips? I need quick &amp; cheap. </p>
<p>While aimed at web design, Steve Krug's excellent "<a href="http://www.amazon.co.uk/Dont-Make-Me-Think-Usability/dp/0321344758/ref=sr_1_3?ie=UTF8&amp;s=books&amp;qid=1221780772&amp;sr=8-3" rel="nofollow noreferrer">Don't Make Me Think: A Common Sense Approach To Web Usability</a>" features (in the second edition, at least), a great chapter entitled "Usability Testing On 10 Cents A Day", which I think is applicable to a much wider range of platforms.</p> <p>The chapter specifically deals with usability testing done quick and dirty, in a low-budget (no money and/or no time) environment, and illustrates some of the most important considerations for getting an initial "feel" of the thing.</p> <p>Some of the points I like in particular are:</p> <ul> <li>You don't need to test with a huge number of people (a sentiment also echoed by <a href="http://www.useit.com/alertbox/20000319.html" rel="nofollow noreferrer">Jakob Nielsen</a>)</li> <li>A live reaction is worth a lot; if possible, make sure the developers can see the reaction (perhaps using a video camera and a TV; it doesn't need to be an expensive one)</li> <li>Testing a few people early is better than a lot later</li> </ul> <p>Joel Spolsky is known for advocating "<a href="http://www.joelonsoftware.com/articles/fog0000000043.html" rel="nofollow noreferrer">hallway usability testing</a>", where you grab a few passing users and ask them to complete some simple task. Partly inspired by the "a few users yield the bulk of the results" philosophy, it's also relatively convenient and inexpensive, and can be done every so often.</p>
<p>If you don't know where to begin, start small. Sit a friend down at your computer. Explain that you want them to accomplish a task using software, and watch everything they do.</p> <p>It helps to remain silent while they are actually working. Write everything down. <code>"John spent 15 seconds looking at the screen before acting. He moused over the top nav to see if it contained popup menus. He first clicked "About Us" even though it wasn't central to his task."</code> Etc.</p> <p>Then use the knowledge you gain from this to help you design more elaborate tests. Tests with different users from different knowledge realms. More elaborate tasks and more of them.</p> <p>Film them. A web-cam mounted on the monitor is a good way to capture where their eyes are moving. A video recorder coming over their shoulder at 45 degrees is a good way to capture an overview. Bonus points if you can time-sync the two. Don't worry if you can't do it all. Do what you can do. </p> <p>Don't plan your test as if it's the last one you'll ever need and you want to get it perfect. There is no perfect. The only thing approaching perfection is many iteration and much repetition. You can only approach 100% confidence as the number of tests approaches the number of actual users of your software. Usually nobody even gets close to this number, but everybody should be trying to.</p> <p>And don't forget to re-test people after you incorporated the improvement you saw were needed. Same people, different people, either is ok.</p> <p>Do what you can do. Don't lament what you can't do. Only lament what you could have tested but didn't.</p>
12,338
<p>I've generated a pdf using iTextSharp and I can preview it very well in ASP.Net but I need to send it directly to printer without a preview. I want the user to click the print button and automatically the document prints.</p> <p>I know that a page can be sent directly to printer using the javascript window.print() but I don't know how to make it for a PDF.</p> <p>Edit: it is not embedded, I generate it like this;</p> <pre><code> ... FileStream stream = new FileStream(Request.PhysicalApplicationPath + "~1.pdf", FileMode.Create); Document pdf = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.GetInstance(pdf, stream); pdf.Open(); pdf.Add(new Paragraph(member.ToString())); pdf.Close(); Response.Redirect("~1.pdf"); ... </code></pre> <p>And here I am.</p>
<p>Finally I made it, but I had to use an IFRAME, I defined an IFrame in the aspx and didn't set the src property, in the cs file I made generated the pdf file and set the src property of the iFrame as the generated pdf file name, like this;</p> <pre><code>Document pdf = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.GetInstance(pdf, new FileStream(Request.PhysicalApplicationPath + "~1.pdf", FileMode.Create)); pdf.Open(); //This action leads directly to printer dialogue PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer); writer.AddJavaScript(jAction); pdf.Add(new Paragraph("My first PDF on line")); pdf.Close(); //Open the pdf in the frame frame1.Attributes["src"] = "~1.pdf"; </code></pre> <p>And that made the trick, however, I think that i should implement your solution Stefan, the problem is that I'm new to asp.net and javascript and if I don't have a complete source code I could not code your suggestion but at least is the first step, I was very surprised how much code in html and javascript i need to learn. Thnx. </p>
<p>ALso, try this gem:</p> <pre><code>&lt;link ref="mypdf" media="print" href="mypdf.pdf"&gt; </code></pre> <p>I havent tested it, but what I have read about it, it can be used in this way to let the mypdf.pdf be printed instead of page content whatever method you are using to print the page.</p> <p>Search for media="print" to check out more.</p>
34,030
<p>What is a good complete <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expression</a> or some other process that would take the title:</p> <blockquote> <p>How do you change a title to be part of the URL like Stack Overflow?</p> </blockquote> <p>and turn it into </p> <pre class="lang-none prettyprint-override"><code>how-do-you-change-a-title-to-be-part-of-the-url-like-stack-overflow </code></pre> <p>that is used in the SEO-friendly URLs on Stack&nbsp;Overflow?</p> <p>The development environment I am using is <a href="http://en.wikipedia.org/wiki/Ruby_on_Rails" rel="noreferrer">Ruby on Rails</a>, but if there are some other platform-specific solutions (.NET, PHP, <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="noreferrer">Django</a>), I would love to see those too. </p> <p>I am sure I (or another reader) will come across the same problem on a different platform down the line. </p> <p>I am using custom routes, and I mainly want to know how to alter the string to all special characters are removed, it's all lowercase, and all whitespace is replaced.</p>
<p>Here's how we do it. Note that there are probably more edge conditions than you realize at first glance.</p> <p>This is the second version, unrolled for 5x more performance (and yes, I benchmarked it). I figured I'd optimize it because this function can be called hundreds of times per page.</p> <pre><code>/// &lt;summary&gt; /// Produces optional, URL-friendly version of a title, "like-this-one". /// hand-tuned for speed, reflects performance refactoring contributed /// by John Gietzen (user otac0n) /// &lt;/summary&gt; public static string URLFriendly(string title) { if (title == null) return ""; const int maxlen = 80; int len = title.Length; bool prevdash = false; var sb = new StringBuilder(len); char c; for (int i = 0; i &lt; len; i++) { c = title[i]; if ((c &gt;= 'a' &amp;&amp; c &lt;= 'z') || (c &gt;= '0' &amp;&amp; c &lt;= '9')) { sb.Append(c); prevdash = false; } else if (c &gt;= 'A' &amp;&amp; c &lt;= 'Z') { // tricky way to convert to lowercase sb.Append((char)(c | 32)); prevdash = false; } else if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\\' || c == '-' || c == '_' || c == '=') { if (!prevdash &amp;&amp; sb.Length &gt; 0) { sb.Append('-'); prevdash = true; } } else if ((int)c &gt;= 128) { int prevlen = sb.Length; sb.Append(RemapInternationalCharToAscii(c)); if (prevlen != sb.Length) prevdash = false; } if (i == maxlen) break; } if (prevdash) return sb.ToString().Substring(0, sb.Length - 1); else return sb.ToString(); } </code></pre> <p>To see the previous version of the code this replaced (but is functionally equivalent to, and 5x faster), view revision history of this post (click the date link).</p> <p>Also, the <code>RemapInternationalCharToAscii</code> method source code can be found <a href="https://meta.stackexchange.com/a/7696">here</a>.</p>
<p>Rewrite of Jeff's code to be more concise</p> <pre><code> public static string RemapInternationalCharToAscii(char c) { var s = c.ToString().ToLowerInvariant(); var mappings = new Dictionary&lt;string, string&gt; { { &quot;a&quot;, &quot;àåáâäãåą&quot; }, { &quot;c&quot;, &quot;çćčĉ&quot; }, { &quot;d&quot;, &quot;đ&quot; }, { &quot;e&quot;, &quot;èéêëę&quot; }, { &quot;g&quot;, &quot;ğĝ&quot; }, { &quot;h&quot;, &quot;ĥ&quot; }, { &quot;i&quot;, &quot;ìíîïı&quot; }, { &quot;j&quot;, &quot;ĵ&quot; }, { &quot;l&quot;, &quot;ł&quot; }, { &quot;n&quot;, &quot;ñń&quot; }, { &quot;o&quot;, &quot;òóôõöøőð&quot; }, { &quot;r&quot;, &quot;ř&quot; }, { &quot;s&quot;, &quot;śşšŝ&quot; }, { &quot;ss&quot;, &quot;ß&quot; }, { &quot;th&quot;, &quot;Þ&quot; }, { &quot;u&quot;, &quot;ùúûüŭů&quot; }, { &quot;y&quot;, &quot;ýÿ&quot; }, { &quot;z&quot;, &quot;żźž&quot; } }; foreach(var mapping in mappings) { if (mapping.Value.Contains(s)) return mapping.Key; } return string.Empty; } </code></pre>
4,490
<p>I use <a href="http://www.thekelleys.org.uk/dnsmasq/doc.html" rel="nofollow noreferrer">dnsmasq</a> to resolve DNS queries on my home network. Unfortunately, if a domain name is not known, it will append my own domain name to the request which means that I always end up viewing my own site in a browser.</p> <p>For example, if I enter <a href="http://dlksfhoiahdsfiuhsdf.com" rel="nofollow noreferrer">http://dlksfhoiahdsfiuhsdf.com</a> in a browser, I end up viewing my own site with that URL. If I try something like:</p> <pre><code>host dlksfhoiahdsfiuhsdf.com </code></pre> <p>Instead of the expected:</p> <pre><code>Host dlksfhoiahdsfiuhsdf.com not found: 3(NXDOMAIN) </code></pre> <p>I get this:</p> <pre><code>dlksfhoiahdsfiuhsdf.com.mydomainname.com has address W.X.Y.Z. </code></pre> <p>Clearly, dnsmasq is appending my domain name to impossible name requests in an effort to resolve them, but I'd rather see the not found error instead.</p> <p>I've tried playing with the <em>expand-hosts</em> and <em>domain</em> configuration settings, but to no avail. Is there anything else I can try?</p>
<p>try querying with a trailing dot to explicitly set the root:</p> <pre><code>host dlksfhoiahdsfiuhsdf.com. </code></pre>
<p>I tried removing <em>domain-needed</em> from my own configuration to replicate your issue and it did not produce this behaviour. It's the only other parameter I could find that might be close to relevant.</p> <p>What does your hosts file look like? Maybe something weird is going on there that makes it think all weird domains are local to your network?</p>
2,773
<p>I am making a Color class, and provide a standard constructor like</p> <pre><code>Color(int red, int green, int blue) </code></pre> <p>And then I want to provide an easy way to get the most common colors, like Color.Blue, Color.Red. I see two possible options:</p> <pre><code>public static readonly Color Red = new Color(255, 0, 0); public static Color Red { get { return new Color(255, 0, 0); } } </code></pre> <p>What I don't fully understand is if there is an advantage of one over the other, and how exactly the static keyword works. My thoughts are: The first creates one instance, and then that instance stays in memory for the entire duration of the program, and every time Red is called, this instance is used. The latter only creates something when first used, but creates a new instance every time. If this is correct, then I would argue that if I supply a lot of predefined colors, then the first would use a lot of unnecessary memory? So it is memory usage vs the runtime overhead of instantiating an object every time I guess. </p> <p>Is my reasoning correct? Any advice for best practices when designing classes and use of the static keyword would be great.</p>
<p>I'm guessing that you're probably already aware that the framework provides a <code>Color</code> struct. I'm guessing that you're creating a <code>Color</code> class just for practice.</p> <p>You expressed uncertainty about the meaning of the <code>static</code> keyword, although you've used it correctly. When <code>static</code> is applied to a member of a class or struct, it means that that member belongs to the class as a whole, and does not apply to individual instances. Static data members (fields) are created only once; instances do not get their own copies. Static functions (methods and properties) are called without an instance reference.</p> <p>As far as memory usage goes, I wouldn't worry too much about it in your case. Your <code>Color</code> class shouldn't use more than a few bytes per instance (for instance, the framework's <code>Color</code> structure stores red, green, blue, and alpha in one 32-bit <code>int</code>.). If your <code>Color</code> is a really a <code>class</code> instead of a <code>struct</code>, then you'll have a few more bytes in overhead (each instance will have an additional 32-bit v-table/typeinfo pointer, and each reference is an additional 32-bits), but even so, you're talking about 12 bytes or so per instance. If you have 100 different colors predefined, you'll use &lt;= 1200 bytes. Really no big deal.</p> <p>There are reasons for lazy-instantiation, though. There are classes that <em>do</em> use a lot of memory, and ones that hold on to limited system resources, and ones that take a long time to construct themselves, etc. For these classes it's sometimes better to use a pattern like:</p> <pre><code>class Heavy{ static Heavy first; static Heavy second; public static Heavy First{ get{ if(first == null) first = new Heavy(); return first; } } public static Heavy Second{ get{ if(second == null) second = new Heavy(); return second; } } } </code></pre> <p>Another consideration is mutability. Is your <code>Color</code> class mutable or immutable? In other words, can instances of your class have their value changed, or do they always, once created, represent the same value?</p> <p>If your <code>Color</code> is mutable, then the only correct way to have a static "Red" accessor would be your second example, where you create a new one every access. That way someone can't do something like:</p> <pre><code>Color.Red.G = 255; </code></pre> <p>and make the single shared Color.Red instance actually represent yellow, instead.</p> <p>But also keep in mind that in a case like:</p> <pre><code>for(int y = 0; y &lt; bmp.Height; y++) for(int x = 0; x &lt; bmp.Width; x++) if(bmp.GetPixel(x, y) == Color.Red)) MessageBox.Show("Found a red pixel!"); </code></pre> <p>A <strong>lot</strong> of instances of your <code>Color</code> class are going to be created. They'll be garbage collected later, of course, but this is still a case argument for your first construct above (or the "Heavy" example I gave).</p> <p>Now if your <code>Color</code> is actually a struct, then it's a slightly difference story. There's no heap allocation when you <code>new</code> a struct, and there's no v-table or reference pointer, so the real consideration is then just how long your constructor takes.</p>
<p>It is as you say the first will create create only one instance of the color:</p> <pre><code>public static readonly Color RED = new Color(255, 0, 0); </code></pre> <p>Under the hood I believe that in runtime it will only be instanciated on when it is called for the first time. But I haven't checked it for myself in a debugger though.</p> <p>And as you say with the static getter alternative, that you're providing an implementation of, will fill up the heap uneedingly as you're calling it. The reason is that each invocation will create a <strong>new</strong> object.</p> <p>If you really want to go for the getter alternative but not fill up the heap then at least make the creation of the Color class static as well. Like this:</p> <pre><code>private static readonly Color RED = new Color(255, 0, 0); // RED is created once when it is invoked for the first time. public static Color Red { get { return RED; // Will return a created RED object or create one // for the first time. } } </code></pre>
40,135
<p>I need to repeatedly remove the first line from a huge text file using a bash script.</p> <p>Right now I am using <code>sed -i -e "1d" $FILE</code> - but it takes around a minute to do the deletion.</p> <p>Is there a more efficient way to accomplish this?</p>
<p>Try <a href="http://man7.org/linux/man-pages/man1/tail.1.html" rel="noreferrer">tail</a>:</p> <pre><code>tail -n +2 "$FILE" </code></pre> <p><code>-n x</code>: Just print the last <code>x</code> lines. <code>tail -n 5</code> would give you the last 5 lines of the input. The <code>+</code> sign kind of inverts the argument and make <code>tail</code> print anything but the first <code>x-1</code> lines. <code>tail -n +1</code> would print the whole file, <code>tail -n +2</code> everything but the first line, etc.</p> <p>GNU <code>tail</code> is much faster than <code>sed</code>. <code>tail</code> is also available on BSD and the <code>-n +2</code> flag is consistent across both tools. Check the <a href="https://www.freebsd.org/cgi/man.cgi?query=tail" rel="noreferrer">FreeBSD</a> or <a href="https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/tail.1.html" rel="noreferrer">OS X</a> man pages for more. </p> <p>The BSD version can be much slower than <code>sed</code>, though. I wonder how they managed that; <code>tail</code> should just read a file line by line while <code>sed</code> does pretty complex operations involving interpreting a script, applying regular expressions and the like.</p> <p>Note: You may be tempted to use</p> <pre><code># THIS WILL GIVE YOU AN EMPTY FILE! tail -n +2 "$FILE" &gt; "$FILE" </code></pre> <p>but this will give you an <strong>empty file</strong>. The reason is that the redirection (<code>&gt;</code>) happens before <code>tail</code> is invoked by the shell:</p> <ol> <li>Shell truncates file <code>$FILE</code></li> <li>Shell creates a new process for <code>tail</code></li> <li>Shell redirects stdout of the <code>tail</code> process to <code>$FILE</code></li> <li><code>tail</code> reads from the now empty <code>$FILE</code></li> </ol> <p>If you want to remove the first line inside the file, you should use:</p> <pre><code>tail -n +2 "$FILE" &gt; "$FILE.tmp" &amp;&amp; mv "$FILE.tmp" "$FILE" </code></pre> <p>The <code>&amp;&amp;</code> will make sure that the file doesn't get overwritten when there is a problem.</p>
<p>Would using tail on N-1 lines and directing that into a file, followed by removing the old file, and renaming the new file to the old name do the job?</p> <p>If i were doing this programatically, i would read through the file, and remember the file offset, after reading each line, so i could seek back to that position to read the file with one less line in it.</p>
44,084
<p>I know Windows Vista (and XP) cache recently loaded DLL's in memory...</p> <p>How can this be disabled via the command prompt?</p>
<p>The only thing you can do is disable SuperFetch, which can be done from the command prompt with this command (there has to be a space between the = sign and disabled).</p> <pre><code>sc config Superfetch start= disabled </code></pre> <p>There is a myth out there that you can disable DLL caching, but that only worked for systems prior to Windows 2000. [<a href="http://msdn.microsoft.com/en-us/library/bb776795.aspx" rel="noreferrer">source</a>]</p>
<p>Perhaps it would be helpful to know why you want to do this and then try to help solve the original problem...</p>
5,709
<p>In a recent sharepoint project, I implemented an authentication webpart which should replace the NTLM authentication dialog box. It works fine as long as the user provides valid credentials. Whenever the user provides invalid credentials, the NTLM dialog box pops up in Internet Explorer.</p> <p>My Javascript code which does the authentication via XmlHttpRequest looks like this:</p> <pre><code>function Login() { var request = GetRequest(); // retrieves XmlHttpRequest request.onreadystatechange = function() { if (this.status == 401) { // unauthorized request -&gt; invalid credentials // do something to suppress NTLM dialog box... // already tried location.reload(); and window.location = &lt;url to authentication form&gt;; } } request.open("GET", "http://myServer", false, "domain\\username", "password"); request.send(null); } </code></pre> <p>I don't want the NTLM dialog box to be displayed when the user provides invalid credentials. Instead the postback by the login button in the authentication form should be executed. In other words, the browser should not find out about my unauthorized request.</p> <p>Is there any way to do this via Javascript?</p>
<p><a href="https://stackoverflow.com/users/2199/mark-brackett">Mark</a>'s comment is correct; The NTLM auth prompt is triggered by a 401 response code and the presence of NTLM as the first mechanism offered in the WWW-Authenticate header (Ref: <a href="http://curl.haxx.se/rfc/ntlm.html" rel="nofollow noreferrer">The NTLM Authentication Protocol</a>).</p> <p>I'm not sure if I understand the question description correctly, but I think you are trying to wrap the NTLM authentication for SharePoint, which means you don't have control over the server-side authentication protocol, correct? If you're not able to manipulate the server side to avoid sending a 401 response on failed credentials, then you will not be able to avoid this problem, because it's part of the (client-side) spec:</p> <h3><a href="http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060619/" rel="nofollow noreferrer">The XMLHttpRequest Object</a></h3> <blockquote> <p>If the UA supports HTTP Authentication [RFC2617] it SHOULD consider requests originating from this object to be part of the protection space that includes the accessed URIs and send Authorization headers and handle 401 Unauthorised requests appropriately. if authentication fails, UAs should prompt the users for credentials.</p> </blockquote> <p>So the spec actually calls for the browser to prompt the user accordingly if any 401 response is received in an XMLHttpRequest, just as if the user had accessed the URL directly. As far as I can tell the only way to really avoid this would be for you to have control over the server side and cause 401 Unauthorized responses to be avoided, as Mark mentioned.</p> <p>One last thought is that you may be able to get around this using a proxy, such a separate server side script on another webserver. That script then takes a user and pass parameter and checks the authentication, so that the user's browser isn't what's making the original HTTP request and therefore isn't receiving the 401 response that's causing the prompt. If you do it this way you can find out from your &quot;proxy&quot; script if it failed, and if so then prompt the user again until it succeeds. On a successful authentication event, you can simply fetch the HTTP request as you are now, since everything works if the credentials are correctly specified.</p>
<p>I was able to get this working for all browsers except firefox. See my blog post below from a few years ago. My post is aimed at IE only but with some small code changes it should work in Chrome and safari. </p> <p><a href="http://steve.thelineberrys.com/ntlm-login-with-anonymous-fallback-2/" rel="nofollow">http://steve.thelineberrys.com/ntlm-login-with-anonymous-fallback-2/</a></p> <p>EDIT:</p> <p>The gist of my post is wrapping your JS xml call in a try catch statement. In IE, Chrome, and Safari, this will suppress the NTLM dialog box. It does not seem to work as expected in firefox. </p>
4,939
<p>I've been having tons of problems getting the non-xml configuration for Castle Windsor set up working properly. In the meantime I've seen more and more people giving advice via the Windsor Container fluent interface. I've been Gooogling about for the last day and I cannot find this API anywhere.</p> <p>I am talking about the key .Register() method which seems to be an extension method to the IWindsorContainer object. It seems like it might be in the Castle.MicroKernel.Registration namespace, but I cannot find the corresponding library anywhere!</p> <p>Also, is there any place where I can find documentation for this stuff?</p> <hr> <p><strong>EDIT:</strong> I found that the copy of Castle.MicroKernel in the <a href="http://rhysc.blogspot.com/2008/08/masstransit-classic-webforms.html" rel="nofollow noreferrer">sample project here</a> has more namespaces then the one I was using (even though this one is eight days older and v1.0.0 whereas mine is v1.0.3...), still having trouble finding the .Register() method or any samples though.</p> <p><strong>EDIT:</strong> I found some <a href="http://blog.bittercoder.com/PermaLink,guid,6c1a25f7-5c8c-4a5e-bda9-04ffa944ebd0.aspx" rel="nofollow noreferrer">fluent interface samples at Bitter Coder</a>, no downloadable samples though so I'm still at a loss.</p> <p><strong>Edit Again:</strong> Finally got it. The most recent source code for castle windsor is available <a href="http://builds.castleproject.org/cruise/DownloadBuild.castle" rel="nofollow noreferrer">here</a>, get the most recent successful build, inside the zip file is a bin directory. The fluent interface is inside Castle.Microkernel (you will probably need to reference Castle.Dynaproxy, Castle.Dynaproxy2 and Castle.Windsor too).</p> <p>PS This post is the #1 Google result for "castle fluent interface documentation" sad guys, you need to get on that. <em>Crickets chirp</em> What's that? Fine. Let me figure this out then I'll get on it then.</p>
<p>The Fluent interfaces were introduced a while ago - but are only available on Trunk (after RC3) either grab the castles sources (from the projects subversion repository) and build the IoC projects yourself from <a href="http://svn.castleproject.org:8080/svn/castle/trunk" rel="nofollow noreferrer">here</a>, or easier still grab the <a href="http://builds.castleproject.org/cruise/index.castle" rel="nofollow noreferrer">latest successful build</a> on the continuous integration server and use that.</p> <p><strong>Castle.MicroKernel.Registration</strong> is the name space you'll need to use, in the MicroKernel assembly - once you have a reasonably fresh build of Castle you should be able to find Register(...) methods on both IKernel and IWindsorContainer interfaces, allowing the application of "registration components" (anything which implements IRegistration) which includes the various fluent component registration features in Castle, as well as anything custom you might develop.</p> <p>The best place to ask questions regarding Castle is the google <a href="http://groups.google.com/group/castle-project-users?hl=en" rel="nofollow noreferrer">castle-project-users</a> and <a href="http://groups.google.com/group/castle-project-devel?hl=en" rel="nofollow noreferrer">castle-project-devel</a> groups - keep an eye out for Craig Neuwirt in particular as he's the core developer working on the fluent interface features in Castle Windsor, and so is best equipped to answer questions about the various fluent interface features, as they are not widely documented yet.</p>
<p>Ok, so just for reference. Official, complete documentation for the API is on <a href="http://stw.castleproject.org/Windsor.Fluent-Registration-API.ashx" rel="nofollow noreferrer">Castle Windsor Documentation Wiki</a></p>
14,439
<p>So if I'm using branches that are remote (tracked) branches, and I want to get the lastest, I'm still unclear if I should be doing <code>git pull</code> or <code>git rebase</code>. I thought I had read that doing <code>git rebase</code> when working on a branch with other users, it can screw them up when they pull or rebase. Is that true? Should we all be using <code>git pull</code>?</p>
<p>Git pull is a combination of 2 commands</p> <ul> <li>git fetch (syncs your local repo with the newest stuff on the remote)</li> <li>git merge (merges the changes from the distant branch, if any, into your local tracking branch)</li> </ul> <p>git rebase is only a rough equivalent to git merge. It doesn't fetch anything remotely. In fact it doesn't do a proper merge either, it replays the commits of the branch you're standing on after the new commits from a second branch. </p> <p>Its purpose is mainly to let you have a cleaner history. It doesn't take many merges by many people before the past history in gitk gets terribly spaghetti-like.</p> <p>The best graphical explanation can be seen in the first 2 graphics <a href="http://www.kernel.org/pub/software/scm/git/docs/v1.5.4.3/git-rebase.html" rel="noreferrer">here</a>. But let me explain here with an example.</p> <p>I have 2 branches: master and mybranch. When standing on mybranch I can run</p> <pre><code>git rebase master </code></pre> <p>and I'll get anything new in master inserted before my most recent commits in mybranch. This is perfect, because if I now merge or rebase the stuff from mybranch in master, my new commits are added linearly right after the most recent commits. </p> <p>The problem you refer to happens if I rebase in the "wrong" direction. If I just got the most recent master (with new changes) and from master I rebase like this (before syncing my branch):</p> <pre><code>git rebase mybranch </code></pre> <p>Now what I just did is that I inserted my new changes somewhere in master's past. The main line of commits has changed. And due to the way git works with commit ids, all the commits (from master) that were just replayed over my new changes have new ids.</p> <p>Well, it's a bit hard to explain just in words... Hope this makes a bit of sense :-)</p> <p>Anyway, my own workflow is this:</p> <ul> <li>'git pull' new changes from remote</li> <li>switch to mybranch</li> <li>'git rebase master' to bring master's new changes in my commit history</li> <li>switch back to master</li> <li>'git merge mybranch', which only fast-forwards when everything in master is also in mybranch (thus avoiding the commit reordering problem on a public branch)</li> <li>'git push'</li> </ul> <p>One last word. I strongly recommend using rebase when the differences are trivial (e.g. people working on different files or at least different lines). It has the gotcha I tried to explain just up there, but it makes for a much cleaner history.</p> <p>As soon as there may be significant conflicts (e.g. a coworker has renamed something in a bunch of files), I strongly recommend merge. In this case, you'll be asked to resolve the conflict and then commit the resolution. On the plus side, a merge is much easier to resolve when there are conflicts. The down side is that your history may become hard to follow if a lot of people do merges all the time :-)</p> <p>Good luck!</p>
<p>If you want to pull source without affecting remote branches and without any changes in your local copy, it's best to use git pull.</p> <p>I believe if you have a working branch that you have made changes to, use git rebase to change the base of that branch to be latest remote master, you will keep all of your branch changes, however the branch will now be branching from the master location, rather than where it was previously branched from.</p>
12,218
<p>I have a dataset that I have modified into an xml document and then used a xsl sheet to transform into an Excel xml format in order to allow the data to be opened programatically from my application. I have run into two problems with this:</p> <ol> <li><p>Excel is not the default Windows application to open Excel files, therefore when Program.Start("xmlfilename.xml") is run, IE is opened and the XML file is not very readable.</p></li> <li><p>If you rename the file to .xlsx, you receive a warning, "This is not an excel file, do you wish to continue". This is not ideal for customers.</p></li> </ol> <p>Ideally, I would like Windows to open the file in Excel without modifying the default OS setting for opening Excel files. Office interop is a possibility, but seems like a little overkill for this application. Does anyone have any ideas to make this work?</p> <p>The solution is in .Net/C#, but I am open to other possibilities to create a clean solution.</p>
<pre><code>Process.Start(@"C:\Program Files\Microsoft Office\Officexx\excel.exe", "yourfile.xml"); </code></pre> <p>That being said, you will still get the message box. I suppose that you could use the Interop, but I am not sure how well it will work for you.</p>
<p>As Sam mentioned, the xlsx file extension is probably a good route to go. However, there is more involved than just saving the xml file as xlsx. An xlsx is actually a zip file with a bunch of xml files inside folders. I found some good sample code <a href="http://www.gemboxsoftware.com/Excel2007/DemoApp.htm" rel="nofollow noreferrer">here</a> which seems to give some good explanations although I haven't personally given it a try.</p>
10,369
<p>I have a self built JSP webapp and at the moment I'm using tomcats built in admin pannel to manage user accounts (that are stored in tomcats config xml files) but this is limited because i can not create new accounts from within the web-app (eg. I can not have a sign up website) and need to manually create the accounts. </p> <p>What is the most straight forward way of implementing accounts in a tomcat environment?</p> <p>dennis</p>
<p>Set up a <a href="http://tomcat.apache.org/tomcat-5.5-doc/realm-howto.html" rel="nofollow noreferrer">database realm in Tomcat</a>, either a simple JDBC realm or a DataSource realm that will allow for connection pooling. Then adding users is a very simple CRUD web application, possibly combined with some confirmation emails.</p>
<p>If you are on Windows (not specified in the question) and want to use a windows logon to authenticate you might want to check out <a href="http://jcifs.samba.org/" rel="nofollow noreferrer">JCIFS</a>. JCIFS allows you to obtain the user name of an authenticated windows logon in Java. It is easy to install and relatively foolproof.</p> <p>Not for every situation but in windows only environments it can get you up and running quickly.</p>
17,747
<p>I have a simple table comments <code>(id INT, revision INT, comment VARCHAR(140))</code> with some content like this:</p> <pre><code>1|1|hallo1| 1|2|hallo2| 1|3|hallo3| 2|1|hallo1| 2|2|hallo2| </code></pre> <p>I'm searching for an SQL statement which will return each comment with the highest revision:</p> <pre><code>1|3|hallo3| 2|2|hallo2| </code></pre> <p>I've come up with this solution:</p> <pre><code>select id, revision, comment from comments where revision = ( select max(revision) from comments as f where f.id = comments.id ); </code></pre> <p>but it is very slow on large data sets. Are there any better queries to accomplish this?</p>
<p>Here's one way that with appropriate indexing will not be heinously slow and it doesn't use a subselect:</p> <pre><code>SELECT comments.ID, comments.revision, comments.comment FROM comments LEFT OUTER JOIN comments AS maxcomments ON maxcomments.ID= comments.ID AND maxcomments.revision &gt; comments.revision WHERE maxcomments.revision IS NULL </code></pre> <p>Adapted from queries here: <a href="http://www.xaprb.com/blog/2007/03/14/how-to-find-the-max-row-per-group-in-sql-without-subqueries/" rel="noreferrer">http://www.xaprb.com/blog/2007/03/14/how-to-find-the-max-row-per-group-in-sql-without-subqueries/</a></p> <p>(From google search: max group by sql)</p>
<p>Idea from left field, but what about adding an extra field to the table:</p> <pre><code>CurrentRevision bit not null </code></pre> <p>Then when you make a change, set the flag on the new revision and remove it on all previous ones.</p> <p>Your query would then simply become:</p> <pre><code>select Id, Comment from Comments where CurrentRevision = 1 </code></pre> <p>This would be much easier on the database and therefore much faster.</p>
12,141
<p>So we are building an application with a</p> <ul> <li>UI Layer (web, mobile, Ajax client, etc)</li> <li>Service/API Layer</li> <li>Business Logic Layer </li> <li>Data Access Layer</li> </ul> <p>Our goal is to have an Entity Framework dependency from the Service Layer on down to the DAL. That means the Sevice layer will only accept and return POCOs (plain old CLR objects). </p> <p>What we're currently doing is manually coding a mapping layer between the service layer and business logic layer that will convert POCOs to EF Entities and vice versa. </p> <p>So in short, page has form, form has codebehind that takes form contents, stuffs them into a POCO, sends it to service layer. Service layer converts to EF Entity, sends it to Business Logic Layer which performs certain transformations to the entity, and then interacts with the DAL to get it persisted.</p> <p><strong>Yes, its a bit tedious</strong>, but we were wondering if theres a better way? </p> <p><strong>Yes</strong>, I know someone published an EF Poco Adapter but it's all in C# and we would prefer a VB.NET solution. </p> <p><strong>Yes</strong>, Switching to NHibernate is an option of last resort, as we are already deep into our development cycle.</p>
<p>You should be performing business logic on POCOs. The entire purpose of ORM is that it is an implementation detail. The business logic should be implemented in the domain model and in the domain services - in a business application, "domain" means "business". The DAL should be there to take a POCO and persist it - in your case, that means mapping it to and persisting an EF entity.</p> <p>That's the theoretical / NHibernate model, at any rate.</p>
<p>Can you stand having a dependency in the service layer on the EF <em>interfaces?</em> You could <a href="http://www.sitechno.com/Blog/IntroducingEntityFrameworkContribEasyIPocoImplementationV01.aspx" rel="nofollow noreferrer">implement IPOCO</a>.</p> <p>There's even <a href="http://www.codeplex.com/efcontrib/Wiki/View.aspx?title=PostSharp4EF&amp;referringTitle=Home" rel="nofollow noreferrer" title="PostSharp4EF: Automatically implement IPoco interfaces">a way to do it automatically</a>.</p>
23,508
<p>I know that it's said the PLA becomes brittle when kept in a humid environment, but my case is slightly weirder:</p> <p>I have rolls of 1.75 mm PLA that I bought years ago and they are fine. But if I leave my spool fed inside the PTFE (Teflon) tube of my 3D printer, that part that is inside the PTFE tube, and only that part, gets brittle. The filament spool is always (even when stored) in open air.</p> <p>Is it still the humidity that somehow is better kept inside the tube, or is there a weird reaction of PLA with PTFE?</p>
<p>I have this exact problem as well. I am feeding filament from the dry box through the tube into the top of the hot end. After approximately 2 days I would notice that the filament is broken somewhere close to the hot end. I don't believe that it's just humidity.</p> <p>I suspect that the filament being brittle and being made to conform to the PTFE tube's shape, having been recently on a spool, is causing the breaks.</p> <p>As a result, I'm going to write a small script that will heat the hot end and eject 200 mm of filament every so often.</p> <p>EDIT: Whilst the script works, the filament would just break somewhere else lower down in the tube. Therefore the amount of filament that would need to be extruded periodically would be just wasteful. A better solution would be to unload the filament, either manually or automatically (somehow).</p>
<p>I'm having the exact same problem - it is enough to leave the filament inside the PTFE tube for an overnight and the next day the filament inside the tube is so brittle that I'm not even able to eject the filament without disconnecting the tube and getting out all small pieces of filament manually... but from my experience, it affects only cheap PLA filaments (like Creality ST-PLA) - I never had such issue with other types of filaments (ASA, PETG) or higher-quality brands of PLA (e.g Fillamentum, Filament PM...).</p> <p>BTW - there is a video on YouTube demonstrating the same issue: <div class="youtube-embed"><div> <iframe width="640px" height="395px" src="https://www.youtube.com/embed/SvpSxHLotMI?start=0"></iframe> </div></div></p>
1,990
<p>What is the equivalent of the extended procedure 'xp_dirscan' in SQL Server 2005?</p>
<p>It's not native shipped code in SQL Server. It's a 3rd party extenfed stored proc (which is a DLL).</p> <p>You can register on <a href="http://www.sqlservercentral.com/articles/Administering/sql2000dbatoolkitpart4/2364/" rel="nofollow noreferrer">SQL Server Central and see this article</a> with download and instructions.</p> <p>It's for SQL 2000 but registering the DLL should be the same (I've not tried it on '2005)</p>
<p><code>xp_dirscan</code> seems to be an extended stored proc that performs a recursive directory search. If you have access to the DLL you could register it as an extended stored proc in SQL 2005. </p> <p>Alternatively, you could code something that performs the same action using <code>xp_cmdshell</code> or a managed extended stored proc. </p>
24,876
<p>What's a simple way to combine <strong>feed</strong> and <strong>feed2</strong>? I want the items from <strong>feed2</strong> to be added to <strong>feed</strong>. Also I want to avoid duplicates as <strong>feed</strong> might already have items when a question is tagged with both WPF and Silverlight.</p> <pre><code>Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight"); XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri); SyndicationFeed feed = SyndicationFeed.Load(reader); Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf"); XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri); SyndicationFeed feed2 = SyndicationFeed.Load(reader2); </code></pre>
<p>You can use LINQ to simplify the code to join two lists (don't forget to put System.Linq in your usings and if necessary reference System.Core in your project) Here's a Main that does the union and prints them to console (with proper cleanup of the Reader).</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.ServiceModel.Syndication; namespace FeedUnion { class Program { static void Main(string[] args) { Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight"); SyndicationFeed feed; SyndicationFeed feed2; using(XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri)) { feed= SyndicationFeed.Load(reader); } Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf"); using (XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri)) { feed2 = SyndicationFeed.Load(reader2); } SyndicationFeed feed3 = new SyndicationFeed(feed.Items.Union(feed2.Items)); StringBuilder builder = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(builder)) { feed3.SaveAsRss20(writer); System.Console.Write(builder.ToString()); System.Console.Read(); } } } } </code></pre>
<p>If it's solely for stackoverflow, you can use this :<br> <a href="https://stackoverflow.com/feeds/tag/silverlight%20wpf">https://stackoverflow.com/feeds/tag/silverlight%20wpf</a><br> This <strong>will</strong> do an union of the two tags.</p> <p>For a more general solution, I don't know. You'd probably have to manually iterate the elements of the two feeds and join them together. You can compare the &lt;id> elements of &lt;entry>s to see if they are duplicates.</p>
10,455
<p>I've looked for some other articles on this problem and even tried some of the ideas in <a href="https://stackoverflow.com/questions/8440/visual-studio-optimizations#8539">this thread</a>; however, nothing has solved the issue yet. So, on to the issue.</p> <p>Something happens when working in Visual Studio (usually C#) that causes the IDE to become a bit wonky when saving a file. I will be working along just fine for a while then at some point I notice that every time I save a file (<kbd>Ctrl</kbd>+<kbd>S</kbd>) it becomes very slow.</p> <p>The behavior I notice is this; I hit save in some fashion (<kbd>Ctrl</kbd>+<kbd>S</kbd>, menu, etc...) and in the status bar I see the word <strong>Searching</strong> show up. It looks like it is scanning through all of the loaded namespaces for something, although I have no idea for what or why it is doing so. It causes a real hiccup in workflow since typically I will hit <kbd>Ctrl</kbd>+<kbd>S</kbd> often and keep typing.</p> <p>I have been unable to track down what exactly causes this to start happening. It has happened in multiple project types (web, WPF, console).</p> <p>Has anyone seen this behavior or have any suggestions?</p>
<p>I've had a problem similar to this happen before. Are you using an plugins like ReSharper or DevExpress?</p>
<p>I had similar problem with Visual Studio 2005. </p> <p>I read through several posts (sorry I could not post the links because of: sorry, new users can only post a maximum of one hyperlink).</p> <p>I ran FileMon and discovered that on save the IDE keeps querying C:\Documents and Settings\iguigova\Local Settings\Application Data\Microsoft\WebsiteCache</p> <p>Then I came across this post: <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=347228" rel="nofollow noreferrer">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=347228</a></p> <p>Now I am trying to clear the directory. It was FULL. I plan to set a batch file to delete its contents daily...</p> <p>Good luck!</p>
12,920
<p>Although I don't have an iPhone to test this out, my colleague told me that embedded media files such as the one in the snippet below, only works when the iphone is connected over the WLAN connection or 3G, and does not work when connecting via GPRS.</p> <pre><code>&lt;html&gt;&lt;body&gt; &lt;object data="http://joliclic.free.fr/html/object-tag/en/data/test.mp3" type="audio/mpeg"&gt; &lt;p&gt;alternate text&lt;/p&gt; &lt;/object&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>Is there an example URL with a media file, that will play in an iPhone browser when the iphone connects using GPRS (not 3G)?</p>
<p>The iPhone YouTube application automatically downloads lower quality video when connected via EDGE than when connected via Wi-Fi, because the network is much slower. That fact leads me to believe Apple would make the design decision to not bother downloading an MP3 over EDGE. The browser has no way to know in advance if the bit rate is low enough, and chances are, it won't be. So rather than frustrate the users with a sound file that takes too long to play (and prevents thems from receiving a call while downloading), it's better to spare them the grief and encourage them to find a Wi-Fi hotspot.</p>
<p>I wasn't aware of that limitation. Although it does make sense to disable potentially data-hefty OBJECT or EMBED tags when on the cellular data service for which your provider may be charging by the byte, if that were the reason it wouldn't make sense that it would still work on 3G and only not on GPRS.<br /> Perhaps the problem is one of basic data throughput? Not having an iPhone yourself (or myself) makes it difficult to test your colleague's statement. <br /> Remember that GPRS is much slower than Wi-Fi or 3G. According to Wikipedia, GPRS will provide between 56 and 114 kbps of total duplex throughput, not all of which is in the download direction. You can already see that's not fast enough to instantly stream a typical 128 kbps mp3, even if you were getting the optimal throughput and getting it all as download speed.<br /> Looking at <a href="http://forums.whirlpool.net.au/forum-replies-archive.cfm/832797.html" rel="nofollow noreferrer">this forum discussion</a> as an example that came up on Google, the GPRS customers (the ones not using Telestra, which is an EDGE provider in that area) are getting around 40 kbps. So if as the question implies, you're stuck in EDGEland, NOT 3Gland or anything inbetween, it's going to take about 20 seconds of buffering to play a 30 second mp3. And when you use a behaviour-ambiguous tag like OBJECT or EMBED, there's no guarantee in how the browser will interpret it and whether it's going to try to intelligently stream the file rather than having to download the whole thing before starting it.<br /> So, it's quite possible your colleague just didn't wait long enough to see if whatever embedded media he chose as a test started to play (assuming he wasn't using your 17KB test mp3 there). It's also possible that the iPhone does indeed have this limitation, though I'd think Google would be more forthcoming with it than my quick search uncovered, since people have been vocal enough with other things they don't like about iPhone. Another possibility would be that it's a limitation in the build of Safari that currently ships with the iPhone which might be changed in future versions or in another browser.<br /> Ultimately though, the question is, what kind of user experience do you really want? Embedded audio on GPRS is going to take a long time to load, and users aren't going to enjoy the experience, or potentially even experience it at all if it's supposed to start playing on page visit and it doesn't load before they navigate away. It might not be a goal worth striving towards in that case.</p>
11,279
<p>I have a Jar file, which contains other nested Jars. When I invoke the new <code>JarFile()</code> constructor on this file, I get an exception which says:</p> <blockquote> <p>java.util.zip.ZipException: error in opening zip file</p> </blockquote> <p>When I manually unzip the contents of this Jar file and zip it up again, it works fine.</p> <p>I only see this exception on WebSphere 6.1.0.7 and higher versions. The same thing works fine on tomcat and WebLogic. </p> <p>When I use JarInputStream instead of JarFile, I am able to read the contents of the Jar file without any exceptions.</p>
<p>Make sure your jar file is not corrupted. If it's corrupted or not able to unzip, this error will occur.</p>
<p>Liquibase was getting this error for me. I resolved this after I debugged and watched liquibase try to load the libraries and found that it was erroring on the manifest files for commons-codec-1.6.jar. Essentially, there is either a corrupt zip file somewhere in your path or there is a incompatible version being used. When I did an explore on Maven repository for this library, I found there were newer versions and added the newer version to the pom.xml. I was able to proceed at this point. </p>
42,106
<p>Using Vim I often want to replace a block of code with a block that I just yanked.</p> <p>But when I delete the block of code that is to be replaced, that block itself goes into the register which erases the block I just yanked. So I've got in the habit of yanking, then inserting, then deleting what I didn't want, but with large blocks of code this gets messy trying to keep the inserted block and the block to delete separate.</p> <p>So what is the slickest and quickest way to replace text in Vim?</p> <ul> <li>is there a way to delete text without putting it into the register?</li> <li>is there a way to say e.g. "replace next word" or "replace up to next paragraph"</li> <li>or is the best way to somehow use the multi-register feature?</li> </ul>
<p>To delete something without saving it in a register, you can use the "black hole register":</p> <pre><code>"_d </code></pre> <p>Of course you could also use any of the other registers that don't hold anything you are interested in.</p>
<p>You can make a simple macro with: <code>q&quot;_dwq</code></p> <p>Now to delete the next word without overwriting the register, you can use <code>@d</code></p>
7,789
<p>It is obviously possible to hide individual data points in an Excel line chart.</p> <ul> <li>Select a data point. </li> <li>Right click -> Format Data Point... </li> <li>Select Patterns</li> <li>Tab Set Line to None</li> </ul> <p>How do you accomplish the same thing in VBA? Intuition tells me there should be a property on the <a href="http://msdn.microsoft.com/en-us/library/aa174283(office.11).aspx" rel="nofollow noreferrer">Point object</a> <code>Chart.SeriesCollection(&lt;index&gt;).Points(&lt;index&gt;</code> which deals with this...</p>
<p>"Describe it to the teddy bear" works almost every time...</p> <p>You have to go to the Border child object of the Point object and set its LineStyle to xlNone.</p>
<p>I tried "#N/A" with quotes in Excel 207 and as a result the data point is shown like a zero in the graph. It Works without the quotes.</p>
7,726
<p>I have a user reporting that when they use the back button to return to a web page that they come back as a different person. It seems like they may be accessing a different users profile.</p> <p>Here are the important parts of the code:</p> <pre><code>//here's the code on the web page public static WebProfile p = null; protected void Page_Load(object sender, EventArgs e) { p = ProfileController.GetWebProfile(); if (!this.IsPostBack) { PopulateForm(); } } //here's the code in the "ProfileController" (probably misnamed) public static WebProfile GetWebProfile() { //get shopperID from cookie string mscsShopperID = GetShopperID(); string userName = new tpw.Shopper(Shopper.Columns.ShopperId, mscsShopperID).Email; p = WebProfile.GetProfile(userName); return p; } </code></pre> <p>I'm using static methods and a <code>static WebProfile</code> because I need to use the profile object in a <code>static WebMethod</code> (ajax <code>pageMethod</code>). </p> <ul> <li>Could this lead to the profile object being "shared" by different users? </li> <li>Am I not using static methods and objects correctly?</li> </ul> <hr> <p>The reason I changed <code>WebProfile</code> object to a <code>static</code> object was because I need to access the profile object within a <code>[WebMethod]</code> (called from javascript on the page). </p> <ul> <li>Is there a way to access a profile object within a <code>[WebMethod]</code>? </li> <li>If not, what choices do I have?</li> </ul>
<p>In Perl:</p> <pre><code>#!/usr/local/bin/perl -w if (@ARGV != 2) { print "Usage: watchit.pl &lt;cmd&gt; &lt;str&gt;\n"; exit(1); } $cmd = $ARGV[0]; $str = $ARGV[1]; while (1) { my $output = `$cmd`; print $output; # or dump to file if desired if ($output =~ /$str/) { exit(0); } } </code></pre> <p>Example:</p> <pre><code>[bash$] ./watchit.pl ls stop watchit.pl watchit.pl~ watchit.pl watchit.pl~ ... # from another terminal type "touch stop" stop watchit.pl watchit.pl~ </code></pre> <p>You might want to add a sleep in there, though.</p>
<pre><code>while (/bin/true); do OUTPUT=`/some/command` if [[ "x$OUTPUT" != "x" ]]; then echo $OUTPUT break fi sleep 1 done </code></pre>
15,670
<p>I am developing iPhone application and In that application I've one <code>TableViewController</code>, and that <code>TableViewController</code> made up of Custom table cell.<br> into those cell I am loading image from URL, but the <code>scrolling</code> is not that smooth, (because each cell load images every time when scrolling happen).</p> <p>So I decided to store those images into application document folder, but I don't know how to use document folder in iPhone when application is in running state.</p> <p>Any suggestion?</p> <p>And on other forums I found that SQLITE has blob datatype to store binary data,</p> <p>Which method is efficient, document folder or sqlite to store image?</p>
<p>Storing the images on the device may improve things somewhat, but it will not make scrolling really smooth. The reason scrolling tends to become choppy is that a synchronous function in your cell code means that you are blocking the run loop, which prevents animation. If you want to speed up scrolling you need to get rid of the blocking event, by making it asynchronous (though this still may result it chunky scrolling if you're asynch callbacks take a lot of CPU time), or moving the blocking code off the main thread.</p> <p>If you move your loads off the main thread then either individual files or an sqlite3 database will work fine. The other big issue you will find is that cells are not updated while scrolling. That means if you perform an asynch image load in responds to the cell loading the image will not appear in the cell until the user is done scrolling, which is generally not the desired experience. In order to do avoid that you need to predictively load the images into ram before the user scrolls over them.</p>
<p>You could use <code>NSFileManager</code> 's <code>createFileAtPath</code> to save any <code>NSData</code> into a file.</p> <p>To get the Documents directory, use this:</p> <pre><code>NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; </code></pre>
29,999
<p>I am creating a WordML document from an xml file whose elements sometimes contain html-formatted text. </p> <pre><code>&lt;w:p&gt; &lt;w:r&gt; &lt;w:t&gt; html formatted content is in here taken from xml file! &lt;/w:t&gt; &lt;/w:r&gt; &lt;/w:p&gt; </code></pre> <p>This is how my templates are sort of set up. I have a recursive call-template function that does text replacement against the source xml content. When it comes across a "<code>&lt;b&gt;</code>" tag, I output a string in CDATA containing "<code>&lt;/w:t&gt;&lt;/w:r&gt;&lt;w:r&gt;&lt;w:rPr&gt;&lt;w:b/&gt;&lt;/w:rPr&gt;&lt;w:t&gt;</code>" to close the current run and start up a new run with bold formatting enabled. when it gets to a "<code>&lt;/b&gt;</code>" tag, it replaces it with the following CDATA string "<code>&lt;/w:t&gt;&lt;/w:r&gt;&lt;w:r&gt;&lt;w:t&gt;</code>".</p> <p>What I'd like to do is use XSL to close the run tag and start a new run without using CDATA string inserts. Is this possible?</p>
<p>Working with WordML is tricky. One tip when converting arbitrary XML to WordML using XSLT is to not worry about the text runs when processing blocks, but to instead create a template that matches text() nodes directly, and create the text runs there. It turns out that Word doesn't care if you nest text runs, which makes the problem much easier to solve.</p> <pre><code> &lt;xsl:template match="text()" priority="1"&gt; &lt;w:r&gt; &lt;w:t&gt; &lt;xsl:value-of select="."/&gt; &lt;/w:t&gt; &lt;/w:r&gt; &lt;/xsl:template&gt; &lt;xsl:template match="@*|node()"&gt; &lt;xsl:apply-templates select="@*|node()"/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="para"&gt; &lt;w:p&gt; &lt;xsl:apply-templates select="text() | *" /&gt; &lt;/w:p&gt; &lt;/xsl:template&gt; &lt;xsl:template match="b"&gt; &lt;w:r&gt; &lt;w:rPr&gt; &lt;w:b /&gt; &lt;/w:rPr&gt; &lt;w:t&gt;&lt;xsl:apply-templates /&gt;&lt;/w:t&gt; &lt;/w:r&gt; &lt;/xsl:template&gt; </code></pre> <p>This avoids the bad XSLT technique of inserting tags directly as escaped text. You'll end up with the bold tag as a nested text run, but as I said, Word couldn't care less. If you use this technique, you'll need to be careful to not apply templates to the empty space between paragraphs, since it will trigger the text template and create an out-of-context run.</p>
<p>I can most probably help you if only I understood your problem... Is the html in a CDATA section or is it parsed as part of the input doc (and thus well-formed XML)? Since you talk about 'text replacement' I'll assume that you treat the 'html formatted content' as a single string (CDATA) and therefor need a recursive call-template function to perform string replacement. The only way you're going to be able to use an XSL matching template to do what you're doing now is to make the html part of the parsed document (your input document). In such a case you could just match the <code>b</code> tag and replace it with the appropriate output (again: this assumes that it can always be parsed as valid XML). Your problem now has shifted... since (if I understood your problem correctly) what you're trying to do is close the <code>w:t</code> and <code>w:r</code> elements and then 'reopen' them... this is hard because it's (as you probably suspect) very hard to do this nicely in XSLT (you cannot just create an element in template A and then close it in template B). You'll have to start messing with unescaped output etc. to make this happen. I now I've made a lot of assumptions but here is a small example to help you on your way:</p> <p><em>input.xml</em></p> <pre><code>&lt;doc xmlns:w="urn:schemas-microsoft-com:office:word"&gt; &lt;w:p&gt; &lt;w:r&gt; &lt;w:t&gt;before&lt;b&gt;bold&lt;/b&gt;after&lt;/w:t&gt; &lt;/w:r&gt; &lt;/w:p&gt; &lt;/doc&gt; </code></pre> <p><em>convert_html.xsl</em></p> <p></p> <pre><code>&lt;xsl:template match="@*|node()"&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select="@*|node()"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="/doc/w:p/w:r/w:t//b"&gt; &lt;xsl:value-of select="'&amp;lt;/w:t&gt;&amp;lt;/w:r&gt;&amp;lt;w:r&gt;&amp;lt;w:rPr&gt;&amp;lt;w:b/&gt;&amp;lt;/w:rPr&gt;&amp;lt;w:t&gt;'" disable-output-escaping="yes" /&gt; &lt;xsl:apply-templates select="@*|node()"/&gt; &lt;xsl:value-of select="'&amp;lt;/w:t&gt;&amp;lt;/w:r&gt;&amp;lt;w:r&gt;&amp;lt;w:t&gt;'" disable-output-escaping="yes" /&gt; &lt;/xsl:template&gt; </code></pre> <p></p> <p>Now running </p> <pre><code>xalan input.xml convert_html.xsl </code></pre> <p>produces</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;doc xmlns:w="urn:schemas-microsoft-com:office:word"&gt; &lt;w:p&gt; &lt;w:r&gt; &lt;w:t&gt;before&lt;/w:t&gt;&lt;/w:r&gt;&lt;w:r&gt;&lt;w:rPr&gt;&lt;w:b/&gt;&lt;/w:rPr&gt;&lt;w:t&gt;bold&lt;/w:t&gt;&lt;/w:r&gt;&lt;w:r&gt;&lt;w:t&gt;after&lt;/w:t&gt; &lt;/w:r&gt; &lt;/w:p&gt; &lt;/doc&gt; </code></pre> <p>which I guess is what you wanted.</p> <p>Hope this helps you somewhat.</p>
28,987
<p>I would like to use an add-in like simple-modal or the dialog add-in in the UI kit. However, how do I use these or any other and get a result back. Basically I want the modal to do some AJAX interaction with the server and return the result for the calling code to do some stuff with.</p>
<p>Here is how the confirm window works on simpleModal:</p> <pre><code>$(document).ready(function () { $('#confirmDialog input:eq(0)').click(function (e) { e.preventDefault(); // example of calling the confirm function // you must use a callback function to perform the "yes" action confirm("Continue to the SimpleModal Project page?", function () { window.location.href = 'http://www.ericmmartin.com/projects/simplemodal/'; }); }); }); function confirm(message, callback) { $('#confirm').modal({ close: false, overlayId: 'confirmModalOverlay', containerId: 'confirmModalContainer', onShow: function (dialog) { dialog.data.find('.message').append(message); // if the user clicks "yes" dialog.data.find('.yes').click(function () { // call the callback if ($.isFunction(callback)) { callback.apply(); } // close the dialog $.modal.close(); }); } }); } </code></pre>
<p>Since the modal dialog is on the page, you're free to set any document variable you want. However all of the modal dialog scripts I've seen included a demo using the return value, so it's likely on that page.</p> <p>(the site is blocked for me otherwise I'd look)</p>
7,272
<p>Is there anything we can do either in code (ASP/JavaScript) or in Excel so that the comma separated values end up in separate columns in Excel?</p>
<p>once it is imported, you can go to 'Tools' -> 'Text to Columns...' menu and specify a delimiting character.</p>
<p>If you open the file via Excel's 'File --> Open' menu, then it will separate the values in the cells.</p>
36,959
<p>If I go to www.paypal.com, Firefox displays a huge icon in the location bar. Is it possible to get my web site to do this without paying $2700 to Verisign? Where is the best place to buy SSL certificates and not break the bank?</p>
<p>You're talking about EV (extended validation) SSL. <a href="http://www.digicert.com/ev-ssl-certification.htm" rel="nofollow noreferrer">Digicert</a> are very competitive for this ($488 per year) and also standard SSL certificates. Whoever you go for though, make sure you check what browser compatibility they have as some of the cheaper ones do not have as wide support as the more expensive ones meaning you're kinda getting what you pay for.</p> <p><strong>Edit:</strong> also, EV is only supported on the more recent browsers (not IE6 for example).</p>
<p>To get the green bar, your CA needs to pass an audit. Be sure that you're buying an Extended Validation cert, and using https.</p>
12,350
<p>I've got my brand new VS2008 and decided to convert my main solution from VS2005. One of the projects is a SQL2005 reporting services project. Now that I've converted I cannot load it in VS2008. Is there anyway around this? </p> <p>My problem is that my solution is a hybrid and has websites libraries and reports in there. Separating it out breaks the logic the solution entity.</p>
<p>As you have guessed, the baseAddresses element is completely ignored when hosting in IIS. The service's base address is determined by the web site &amp; virtual directory into which your wcf service is placed.</p> <p>Even when self-hosting, baseAddresses is not required. It is merely a convenience that avoids you having to enter a full address for each endpoint. If it is present, the endpoints can have relative addresses (relative to the base address, that is).</p>
<p>base address required for selfhosting. IIS/WAS hosts ignores the base address.</p>
8,014
<p>I'm using freemarker, SiteMesh and Spring framework. For the pages I use ${requestContext.getMessage()} to get the message from message.properties. But for the decorators this doesn't work. How should I do to get the internationalization working for sitemesh?</p>
<p>You have to use the <strong><em>fmt</em></strong> taglib.</p> <p>First, add the taglib for sitemesh and fmt on the fisrt line of the decorator.</p> <pre><code>&lt;%@ taglib prefix="decorator" uri="http://www.opensymphony.com/sitemesh/decorator"%&gt; &lt;%@ taglib prefix="page" uri="http://www.opensymphony.com/sitemesh/page"%&gt; &lt;%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%&gt; &lt;%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt"%&gt; &lt;fmt:setBundle basename="messages" /&gt; </code></pre> <p>In my example, the i18n file is messages.properties. Then you need to use the fmt tag to use the mesages.</p> <pre><code>&lt;fmt:message key="key_of_message" /&gt; </code></pre>
<p>If you prefer templates and the freemarker servlet instead you can enter the following in your templates:</p> <pre><code>&lt;#assign fmt=JspTaglibs["http://java.sun.com/jstl/fmt"]&gt; &lt;@fmt.message key="webapp.name" /&gt; </code></pre> <p>and in your <code>web.xml</code>:</p> <pre><code>&lt;context-param&gt; &lt;param-name&gt;javax.servlet.jsp.jstl.fmt.localizationContext&lt;/param-name&gt; &lt;param-value&gt;messages&lt;/param-value&gt; &lt;/context-param&gt; </code></pre>
12,262
<p>Can dynamic variables in C# 4.0 be members on a class or passed into or returned from methods? var from C# 3.0 couldn't but I haven't seen any mention anywhere of whether it is possible or not with dynamic.</p>
<p>All of the above. I tried them out in the VPC and was able to do all of these. See the <a href="http://code.msdn.microsoft.com/csharpfuture" rel="noreferrer">'New Features in C#' document here</a></p>
<p>This code snippet from the book "CLR via C#, 3rd Ed" shows dynamic in action :</p> <pre><code>using System; using System.Dynamic; static class DyanmicDemo { public static void Main() { for(Int32 demo =0; demo &lt; 2; demo++) { dynamic arg = (demo == 0) ? (dynamic) 5 : (dynamic) "A"; dynamic result = Plus(arg); M(result); } } private static dynamic Plus(dynamic arg) { return arg + arg; } private static void M(Int32 n) { Console.WriteLine("M(Int32): " + n); } private static void M(String s) { Console.WriteLine("M(String): " + s); } } </code></pre> <p>When I execute Main, I get the following output:</p> <p>M(Int32): 10</p> <p>M(String): AA</p>
30,372
<p>How can I bind arguments to a Python function so that I can call it later without arguments (or with fewer additional arguments)?</p> <p>For example:</p> <pre><code>def add(x, y): return x + y add_5 = magic_function(add, 5) assert add_5(3) == 8 </code></pre> <p>What is the <code>magic_function</code> I need here?</p> <hr /> <p><sub>It often happens with frameworks and libraries that people accidentally call a function immediately when trying to give arguments to a callback: for example <code>on_event(action(foo))</code>. The solution is to bind <code>foo</code> as an argument to <code>action</code>, using one of the techniques described here. See for example <a href="https://stackoverflow.com/questions/6920302">How to pass arguments to a Button command in Tkinter?</a> and <a href="https://stackoverflow.com/questions/21962763/">Using a dictionary as a switch statement in Python</a>.</sub></p> <p><sub>Some APIs, however, allow you to pass the to-be-bound arguments separately, and will do the binding for you. Notably, the threading API in the standard library works this way. See <a href="https://stackoverflow.com/questions/11792629">thread starts running before calling Thread.start</a>.</sub></p> <p><sub>Explicitly binding arguments is also a way to avoid problems caused by late binding when using closures. This is the problem where, for example, a <code>lambda</code> inside a <code>for</code> loop or list comprehension produces separate functions that compute the same result. See <a href="https://stackoverflow.com/questions/2295290/">What do lambda function closures capture?</a> and <a href="https://stackoverflow.com/questions/3431676/">Creating functions (or lambdas) in a loop (or comprehension)</a>.</sub></p>
<p><a href="http://docs.python.org/2/library/functools.html#functools.partial" rel="noreferrer" title="Python 2 Documentation: functools module: partial function"><code>functools.partial</code></a> returns a callable wrapping a function with some or all of the arguments frozen.</p> <pre class="lang-py prettyprint-override"><code>import sys import functools print_hello = functools.partial(sys.stdout.write, "Hello world\n") print_hello() </code></pre> <pre class="lang-none prettyprint-override"><code>Hello world </code></pre> <p>The above usage is equivalent to the following <code>lambda</code>.</p> <pre><code>print_hello = lambda *a, **kw: sys.stdout.write("Hello world\n", *a, **kw) </code></pre>
<p>Functors can be defined this way in Python. They're callable objects. The "binding" merely sets argument values.</p> <pre><code>class SomeFunctor( object ): def __init__( self, arg1, arg2=None ): self.arg1= arg1 self.arg2= arg2 def __call___( self, arg1=None, arg2=None ): a1= arg1 or self.arg1 a2= arg2 or self.arg2 # do something return </code></pre> <p>You can do things like</p> <pre><code>x= SomeFunctor( 3.456 ) x( arg2=123 ) y= SomeFunctor( 3.456, 123 ) y() </code></pre>
35,075
<p>I need to create an access (mdb) database without using the ADOX interop assembly. </p> <p>How can this be done?</p>
<p>Before I throw away this code, it might as well live on stackoverflow </p> <p>Something along these lines seems to do the trick: </p> <pre><code>if (!File.Exists(DB_FILENAME)) { var cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DB_FILENAME; // Use a late bound COM object to create a new catalog. This is so we avoid an interop assembly. var catType = Type.GetTypeFromProgID("ADOX.Catalog"); object o = Activator.CreateInstance(catType); catType.InvokeMember("Create", BindingFlags.InvokeMethod, null, o, new object[] {cnnStr}); OleDbConnection cnn = new OleDbConnection(cnnStr); cnn.Open(); var cmd = cnn.CreateCommand(); cmd.CommandText = "CREATE TABLE VideoPosition (filename TEXT , pos LONG)"; cmd.ExecuteNonQuery(); } </code></pre> <p>This code illustrates that you can access the database using OleDbConnection once its created with the ADOX.Catalog COM component. </p>
<p>You don't need Jet(major headache) installed, if you use this connection string in .net 3.5 </p> <pre><code>Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccess2007file.accdb;Persist Security Info=False; </code></pre> <p>This should work on access 2007 and below</p>
18,850
<p>I had an odd problem today when I was trying to serialize an object. The object was generated via "Add service reference" from a web service (svcutil.exe). </p> <p>The problem was that the below property (agencyId) was not being serialized with the rest of the object. Out of desperation I commented the property below it because it had the "XMLIgnoreAttribute" assigned... after I commented the ignored property, the agencyId field serialized as expected. </p> <p>Can someone please explain to me why this behavior occurred? Thanks!!</p> <pre><code> /// &lt;remarks/&gt; [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)] public string agencyId { get { return this.agencyIdField; } set { this.agencyIdField = value; this.RaisePropertyChanged("agencyId"); } } /// &lt;remarks/&gt; [System.Xml.Serialization.XmlIgnoreAttribute()] public bool agencyIdSpecified { get { return this.agencyIdFieldSpecified; } set { this.agencyIdFieldSpecified = value; this.RaisePropertyChanged("agencyIdSpecified"); } } </code></pre>
<p>There is a pattern (for XmlSerializer), that a property Foo will also look for either "bool FooSpecified", or "bool ShouldSerializeFoo()" - and if found, only serialize Foo if this other member returns true. So I assume that agencyIdSpecified had never been set to true? Removing this member would make it always serialize (unless you add a <code>[DefaultValue]</code> or similar).</p> <p>This type of behaviour is used to model optional values on the occasion that we really need to know whether it was in the original data - i.e. does it have the value 0 because the caller told us that number, or because that is simply the default.</p> <p>Note that the "FooSpecified" member commonly has <code>[XmlIgnore]</code> so that XmlSerializer knows that it shouldn't be considered as data for serialization. This isn't necessary (or legal, in fact) with "ShouldSerializeFoo()", since methods are never serialized.</p>
<p>The purpose of XmlIgnoreAttribute is to tell the XmlSerializer that you don't want to serialize that property: it's the whole point. So what you're seeing is the designed behavior of that code. A much better question would be why the class implementor chose to decorate that property in that way.</p>
25,602
<p>I'm really stumped on this one. I want to output a list and have the tag file take care of commas, singular versus plural, etc. but when I display the list it completely ignores whitespace so everythingrunstogetherlikethis. I tried using the HTML entities "thinsp", "ensp" and "emsp" (I can't use "nbsp", these have to be breaking), but they're all hideously wide on IE except thinsp which is way too skinny on everything else.</p> <p>Edit: won't work. The output from the tag has no spaces at all. Although any content in the JSP has normal spacing. Obviously I could just put everything in the JSP but this is code that goes on multiple JSPs, so tag files would make a lot of sense.</p>
<p>It's actually a bug in the EL parser which causes spaces in between EL expressions to be eaten. E.g.</p> <pre><code>${bean.foo} ${bean.bar} ${bean.waa} </code></pre> <p>would get printed as (assuming that they returns the very same String value as its property name is):</p> <pre><code>foobarwaa </code></pre> <p>I recall that this issue was reported somewhere before, but I can't seem to find it right now. As far now you can fix it by using JSTL <code>c:out</code> tag:</p> <pre><code>&lt;c:out value="${bean.foo} ${bean.bar} ${bean.waa}" /&gt; </code></pre> <p>which correctly get printed as:</p> <pre><code>foo bar waa </code></pre>
<p>So you are saying your <em>tag</em> doesn't print out white space at all? Is there any whitespace for it to print out?</p> <p>Can you post the code, and a short example of how you use it?</p>
30,374
<p>Has anyone found a useful solution to the DesignMode problem when developing controls?</p> <p>The issue is that if you nest controls then DesignMode only works for the first level. The second and lower levels DesignMode will always return FALSE.</p> <p>The standard hack has been to look at the name of the process that is running and if it is "DevEnv.EXE" then it must be studio thus DesignMode is really TRUE.</p> <p>The problem with that is looking for the ProcessName works its way around through the registry and other strange parts with the end result that the user might not have the required rights to see the process name. In addition this strange route is very slow. So we have had to pile additional hacks to use a singleton and if an error is thrown when asking for the process name then assume that DesignMode is FALSE.</p> <p>A nice clean way to determine DesignMode is in order. Acually getting Microsoft to fix it internally to the framework would be even better!</p>
<p>Revisiting this question, I have now 'discovered' 5 different ways of doing this, which are as follows:</p> <pre><code>System.ComponentModel.DesignMode property System.ComponentModel.LicenseManager.UsageMode property private string ServiceString() { if (GetService(typeof(System.ComponentModel.Design.IDesignerHost)) != null) return "Present"; else return "Not present"; } public bool IsDesignerHosted { get { Control ctrl = this; while(ctrl != null) { if((ctrl.Site != null) &amp;&amp; ctrl.Site.DesignMode) return true; ctrl = ctrl.Parent; } return false; } } public static bool IsInDesignMode() { return System.Reflection.Assembly.GetExecutingAssembly() .Location.Contains("VisualStudio")) } </code></pre> <p>To try and get a hang on the three solutions proposed, I created a little test solution - with three projects: </p> <ul> <li>TestApp (winforms application), </li> <li>SubControl (dll) </li> <li>SubSubControl (dll)</li> </ul> <p>I then embedded the SubSubControl in the SubControl, then one of each in the TestApp.Form.</p> <p>This screenshot shows the result when running. <img src="https://i.stack.imgur.com/pylfS.png" alt="Screenshot of running"></p> <p>This screenshot shows the result with the form open in Visual Studio:</p> <p><img src="https://i.stack.imgur.com/4cgxt.png" alt="Screenshot of not running"></p> <p>Conclusion: It would appear that <em>without reflection</em> the only one that is reliable <em>within</em> the constructor is LicenseUsage, and the only one which is reliable <em>outside</em> the constructor is 'IsDesignedHosted' (by <a href="https://stackoverflow.com/questions/34664/designmode-with-controls/2693338#2693338">BlueRaja</a> below)</p> <p>PS: See ToolmakerSteve's comment below (which I haven't tested): "Note that <a href="https://stackoverflow.com/a/2693338/199364">IsDesignerHosted</a> answer has been updated to include LicenseUsage..., so now the test can simply be if (IsDesignerHosted). An alternative approach is <a href="https://stackoverflow.com/a/2849244/199364">test LicenseManager in constructor and cache the result</a>."</p>
<p>I had to fight this problem recently in Visual Studio 2017 when using nested UserControls. I combine several of the approaches mentioned above and elsewhere, then tweaked the code until I had a decent extension method which works acceptably so far. It performs a sequence of checks, storing the result in static boolean variables so so each check is only performed at most only once at run time. The process may be overkill, but it is keeping the code from executing in studio. Hope this helps someone.</p> <pre><code> public static class DesignTimeHelper { private static bool? _isAssemblyVisualStudio; private static bool? _isLicenseDesignTime; private static bool? _isProcessDevEnv; private static bool? _mIsDesignerHosted; /// &lt;summary&gt; /// Property &lt;see cref="Form.DesignMode"/&gt; does not correctly report if a nested &lt;see cref="UserControl"/&gt; /// is in design mode. InDesignMode is a corrected that property which . /// (see https://connect.microsoft.com/VisualStudio/feedback/details/553305 /// and https://stackoverflow.com/a/2693338/238419 ) /// &lt;/summary&gt; public static bool InDesignMode( this Control userControl, string source = null) =&gt; IsLicenseDesignTime || IsProcessDevEnv || IsExecutingAssemblyVisualStudio || IsDesignerHosted(userControl); private static bool IsExecutingAssemblyVisualStudio =&gt; _isAssemblyVisualStudio ?? (_isAssemblyVisualStudio = Assembly .GetExecutingAssembly() .Location.Contains(value: "VisualStudio")) .Value; private static bool IsLicenseDesignTime =&gt; _isLicenseDesignTime ?? (_isLicenseDesignTime = LicenseManager.UsageMode == LicenseUsageMode.Designtime) .Value; private static bool IsDesignerHosted( Control control) { if (_mIsDesignerHosted.HasValue) return _mIsDesignerHosted.Value; while (control != null) { if (control.Site?.DesignMode == true) { _mIsDesignerHosted = true; return true; } control = control.Parent; } _mIsDesignerHosted = false; return false; } private static bool IsProcessDevEnv =&gt; _isProcessDevEnv ?? (_isProcessDevEnv = Process.GetCurrentProcess() .ProcessName == "devenv") .Value; } </code></pre>
5,498
<p>I want to do something like this:</p> <pre><code>const MyFirstConstArray: array[0..1] of string = ('Hi', 'Foo'); MySecondConstArrayWhichIncludesTheFirstOne: array[0..2] of string = MyFirstConstArray + ('Bar'); </code></pre> <p>Basically I want the following result:</p> <pre><code>MyFirstConstArray -&gt; ('Hi', 'Foo'); MySecondConstArrayWhichIncludesTheFirstOne -&gt; ('Hi', 'Foo', 'Bar'); </code></pre> <p>Is it possible somehow?</p>
<p>AFAIK, you can't do that.<br> But if the goal is to ensure you declare your actual constant string only once, I suggest you declare the individual strings and then group them in arrays: </p> <pre><code>const MyConst1 = 'Hi'; MyConst2 = 'Foo'; MyConst3 = 'Bar'; MyFirstConstArray: array[0..1] of string = (MyConst1, MyConst2); MySecondConstArrayWhichIncludesTheFirstOne: array[0..2] of string = (MyConst1, MyConst2, MyConst3); </code></pre> <p>BTW, your syntax is incorrect, you have to precise the type of the array elements.</p>
<p>I don't think so. You'll have to do it in code. If these are global constants, you can do the initialization in the 'initialization' section of the unit.</p>
30,668
<p>I was shocked to learn that OpenMosix is <a href="http://openmosix.sourceforge.net/" rel="nofollow noreferrer">closed</a>. Can you suggest any similar free tool for linux. </p> <p>For those who don't know, OpenMosix is</p> <blockquote> <p>a software package that turns networked computers running GNU/Linux into a cluster. It automatically balances the load between different nodes of the cluster, and nodes can join or leave the running cluster without disruption of the service. The load is spread out among nodes according to their connection and CPU speeds. </p> </blockquote> <p>The nicest part is that you don't need to link your programs with any special libraries neither do you need to modify your programs. Just "fork and forget".</p> <p>Another nice (but not must have) feature is the fact that it doesn't have to be installed on dedicated computers, but can sit on various desktop computers in your organization/lab/home etc.</p> <p>I'm aware of the names of several possible solutions (<a href="http://en.wikipedia.org/wiki/Single-system_image" rel="nofollow noreferrer">for example</a>). I'm looking for personal experience and/or nice reviews</p> <p><strong>EDIT</strong> <a href="http://www.mosix.org/" rel="nofollow noreferrer">Mosix</a>, the predecessor of OpenMosix, used to be free (as free beer). However, now it costs <a href="http://www.mosix.com.au/prices.html" rel="nofollow noreferrer">money</a></p>
<p>I'm not sure how it compares feature-wise to OpenMosix, but <a href="http://www.rocksclusters.org/" rel="nofollow noreferrer">Rocks</a> is an open source cluster Linux distro.</p> <p><a href="http://www.rocksclusters.org/wordpress/?page_id=57" rel="nofollow noreferrer">From the website</a>:</p> <blockquote> <p>Rocks is an open-source Linux cluster distribution that enables end users to easily build computational clusters, grid endpoints and visualization tiled-display walls. Hundreds of researchers from around the world have used Rocks to deploy their own cluster</p> </blockquote> <p>You may want to listen to <a href="http://twit.tv/floss30" rel="nofollow noreferrer">this episode of FLOSS Weekly</a> that is all about Rocks.</p>
<p>I looked here to get an update as I have not used openmosix since graduating, but there is now a new tech called "Mesh Computing", and also the ether of bitcoin, so processes must transport the means of getting their data to a suitable node in a secure manner, and then try to run in a fault tolerant manner. I think the answer is a HURD, which before the mesh was more of a pipe dream. I think you should go to <a href="https://www.gnu.org/software/hurd/hurd.html" rel="nofollow noreferrer">https://www.gnu.org/software/hurd/hurd.html</a> and pitch in if you have time. The mesh is upon us and there is no access to anything except agent hosting on mesh.</p>
35,111
<p>I am currently validating a client's HTML Source and I am getting a lot of validation errors for images and input files which do not have the Omittag. I would do it manually but this client literally has thousands of files, with a lot of instances where the is not .</p> <p>This client has validated some img tags (for whatever reason).</p> <p>Just wondering if there is a unix command I could run to check to see if the does not have a Omittag to add it.</p> <p>I have done simple search and replaces with the following command:</p> <pre><code>find . \! -path '*.svn*' -type f -exec sed -i -n '1h;1!H;${;g;s/&lt;b&gt;/&lt;strong&gt;/g;p}' {} \; </code></pre> <p>But never something this large. Any help would be appreciated.</p>
<p>Try this. It'll go through your files, make a <code>.orig</code> backup of each file (perl's <code>-i</code> operator), and replace <code>&lt;img&gt;</code> and <code>&lt;input&gt;</code> tags with <code>&lt;img /&gt;</code> and <code>&lt;input &gt;</code>.</p> <pre><code>find . \! -path '*.svn*' -type f -exec perl -pi.orig -e 's{ ( &lt;(?:img|input)\b ([^&gt;]*?) ) \ ?/?&gt; }{$1\ /&gt;}sgxi' {} \; </code></pre> <p>Given input:</p> <pre><code>&lt;img&gt; &lt;img/&gt; &lt;img src=".."&gt; &lt;img src="" &gt; &lt;input&gt; &lt;input/&gt; &lt;input id=".."&gt; &lt;input id="" &gt; </code></pre> <p>It changes the file to:</p> <pre><code>&lt;img /&gt; &lt;img /&gt; &lt;img src=".." /&gt; &lt;img src="" /&gt; &lt;input /&gt; &lt;input /&gt; &lt;input id=".." /&gt; &lt;input id="" /&gt; </code></pre> <p>Here's what the regexp is doing:</p> <pre><code>s{(&lt;(?:img|input)\b ([^&gt;]*?)) # capture "&lt;img" or "&lt;input" followed by non-"&gt;" chars \ ?/?&gt;} # optional space, optional slash, followed by "&gt;" {$1\ /&gt;}sgxi # replace with: captured text, plus " /&gt;" </code></pre>
<p>See questions I asked in comment at top.</p> <p>Assuming you're using GNU sed, and that you're trying to <strong>add</strong> the trailing <code>/</code> to your tags to make XML-compliant <code>&lt;img /&gt;</code> and <code>&lt;input /&gt;</code>, then replace the sed expression in your command with this one, and it should do the trick: <code>'1h;1!H;${;g;s/\(img\|input\)\( [^&gt;]*[^/]\)&gt;/\1\2\/&gt;/g;p;}'</code></p> <p>Here it is on a simple test file (SO's colorizer doing wacky things):</p> <pre><code>$ cat test.html This is an &lt;img tag&gt; without closing slash. Here is an &lt;img tag /&gt; with closing slash. This is an &lt;input tag &gt; without closing slash. And here one &lt;input attrib="1" &gt; that spans multiple lines. Finally one &lt;input attrib="1" /&gt; with closing slash. $ sed -n '1h;1!H;${;g;s/\(img\|input\)\( [^&gt;]*[^/]\)&gt;/\1\2\/&gt;/g;p;}' test.html This is an &lt;img tag/&gt; without closing slash. Here is an &lt;img tag /&gt; with closing slash. This is an &lt;input tag /&gt; without closing slash. And here one &lt;input attrib="1" /&gt; that spans multiple lines. Finally one &lt;input attrib="1" /&gt; with closing slash. </code></pre> <p>Here's <a href="http://www.gnu.org/software/sed/manual/sed.html#Regular-Expressions" rel="nofollow noreferrer">GNU sed regex syntax</a> and <a href="http://www.ilfilosofo.com/blog/2008/04/26/sed-multi-line-search-and-replace/" rel="nofollow noreferrer">how the buffering works to do multiline search/replace</a>.</p> <p>Alternately you could use something like <a href="http://tidy.sourceforge.net/" rel="nofollow noreferrer">Tidy</a> that's designed for sanitizing bad HTML -- that's what I'd do if I were doing anything more complicated than a couple of simple search/replaces. Tidy's options get complicated fast, so it's usually better to write a script in your scripting language of choice (Python, Perl) that calls <code>libtidy</code> and sets whatever options you need.</p>
29,965
<p>What do folks here see as the relative strengths and weaknesses of Git, Mercurial, and Bazaar?</p> <p>In considering each of them with one another and against version control systems like SVN and Perforce, what issues should be considered?</p> <p>In planning a migration from SVN to one of these distributed version control systems, what factors would you consider?</p>
<p>Git is very fast, scales very well, and is very transparent about its concepts. The down side of this is that it has a relatively steep learning curve. A Win32 port is available, but not quite a first-class citizen. Git exposes hashes as version numbers to users; this provides guarantees (in that a single hash always refers to the exact same content; an attacker cannot modify history without being detected), but can be cumbersome to the user. Git has a unique concept of tracking file contents, even as those contents move between files, and views files as first-level objects, but does not track directories. Another issue with git is that has many operations (such as <I>rebase</I>) which make it easy to modify history (in a sense -- the content referred to by a hash will never change, but references to that hash may be lost); some purists (myself included) don't like that very much.</p> <p>Bazaar is reasonably fast (very fast for trees with shallow history, but presently scales poorly with history length), and is easy-to-learn to those familiar with the command-line interfaces of traditional SCMs (CVS, SVN, etc). Win32 is considered a first-class target by its development team. It has a pluggable architecture for different components, and replaces its storage format frequently; this allows them to introduce new features (such as better support for integration with revision control systems based on different concepts) and improve performance. The Bazaar team considers directory tracking and rename support first-class functionality. While globally unique revision-id identifiers are available for all revisions, tree-local revnos (standard revision numbers, more akin to those used by svn or other more conventional SCMs) are used in place of content hashes for identifying revisions. Bazaar has support for "lightweight checkouts", in which history is kept on a remote server instead of copied down to the local system and is automatically referred to over the network when needed; at present, this is unique among DSCMs.</p> <p>Both have some form of SVN integration available; however, bzr-svn is considerably more capable than git-svn, largely due to backend format revisions introduced for that purpose. <I>[Update, as of 2014: The third-party commercial product SubGit provides a bidirectional interface between SVN and Git which is comparable in fidelity to bzr-svn, and considerably more polished; I <B>strongly</B> recommend its use over that of git-svn when budget and licensing constraints permit].</I></p> <p>I have not used Mercurial extensively, and so cannot comment on it in detail -- except to note that it, like Git, has content-hash addressing for revisions; also like Git, it does not treat directories as first-class objects (and cannot store an empty directory). It is, however, faster than any other DSCM except for Git, and has far better IDE integration (especially for Eclipse) than any of its competitors. Given its performance characteristics (which lag only slightly behind those of Git) and its superior cross-platform and IDE support, Mercurial may be compelling for teams with significant number of win32-centric or IDE-bound members.</p> <p>One concern in migrating from SVN is that SVN's GUI frontends and IDE integration are more mature than those of any of the distributed SCMs. Also, if you currently make heavy use of precommit script automation with SVN (ie. requiring unit tests to pass before a commit can proceed), you'll probably want to use a tool similar to <A HREF="https://launchpad.net/pqm" rel="noreferrer">PQM</A> for automating merge requests to your shared branches.</p> <p>SVK is a DSCM which uses Subversion as its backing store, and has quite good integration with SVN-centric tools. However, it has dramatically worse performance and scalability characteristics than any other major DSCM (even Darcs), and should be avoided for projects which are liable to grow large in terms of either length of history or number of files.</p> <p>[About the author: I use Git and Perforce for work, and Bazaar for my personal projects and as an embedded library; other parts of my employer's organization use Mercurial heavily. In a previous life I built a great deal of automation around SVN; before that I have experience with GNU Arch, BitKeeper, CVS and others. Git was quite off-putting at first -- it felt like GNU Arch inasmuch as being a concept-heavy environment, as opposed to toolkits built to conform to the user's choice of workflows -- but I've since come to be quite comfortable with it].</p>
<p>Distributed version control systems (DVCSs) solve different problems than Centralized VCSs. Comparing them is like comparing hammers and screwdrivers.</p> <p><a href="http://en.wikipedia.org/wiki/Revision_control" rel="nofollow noreferrer">Centralized VCS</a> systems are designed with the intent that there is One True Source that is Blessed, and therefore Good. All developers work (checkout) from that source, and then add (commit) their changes, which then become similarly Blessed. The only real difference between CVS, Subversion, ClearCase, Perforce, VisualSourceSafe and all the other CVCSes is in the workflow, performance, and integration that each product offers.</p> <p><a href="http://en.wikipedia.org/wiki/Distributed_revision_control" rel="nofollow noreferrer">Distributed VCS</a> systems are designed with the intent that one repository is as good as any other, and that merges from one repository to another are just another form of communication. Any semantic value as to which repository should be trusted is imposed from the outside by process, not by the software itself.</p> <p>The real choice between using one type or the other is organizational -- if your project or organization wants centralized control, then a DVCS is a non-starter. If your developers are expected to work all over the country/world, without secure broadband connections to a central repository, then DVCS is probably your salvation. If you need both, you're fsck'd.</p>
10,297
<p>What is .net dynamic data and why would I use it?</p>
<p>From <a href="http://weblogs.asp.net/scottgu/archive/2007/12/14/new-asp-net-dynamic-data-support.aspx" rel="nofollow noreferrer">ScottGu's Blog</a> a great article on how to use Dynamic Data.</p> <blockquote> <p>One of the cool new features is something we call "ASP.NET Dynamic Data Support". In a nutshell this enables you to really quickly build data driven web-sites that work against a LINQ to SQL (and in the future LINQ to Entities) object model - and optionally allows you to-do this without having to build any pages manually.</p> </blockquote> <p>See this <a href="http://blogs.msdn.com/davidebb/archive/2007/12/12/dynamic-data-screencast-is-now-available.aspx" rel="nofollow noreferrer">screencast</a>. It is very enlightening.</p> <p>From more official <a href="http://www.asp.net/dynamicdata/" rel="nofollow noreferrer">ASP.NET Dynamic Data site</a>:</p> <blockquote> <p>ASP.NET Dynamic Data provides a framework that enables you to quickly build a functional data-driven application, based on a LINQ to SQL or Entity Framework data model. It also adds great flexibility and functionality to the DetailsView, FormView, GridView, and ListView controls in the form of smart validation and the ability to easily change the display of these controls using templates.</p> </blockquote>
<p>ASP.NET DDS is the drag and drop change here and there and you have a data Driven web application ready to go kind'a thing.</p> <p><a href="http://mattberseth.com/" rel="nofollow noreferrer">Matt Berseth</a> has a <a href="http://mattberseth.com/blog/dynamic_data/" rel="nofollow noreferrer">few good posts about this</a></p>
24,790
<p>Null or empty string -- is one better than the other to represent no data in a table column? (I specifically use MySQL, but I'm thinking this is system-independent.) Are there major advantages/disadvantages to using one over the other, or is it simply programmer preference?</p>
<p>I strongly disagree with everyone who says to unconditionally use NULL. Allowing a column to be NULL introduces an additional state that you wouldn't have if you set the column up as NOT NULL. Do not do this if you don't need the additional state. That is, if you can't come up with a difference between the meaning of empty string and the meaning of null, then set the column up as NOT NULL and use empty string to represent empty. Representing the same thing in two different ways is a bad idea.</p> <p>Most of the people who told you to use NULL also gave an example where NULL would mean something different than empty string. And in those examples, they are right.</p> <p>Most of the time, however, NULL is a needless extra state that just forces programmers to have to handle more cases. As others have mentioned, Oracle does not allow this extra state to exist because it treats NULL and empty string as the same thing (it is impossible to store an empty string in a column that does not allow null in Oracle).</p>
<p>There is one important exception. Bill Karwin stated "CONCAT(NULL, 'foo') yields NULL" which is true for most RDBMSs but NOT for Oracle.</p> <p>As suggested by James Curran above, Oracle chose this rather critical juncture to depart from standard SQL by treating NULLs and empty strings exactly the same. Worse than just treating them the same, however, it can actually corrupt the meaning of a NULL value by returning something other than NULL when concatenating.</p> <p>Specifically, in oracle CONCAT(NULL, 'foo') yields 'foo'. Thanks Oracle, I've now lost my nulls which may not matter to you but sure makes a difference when the data is passed to other RDBMSs for further processing.</p>
20,287
<p>Has anyone worked out how to get PowerShell to use <code>app.config</code> files? I have a couple of .NET DLL's I'd like to use in one of my scripts but they expect their own config sections to be present in <code>app.config</code>/<code>web.config</code>.</p>
<p>Cross-referencing with this thread, which helped me with the same question: <a href="https://stackoverflow.com/questions/2789920/subsonic-access-to-app-config-connection-strings-from-referenced-dll-in-powershel">Subsonic Access To App.Config Connection Strings From Referenced DLL in Powershell Script</a></p> <p>I added the following to my script, before invoking the DLL that needs config settings, where $configpath is the location of the file I want to load:</p> <pre><code>[appdomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $configpath) Add-Type -AssemblyName System.Configuration </code></pre> <p>See <a href="https://stackoverflow.com/questions/6150644/change-default-app-config-at-runtime/6151688#6151688">this</a> post to ensure the configuration file specified is applied to the running context. </p>
<p><em>Attempting a new answer to an old question.</em></p> <p>I think the modern answer would be: don't do that. PowerShell is a shell. The normal way of passing information between parts of the shell are shell variables. For powershell that would look like:</p> <pre><code>$global:MyComponent_MySetting = '12' # i.e. $PSDefaultParameterValues $ErrorActionPreference </code></pre> <p>If settings is expected to be inherited across processes boundaries the convention is to use environment variables. I extend this to settings that cross C# / PowerShell boundary. A couple of examples:</p> <pre><code>$env:PATH $env:PSModulePath </code></pre> <p>If you think this is an anti-pattern for .NET you might want to reconsider. This is the norm for PAAS hosted apps, and is going to be the new default for ASP.NET running on server-optimized CLR (ASP.NET v5). </p> <p>See <a href="https://github.com/JabbR/JabbRv2/blob/dev/src/JabbR/Startup.cs#L21" rel="nofollow">https://github.com/JabbR/JabbRv2/blob/dev/src/JabbR/Startup.cs#L21</a> <br> Note: at time of writing I'm linking to <code>.AddEnvironmentVariables()</code></p> <p>I've revisited this question a few times, including asking it myself. I wanted to put a stake in the ground to say PowerShell stuff doesn't work well with <code>&lt;appSettings&gt;</code>. IMO it is much better to embrace the shell aspect of PS over the .NET aspect in this regards. </p> <p>If you need complex configuration take a JSON string. POSH v3+ has <a href="https://technet.microsoft.com/en-us/library/hh849898.aspx" rel="nofollow">ConvertFrom-JSON</a> built-in. If everything in your process uses the same complex configuration put it in a .json file and point to that file from an environment variable. </p> <p>If a single file doesn't suffice there are well established solutions like the <code>PATH</code> pattern, <strong>GIT .gitignore</strong> resolution, or <strong>ASP.NET web.config</strong> resolution (which I won't repeat here).</p>
3,858
<p>HI, I am new to the scrum methodology and looking for some help to get comfortable with the environment and wondering if there needs to be a bucket to track Developers and QA hours spent on deployments and bug fixes and retests. Seems like it could have major impact on the graph.</p>
<p>My team is supporting a number of legacy apps, so there's quite a bit of unplanned bug fixing that occurs during each sprint. We've adopted the following practice:</p> <ul> <li>If the bug is easy/quick to fix (one liner, etc), then just fix it.</li> <li>If the bug is not trivial, and not a blocker, then add it to the backlog.</li> <li>If the bug is a blocker then add a task (to the current sprint) to capture the work required to fix it, and start working on it. This requires that something else be moved (from the current sprint) to the backlog to account for the new hours because your total hours available hasn't changed.</li> </ul> <p>When we add new bug tasks we'll mark them differently from the planned tasks so make them easy to see during the sprint review. Sometimes unplanned work ends up being >50% of our sprint, but because we're pushing planned items to the backlog we know very early what we're not delivering this sprint that we had planned on.</p> <p>This has proven to be very useful for our team in dealing with legacy apps where none of us are as familiar or confident with the systems as we'd like to be.</p>
<p>In each sprint I have two 'tasks' - one for bugs found in the current sprint (i.e. on unshipped code), and one for issues found in anything else (any shipped release). This helps me keep track of how much time is lost (per developer) fixing bugs.</p> <p>Any time logged in the latter category is regarded as waste and it's a key target for reduction. Time logged in the former is reviewed for how it can be more closely linked to the features and changes that caused it.</p> <p>Don't put estimates against bugs, instead try to add that time to the estimates for unit/functional testing against the features you're working on.</p> <p>Feel free to adapt any model to suit how your team works - there should be a culture of continuous improvment in any Scrum team, and the devs should be able to suggest and try out improvements as they learn Scrum.</p>
21,141
<p>I'm using two different libraries in my project, and both of them supply a basic rectangle <code>struct</code>. The problem with this is that there seems to be no way to insert a conversion between the types, so I can't call a function in one library with the result from a function in the other. If I was the author of either of these, I could create conversions, from the outside, I can't.</p> <p>library a:</p> <pre><code>typedef struct rectangle { sint16 x; sint16 y; uint16 w; uint16 h; } rectangle; </code></pre> <p>library b:</p> <pre><code>class Rect { int x; int y; int width; int height; /* ... */ }; </code></pre> <p>Now, I can't make a converter <code>class</code>, because C++ will only look for a conversion in one step. This is probably a good thing, because there would be a lot of possibilities involving creating new objects of all kinds of types.</p> <p>I can't make an operator that takes the <code>struct</code> from <code>a</code> and supplies an object of the <code>class</code> from <code>b</code>:</p> <pre>foo.cpp:123 error: ‘operator b::Rect(const rectangle&)’ must be a nonstatic member function</pre> <p>So, is there a sensible way around this?</p> <h2>edit:</h2> <p>I should perhaps also point out that I'd really like some solution that makes working with the result seamless, since I don't expect to be that coder. (Though I agree, old-school, explicit, conversion would have been a good choice. The other branch, <a href="http://en.cppreference.com/w/cpp/language/reinterpret_cast" rel="nofollow noreferrer"><code>reinterpret_cast</code></a> has the same problem..)</p> <h2>edit2:</h2> <p>Actually, none of the suggestions really answer my actual question, <a href="https://stackoverflow.com/users/1968/konrad-rudolph">Konrad Rudolph</a> seems to be correct. C++ actually can't do this. Sucks, but true. (If it makes any difference, I'm going to try subclassing as suggested by <a href="https://stackoverflow.com/users/90/codingthewheel">CodingTheWheel</a>.</p>
<p>If you can't modify the structures then you have no alternative to writing a manual conversion function because overloading conversion operators only works within the class body. There's no other way.</p>
<p>Maybe you could try it with operator overloading ? (Maybe a = operator which is not a method of your class) ?</p> <p>Rect operator= (const Rect&amp;,const rectangle&amp;)</p> <p>More about this in the C++ programming language by Bjarne Stroustrup or maybe on this page: <a href="http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html" rel="nofollow noreferrer">http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html</a></p>
4,786
<p>As the question states - is there a good tool out there which lists methods an unmanaged DLL exports? I would like it to list COM methods and interfaces too.</p>
<p>For DLLs, use the Dependency Viewer (<a href="http://technet.microsoft.com/en-us/library/cc738370.aspx" rel="noreferrer">depends.exe</a>).</p> <p>For COM objects, use <a href="http://www.microsoft.com/downloads/details.aspx?familyid=5233b70d-d9b2-4cb5-aeb6-45664be858b6&amp;displaylang=en" rel="noreferrer">oleview.exe</a></p>
<p>As an application packager we use a utility that monitors (or dumps) the registration information - WiseComCapture.exe - this is part of Wise Package Studio however which isn't free. It spits out a .reg file of all it's registration information. </p> <p>A bit of noodling around with google may 'expose' it</p>
23,759
<p>How can I generate a report in access with the data from a recordset (instead of a query or table). I have updates to the recordset that also must be shown in the report.</p>
<p>From <a href="http://www.mvps.org/access/reports/rpt0014.htm" rel="nofollow noreferrer">Access Web</a> you can use the "name" property of a recordset. You resulting code would look something like this:</p> <p><em>In the report</em> </p> <pre><code>Private Sub Report_Open(Cancel As Integer) Me.RecordSource = gMyRecordSet.Name End Sub </code></pre> <p><em>In the calling object (module, form, etc.)</em> </p> <pre><code>Public gMyRecordSet As Recordset '... Public Sub callMyReport() '... Set gMyRecordSet = CurrentDb.OpenRecordset("Select * " &amp; _ "from foo " &amp; _ "where bar='yaddah'") DoCmd.OpenReport "myReport", acViewPreview '... gMyRecordSet.Close Set gMyRecordSet = Nothing '... End Sub </code></pre>
<p>Please explain in more detail. For example, do you wish to show what the field was and what it is now? If so, you will need an audit trail. Here is an example from Microsoft: <a href="http://support.microsoft.com/kb/q197592/" rel="nofollow noreferrer">http://support.microsoft.com/kb/q197592/</a></p> <p>What do you mean by report? If you mean a printed paper document, Access has a good report builder. If you mean you wish to view the data, you can use a form. If you are unfamilar with building reports and forms, there are wizards. </p> <p>It is always wise to study the Northwind sample database that ships with every version of Access.</p>
30,017
<p>Should i stay out of rails if a client has a cheap hosting service with a provider that do not support mod_rails? Will rails + fast.cgi provide a good experience for a user or should I choose, in this scenario, php + my-favorite-framework as platform ?</p> <p>Regards,</p> <p>Victor</p>
<p>I have three clients on inexpensive hosting plans using FastCGI and have not run into any issues due to FastCGI itself. These are all low traffic sites where Mongrel was not necessary.</p> <blockquote> <p>Will rails + fast.cgi provide a good experience for a user</p> </blockquote> <p>It all depends on what you're trying to do. If you're going to build a site where users will uploading and playing video then no FastCGI is not a good choice.</p> <blockquote> <p>or should I choose, in this scenario, php + my-favorite-framework as platform</p> </blockquote> <p>You always choose the right tool for the job. Without any details on what you are trying to build I'm not sure anyone here will be able to tell you how to build it.</p>
<p>I would tend to avoid FastCGI. I haven't used it myself but I've read enough horror stories about it to never want to.</p> <p>If the hosting company is going to be completely responsible for managing the server instance and you can trust them to be the ones who will make sure the app is always up and running, then maybe it would work. I doubt this is the case though, and if you don't own the servers I think you'll run into a lot of problems troubleshooting the all the weird bugs FastCGI will inevitably throw at you.</p>
25,651
<p>Is there currently a way to host a shared Git repository in Windows? I understand that you can configure the Git service in Linux with:</p> <pre><code>git daemon </code></pre> <p>Is there a native Windows option, short of sharing folders, to host a Git service?</p> <p>EDIT: I am currently using the cygwin install of git to store and work with git repositories in Windows, but I would like to take the next step of hosting a repository with a service that can provide access to others.</p>
<p>Here are some steps you can follow to get the git daemon running under Windows:</p> <p><em>(Prerequisites: A default Cygwin installation and a git client that supports git daemon)</em></p> <p><strong>Step 1</strong>: Open a bash shell</p> <p><strong>Step 2</strong>: In the directory /cygdrive/c/cygwin64/usr/local/bin/, create a file named "gitd" with the following content:</p> <pre><code>#!/bin/bash /usr/bin/git daemon --reuseaddr --base-path=/git --export-all --verbose --enable=receive-pack </code></pre> <p><strong>Step 3</strong>: Run the following cygrunsrv command from an elevated prompt (i.e. as admin) to install the script as a service (Note: assumes Cygwin is installed at C:\cygwin64):</p> <pre><code>cygrunsrv --install gitd \ --path c:/cygwin64/bin/bash.exe \ --args c:/cygwin64/usr/local/bin/gitd \ --desc "Git Daemon" \ --neverexits \ --shutdown </code></pre> <p><strong>Step 4</strong>: Run the following command to start the service:</p> <p>cygrunsrv --start gitd</p> <p>You are done. If you want to test it, here is a quick and dirty script that shows that you can push over the git protocol to your local machine:</p> <pre><code>#!/bin/bash echo "Creating main git repo ..." mkdir -p /git/testapp.git cd /git/testapp.git git init --bare touch git-daemon-export-ok echo "Creating local repo ..." cd mkdir testapp cd testapp git init echo "Creating test file ..." touch testfile git add -A git commit -m 'Test message' echo "Pushing master to main repo ..." git push git://localhost/testapp.git master </code></pre>
<p>I think what Henk is saying is that you can create a shared repository on a drive and then copy it to some common location that both of you have access to. If there is some company server or something that you both have ssh access to, you can put the repository someplace where you can SCP it back to your own computer, and then pull from that. I did this for my self a little while, since I have two computers. It's a hassle, but it does work.</p>
28,892
<p>Is there a way of changing/adding to the windows Open/Save common dialog to add extra functionality?</p> <p>At work we have an area on a server with hundreds of 'jobfolders'- just ordinary windows folders created/managed automatically by the database application to house information about a job (emails/scanned faxes/Word docs/Spreadsheets/Photos etc) The folders are named by the job Number.</p> <p>I would like to expand the standard open/save dialog with a combobox which searches for jobfolders based on tags from the database, so that whatever my users are doing they can easily find their way to the correct jobfolder to find/save their work</p> <p>Connecting to the database and providing the functionality to search is no problem, but is there a way to add a combobox control (ideally with a keypress/keydown event) to the dialog?</p> <p>Or Create my own dialog and have it called/used in place of the standard one? i.e. from ANY app my dialog would be called allowing easy access to the jobfolders. If they are in outlook they can find a jobfolder quickly, if there are using Notepad they can still find the folder easily.</p> <p>This would mean a new unified way of finding jobfolders from any app.</p> <p>Ideally someone would know a way using VB/VB.net/C# but I'm guessing, if its possible, its probably going to be C++.</p>
<p>Like Mark Ransom said, you can do it with the OFN&nbsp;ENABLETEMPLATE and OFN&nbsp;ENABLEHOOK flags. You then specify a Dialog Resource to the lpTemplateName data member of the OPENFILENAME structure. Getting the placement of your controls right takes a bit of trial and error.</p> <p>The hook procedure that you write will receive window messages specific to that dialog - you're particularly interested in the WM_NOTIFY messages - there's a bunch of special ones (CDN&nbsp;INITDONE, CDN&nbsp;FOLDERCHANGE, etc).</p> <p>I've created some pretty elaborate ones a few times, I wish I could include a screenshot.</p>
<p>Your program can set the starting folder, so if you know the job number (and therefor the name of the folder), you can set the dialog to start out with the correct folder already opened. Beyond that I don't think you can do much without writing an entire shell extension for it.</p>
17,972
<p>I have this code:</p> <pre><code>SELECT idcallhistory3, callid, starttime, answertime, endtime, duration, is_answ, is_fail, is_compl, is_fromoutside, mediatype, from_no, to_no, callerid, dialednumber, lastcallerid, lastdialednumber, group_no, line_no FROM "public".callhistory3 WHERE (starttime &gt;= ?) AND (endtime &lt;= ?) AND (is_fromoutside = ?) AND (from_no = ?) AND (to_no = ?) </code></pre> <p>The problem is I need to pass one value for ? and get all the result without filter, some thing like *</p> <p>Any help?</p>
<pre><code>WHERE (@start is null OR starttime &gt;= @start) AND (@end is null OR endtime &lt;= @end) AND (@fromOutside is null OR is_fromoutside = @fromOutside) AND (@fromNo is null OR from_no = @fromNo) AND (@toNo is null OR to_no = @toNo) </code></pre> <p>Pass nulls for all parameters (dang sql nulls; thanks GC).</p>
<p>I agree with Jamal Hansen. COALESCE is by far the best performing way to go, at least on SQL Server</p>
45,471
<p>I'm mostly a .Net person at the moment, but I've been playing with Java some lately-- exploring what's out there.</p> <p>Now I'm looking for the Java equivalent for WPF. I know I could find an OpenGL library or two out there, but that's not really as rich or simple as the WPF system.</p>
<p>I think a combination of JavaFX, Swing, Java2D, and Java's browser-based JRE comprise the solutions that WPF provides:</p> <ul> <li>JavaFX applications (actually, any Java app) can run in the browser or on a desktop</li> <li>JavaFX provides high-end video support</li> <li>JavaFX provides for scripted animations and visual special effects</li> <li>Swing provides UI capabilities, and can be used in both Java and JavaFX</li> <li>Java2D, which provides the underpinnings for all drawing tasks (including Swing), takes advantage of hardware acceleration and DirectX support</li> <li>The JRE on the desktop or the browser enable Java applications to be deployed to multiple environments (including other screens, like set-top boxes or phones)</li> </ul>
<p>Feature-wise WPF is more comprehensive than any of the JavaFX, Swing, AWT or Java2D. That was the design goal after all, to bring everything related to the presentation in a single library. Performance-wise they are about the same with the exception of the memory usage where Java is a <a href="http://www.codeproject.com/KB/dotnet/RuntimePerformance.aspx" rel="noreferrer">hungry hog</a></p>
36,193
<p>My company develops several types of applications. A lot of our business comes from doing multimedia-type apps, typically done in Flash. However, now that side of the house is starting to migrate towards doing Flex development.</p> <p>Most of our other development is done using .NET. I'm trying to make a push towards doing Silverlight development instead, since it would take better advantage of the .NET developers on staff. I prefer the Silverlight platform over the Flex platform for the simple fact that Silverlight is all .NET code. We have more .NET developers on staff than Flash/Flex developers, and most of our Flash/Flex developers are graphic artists (not real programmers). Only reason they push towards Flex right now is because it seems like the logical step from Flash.</p> <p>I've done development using both, and I honestly believe Silverlight is easier to work with. But I'm trying to convince people who are only Flash developers. </p> <p>So here's my question: If I'm going to go into a meeting to praise Silverlight, why would a company want to go with Silverlight instead of Flex? Other than the obvious "not everyone has Silverlight", what are the pros and cons for each?</p>
<p>I think you should look at Silverlight as a long-term play, just as Microsoft seems to be doing. There's an obvious balance on when to use Silverlight vs. Flash when you're concerned about reach and install base, but here are some reasons Silverlight is a good direction to move in:</p> <ol> <li><p>Second mover advantage - Just as Microsoft built a "better Java" with .NET, they're able to look at how you'd design a RIA plugin from scratch, today. They have the advantage of knowing how people use the web today, something the inventors of Flash could never have accurately guessed. Flash can add features, but they can't realistically chuck the platform and start over.</p></li> <li><p>Developer familiarity - While Silverlight is a new model, it's not entirely unfamiliar to developers. They'll "get" the way Silverlight works a lot more quickly than they'll understand firing up a new development environment with a new scripting language and new event paradigms.</p></li> <li><p>Being rid of the timeline model in Flash - Flash was originally built for keyframe based animations, and while there are ways to abstract this away, it's at the core of how Flash works. Silverlight ditches that for an application-centric model. </p></li> <li><p>ScottGu - ScottGu is fired up about Silverlight. Nuff said.</p></li> <li><p>Cool new features - While Silverlight still has some catching up to do with Flash on some obvious features (like webcam / mic integration, or 3d / graphics acceleration), there are some slick new technologies built in to Silverlight - Deep Zoom is one example. I'm seeing more "revolutionary" technologies on the Silverlight side, while Flash seems to be in maintenance mode at this point.</p></li> </ol>
<p>Flash Player is available &amp; supported officially in almost all desktop platforms (Windows, Linux, Mac) whereas Silverlight will be supported mainly in Windows.</p> <p>the following <a href="http://www.brighthub.com/internet/web-development/articles/33696.aspx" rel="nofollow noreferrer">article</a> provides comparision of both the platforms.</p>
4,127
<p>As you develop an application database changes inevitably pop up. The trick I find is keeping your database build in step with your code. In the past I have added a build step that executed SQL scripts against the target database but that is dangerous in so much as you could inadvertanly add bogus data or worse. </p> <p>My question is what are the tips and tricks to keep the database in step with the code? What about when you roll back the code? Branching?</p>
<p>Version numbers embedded in the database are helpful. You have two choices, embedding values into a table (allows versioning multiple items) that can be queried, or having an explictly named object (such as a table or somesuch) you can test for.</p> <p>When you release to production, do you have a rollback plan in the event of unexpected catastrophe? If you do, is it the application of a schema rollback script? Use your rollback script to rollback the database to a previous code version.</p>
<p>I like the way that Django does it. You build models and the when you run a syncdb it applies the models that you have created. If you add a model you just need to run syncdb again. This would be easy to have your build script do every time you made a push. </p> <p>The problem comes when you need to alter a table that is already made. I do not think that syncdb handles that. That would require you to go in and manually add the table and also add a property to the model. You would probably want to version that alter statement. The models would always be under version control though, so if you needed to you could get a db schema up and running on a new box without running the sql scripts. Another problem with this is keeping track of static data that you always want in the db.</p> <p>Rails migration scripts are pretty nice too. </p> <p>A DB versioning system would be great, but I don't really know of such a thing. </p>
5,372
<p>I was recommeded a book called: </p> <p>Accelerated C++ Practical Programming by Example by Andrew Koenig and Barbara E. Moo Addison-Wesley, 2000 ISBN 0-201-70353-X </p> <p>The basis of this book is that Object Oriented Programming is highly wasteful memory-wise, and that most source-code should not be written this way, rather that you should use all inline function calls and procedural programming.</p> <p>I mean I know most programming books have about the same shelf life as milk, but if your coding a client/server application (database, server and all) (not a device driver or a video game) is it really worth the hassle of having un-maintainable code just for a speed boost?</p> <p>Or is it worth it just to make the application run on a client's really old machine? Or to be able to run more servers on a single box?</p>
<p>I haven't read the book, but I have trouble believe that they wrote a book whose "basis ...is that Object Oriented Programming is highly wasteful memory-wise" (Full disclosure: Andy &amp; Barbara are friends of mine). </p> <p>Andy would never say the OOP is wasteful of memory. He WOULD say that a particular algorithm or technique is wasteful, and might recommend a less OO approach in some cases, but, he would be the first to argue that as a general rule OO designs are no more or less wasteful that any other style of programming. </p> <p>The argument that OO designs are wasteful largely came from the fact that the EXEs of C++ "hello world" programs tend to be larger that the EXEs of C "hello world" programs. This is mostly because iostreams is larger the printf (but then, iostreams does more). </p>
<p>Some of the answers are totally missing the point. OOP in C++ has many opportunities to be much faster than their C counterparts. I'll give the example from I think Effective C++ by Scott Meyers, which is that quicksort runs slower than C++ sort because the compiler is able to inline the function call easily in C++ whereas it is unable to do so in C due to quicksort being passed a function pointer. </p> <p>Additionally, nothing about c++ makes it slow, unlike other languages, any slowness is purely library implementations or algorithm design.</p>
26,137
<p>I am experimenting for the first time with css layouts and my experience with CSS is very basic. What I want to achieve is a 2 column layout: left panel and content.<br> I have found this:</p> <pre><code>#leftcontent { position: absolute; left: 10px; top: 10px; width: 170px; border: 1px solid #C0C0C0; padding: 2px; } #centercontent { position: absolute; margin-left: 181px; border:1px solid #C0C0C0; top: 10px; //fix IE5 bug voice-family: "\"}\""; voice-family: inherit; margin-left: 181px; } </code></pre> <p>This displays great in firefox but the content in IE8 goes off the right of the screen, I assume by the length of the <code>#leftcontent</code>. How can I fix this?</p> <p>This is probably quite a simple fix but I have experimented and looked for fixes, but this supposedly should work. I appreciate any help.</p>
<p>I'd advise floating the #leftcontent element to the left, and then setting the margin of the #centercontent element to compensate:</p> <pre><code>#leftcontent { float: left; width:170px; border:1px solid #C0C0C0; padding: 2px; } #centercontent { margin-left: 181px; border:1px solid #C0C0C0; } </code></pre>
<p>Use a table. It is more suited to the task, way easier to implement and far more reliable across different browsers.</p>
32,540
<p>I have a database that stores events in it and a page with a calendar object on it. When rendering the days it looks through the months events and if any match the current day being rendered it creates a linkbutton to represent the event in the day on the calendar and adds it to that cell. I add some javascript to the linkbutton to change the window.location to a page to view event details passing EventID in the querystring ( I tried setting the postbackurl of the newly created linkbutton but it wasnt causing a postback... no luck). I need to set a Session variable ie. Session("EditMode") = "Edit" So the new page will know it is to get an existing event info rather than prepare to create a new event? Any SUGGESTIONS?</p>
<p>Your session vars are controlled by the server, JS runs client side, and as such cannot modify the vars directly.</p> <p>You need to make server requests using POST or GET and hidden iframes, or XMLHTTPRequest() calls to send data from the JS to the server, and then have your server side code handle the vars.</p> <p>Add another query string variable that the page can use to trigger existing vs new.</p>
<pre><code>var page1 = document.getElementById("textbox").value; sessionStorage.setItem("page1content", page1); </code></pre> <p>in other page use this value as like session variable </p> <pre><code>document.getElementById("textbox2").value=sessionStorage.getItem("page1content"); </code></pre>
15,776
<p>We are developing a Visual Basic 6.0 project. We have written a library, which we were testing using vbunit and vbmock. But soon found that the tests were not maintainable. So, we decided to write tests using MBunit. Now, we want to know the test coverage. How can we do it? thanks</p>
<p>The only VB6 test coverage tool I know is <a href="http://www.aivosto.com/vbwatch.html" rel="nofollow noreferrer">http://www.aivosto.com/vbwatch.html</a> Aivisto seems to have a generally good reputation for their VB tools.</p>
<p>Look into NCover</p>
10,575
<p>Can someone explain why there is the need to add an out or in parameter to indicate that a generic type is Co or Contra variant in C# 4.0?</p> <p>I've been trying to understand why this is important and why the compiler can't just figure it out..</p> <p>Thanks,</p> <p>Josh</p>
<p>Eric Lippert, who works on the langauge, has a series of posts on msdn that should help clarify the issues involved:<br> <a href="http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx</a></p> <p>When reading the articles shown at that link, start at the bottom and work up.</p> <p>Eventually you'll get to <a href="http://blogs.msdn.com/ericlippert/archive/2007/10/29/covariance-and-contravariance-in-c-part-seven-why-do-we-need-a-syntax-at-all.aspx" rel="nofollow noreferrer">#7 (Why do we need a syntax at all?)</a>.</p>
<p>The <code>in</code> and <code>out</code> keywords have been keywords since C# 1.0, and have been used in the context of <code>in</code>- and <code>out</code>- parameters to methods.</p> <p>Covariance and contravariance are constraints on how one can implement an interface. There is no good way to infer them - the only way, I think, is from usage, and that would be messy and in the end it wouldn't work.</p>
33,746
<p>How can I get the current system status (current CPU, RAM, free disk space, etc.) in Python? Ideally, it would work for both Unix and Windows platforms.</p> <p>There seems to be a few possible ways of extracting that from my search:</p> <ol> <li><p>Using a library such as <a href="http://www.psychofx.com/psi/trac/wiki/" rel="noreferrer">PSI</a> (that currently seems not actively developed and not supported on multiple platforms) or something like <a href="http://www.i-scream.org/pystatgrab/" rel="noreferrer">pystatgrab</a> (again no activity since 2007 it seems and no support for Windows).</p> </li> <li><p>Using platform specific code such as using a <code>os.popen(&quot;ps&quot;)</code> or similar for the *nix systems and <code>MEMORYSTATUS</code> in <code>ctypes.windll.kernel32</code> (see <a href="http://code.activestate.com/recipes/511491/" rel="noreferrer">this recipe on ActiveState</a>) for the Windows platform. One could put a Python class together with all those code snippets.</p> </li> </ol> <p>It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?</p>
<p><a href="https://pypi.python.org/pypi/psutil" rel="noreferrer">The psutil library</a> gives you information about CPU, RAM, etc., on a variety of platforms:</p> <blockquote> <p>psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top and Windows task manager.</p> <p>It currently supports Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version).</p> </blockquote> <hr /> <p>Some examples:</p> <pre><code>#!/usr/bin/env python import psutil # gives a single float value psutil.cpu_percent() # gives an object with many fields psutil.virtual_memory() # you can convert that object to a dictionary dict(psutil.virtual_memory()._asdict()) # you can have the percentage of used RAM psutil.virtual_memory().percent 79.2 # you can calculate percentage of available memory psutil.virtual_memory().available * 100 / psutil.virtual_memory().total 20.8 </code></pre> <p>Here's other documentation that provides more concepts and interest concepts:</p> <ul> <li><a href="https://psutil.readthedocs.io/en/latest/" rel="noreferrer">https://psutil.readthedocs.io/en/latest/</a></li> </ul>
<p>I don't believe that there is a well-supported multi-platform library available. Remember that Python itself is written in C so any library is simply going to make a smart decision about which OS-specific code snippet to run, as you suggested above. </p>
34,803
<p>Python is quite cool, but unfortunately, its debugger is not as good as perl -d. </p> <p>One thing that I do very commonly when experimenting with code is to call a function from within the debugger, and step into that function, like so:</p> <pre><code># NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO() ~&gt; cat -n /tmp/show_perl.pl 1 #!/usr/local/bin/perl 2 3 sub foo { 4 print "hi\n"; 5 print "bye\n"; 6 } 7 8 exit 0; ~&gt; perl -d /tmp/show_perl.pl Loading DB routines from perl5db.pl version 1.28 Editor support available. Enter h or `h h' for help, or `man perldebug' for more help. main::(/tmp/show_perl.pl:8): exit 0; # MAGIC HAPPENS HERE -- I AM STEPPING INTO A FUNCTION THAT I AM CALLING INTERACTIVELY DB&lt;1&gt; s foo() main::((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3): 3: foo(); DB&lt;&lt;2&gt;&gt; s main::foo(/tmp/show_perl.pl:4): print "hi\n"; DB&lt;&lt;2&gt;&gt; n hi main::foo(/tmp/show_perl.pl:5): print "bye\n"; DB&lt;&lt;2&gt;&gt; n bye DB&lt;2&gt; n Debugged program terminated. Use q to quit or R to restart, use O inhibit_exit to avoid stopping after program termination, h q, h R or h O to get additional info. DB&lt;2&gt; q </code></pre> <p>This is incredibly useful when trying to step through a function's handling of various different inputs to figure out why it fails. However, it does not seem to work in either pdb or pydb (I'd show an equivalent python example to the one above but it results in a large exception stack dump).</p> <p>So my question is twofold:</p> <ol> <li>Am I missing something?</li> <li>Is there a python debugger that would indeed let me do this?</li> </ol> <p>Obviously I could put the calls in the code myself, but I love working interactively, eg. not having to start from scratch when I want to try calling with a slightly different set of arguments.</p>
<p>And I've answered my own question! It's the "debug" command in pydb:</p> <pre><code>~&gt; cat -n /tmp/test_python.py 1 #!/usr/local/bin/python 2 3 def foo(): 4 print "hi" 5 print "bye" 6 7 exit(0) 8 ~&gt; pydb /tmp/test_python.py (/tmp/test_python.py:7): &lt;module&gt; 7 exit(0) (Pydb) debug foo() ENTERING RECURSIVE DEBUGGER ------------------------Call level 11 (/tmp/test_python.py:3): foo 3 def foo(): ((Pydb)) s (/tmp/test_python.py:4): foo 4 print "hi" ((Pydb)) s hi (/tmp/test_python.py:5): foo 5 print "bye" ((Pydb)) s bye ------------------------Return from level 11 (&lt;type 'NoneType'&gt;) ----------------------Return from level 10 (&lt;type 'NoneType'&gt;) LEAVING RECURSIVE DEBUGGER (/tmp/test_python.py:7): &lt;module&gt; </code></pre>
<p>There is a python debugger that is part of the core distribution of python called 'pdb'. I rarely use it myself, but find it useful sometimes.</p> <p>Given this program:</p> <pre><code>def foo(): a = 0 print "hi" a += 1 print "bye" foo() </code></pre> <p>Here is a session debugging it:</p> <pre><code>$ python /usr/lib/python2.5/pdb.py /var/tmp/pdbtest.py ~ &gt; /var/tmp/pdbtest.py(2)&lt;module&gt;() -&gt; def foo(): (Pdb) s &gt; /var/tmp/pdbtest.py(10)&lt;module&gt;() -&gt; foo() (Pdb) s --Call-- &gt; /var/tmp/pdbtest.py(2)foo() -&gt; def foo(): (Pdb) s &gt; /var/tmp/pdbtest.py(3)foo() -&gt; a = 0 (Pdb) s &gt; /var/tmp/pdbtest.py(4)foo() -&gt; print "hi" (Pdb) print a 0 (Pdb) s hi &gt; /var/tmp/pdbtest.py(6)foo() -&gt; a += 1 (Pdb) s &gt; /var/tmp/pdbtest.py(8)foo() -&gt; print "bye" (Pdb) print a 1 (Pdb) s bye --Return-- &gt; /var/tmp/pdbtest.py(8)foo()-&gt;None -&gt; print "bye" (Pdb) s --Return-- &gt; /var/tmp/pdbtest.py(10)&lt;module&gt;()-&gt;None -&gt; foo() (Pdb) s </code></pre>
28,294
<p>I'd like to implement a UITableView which displays say 20 rows at a time. But given the fact that I might actually have say 120 items to present, I'd like to handle this using some sort of paging:</p> <p>Populate table with first 20 items. When the user does a right-to-left swipe, reload the UITableView with the next 20 items. A left-to-right swipe would show the previous 20 items.</p> <p>I think subclassing UITableView and handle UITouches there is the way to go, but I'm not sure how to handle the touches correctly in order not to interfer with the standard event handling. </p> <p>Eg. if the user just touches (clicks) a row, I want the row to hightlight (selected) and then switch to a detail view presenting data corresponding to the selected row. But if the user does a horizontal swipe, I don't want the row below the swipe to be highlighted (and therefore selected), instead, i want to trigger my loadprevious page / loadnext page handling, which wil reload the table with the according 20 previous or next items, depending on the swipe direction. </p> <p>Any suggestions?</p>
<p>A horizontal swipe on a table row is already a standard UI behavior that causes that row to be deleted. Don't go changing standard UI paradigms -- it confuses users and makes them dislike your app.</p>
<p>Just call a touch cancel method there check the swipe is occured ir not with touch points.Then do your functionality</p>
44,564
<p>Every time I create an object that has a collection property I go back and forth on the best way to do it?</p> <ol> <li>public property with a getter that returns a reference to private variable</li> <li>explicit get_ObjList and set_ObjList methods that return and create new or cloned objects every time</li> <li>explicit get_ObjList that returns an IEnumerator and a set_ObjList that takes IEnumerator</li> </ol> <p>Does it make a difference if the collection is an array (i.e., objList.Clone()) versus a List?</p> <p>If returning the actual collection as a reference is so bad because it creates dependencies, then why return any property as a reference? Anytime you expose an child object as a reference the internals of that child can be changed without the parent "knowing" unless the child has a property changed event. Is there a risk for memory leaks?</p> <p>And, don't options 2 and 3 break serialization? Is this a catch 22 or do you have to implement custom serialization anytime you have a collection property?</p> <p>The generic ReadOnlyCollection seems like a nice compromise for general use. It wraps an IList and restricts access to it. Maybe this helps with memory leaks and serialization. However it still has <a href="http://www.coversant.net/Coversant/Blogs/tabid/88/EntryID/34/Default.aspx" rel="noreferrer">enumeration concerns</a> </p> <p>Maybe it just depends. If you don't care that the collection is modified, then just expose it as a public accessor over a private variable per #1. If you don't want other programs to modify the collection then #2 and/or #3 is better.</p> <p>Implicit in the question is why should one method be used over another and what are the ramifications on security, memory, serialization, etc.?</p>
<p>How you expose a collection depends entirely on how users are intended to interact with it.</p> <p><strong>1)</strong> If users will be adding and removing items from an object's collection, then a simple get-only collection property is best (option #1 from the original question):</p> <pre><code>private readonly Collection&lt;T&gt; myCollection_ = new ...; public Collection&lt;T&gt; MyCollection { get { return this.myCollection_; } } </code></pre> <p>This strategy is used for the <code>Items</code> collections on the WindowsForms and WPF <code>ItemsControl</code> controls, where users add and remove items they want the control to display. These controls publish the actual collection and use callbacks or event listeners to keep track of items.</p> <p>WPF also exposes some settable collections to allow users to display a collection of items they control, such as the <code>ItemsSource</code> property on <code>ItemsControl</code> (option #3 from the original question). However, this is not a common use case.</p> <p><br/> <strong>2)</strong> If users will only be reading data maintained by the object, then you can use a readonly collection, as <a href="https://stackoverflow.com/questions/35007/how-to-expose-a-collection-property#35065">Quibblesome</a> suggested:</p> <pre><code>private readonly List&lt;T&gt; myPrivateCollection_ = new ...; private ReadOnlyCollection&lt;T&gt; myPrivateCollectionView_; public ReadOnlyCollection&lt;T&gt; MyCollection { get { if( this.myPrivateCollectionView_ == null ) { /* lazily initialize view */ } return this.myPrivateCollectionView_; } } </code></pre> <p>Note that <code>ReadOnlyCollection&lt;T&gt;</code> provides a live view of the underlying collection, so you only need to create the view once.</p> <p>If the internal collection does not implement <code>IList&lt;T&gt;</code>, or if you want to restrict access to more advanced users, you can instead wrap access to the collection through an enumerator:</p> <pre><code>public IEnumerable&lt;T&gt; MyCollection { get { foreach( T item in this.myPrivateCollection_ ) yield return item; } } </code></pre> <p>This approach is simple to implement and also provides access to all the members without exposing the internal collection. However, it does require that the collection remain unmodfied, as the BCL collection classes will throw an exception if you try to enumerate a collection after it has been modified. If the underlying collection is likely to change, you can either create a light wrapper that will enumerate the collection safely, or return a copy of the collection.</p> <p><br/> <strong>3)</strong> Finally, if you need to expose arrays rather than higher-level collections, then you should return a copy of the array to prevent users from modifying it (option #2 from the orginal question):</p> <pre><code>private T[] myArray_; public T[] GetMyArray( ) { T[] copy = new T[this.myArray_.Length]; this.myArray_.CopyTo( copy, 0 ); return copy; // Note: if you are using LINQ, calling the 'ToArray( )' // extension method will create a copy for you. } </code></pre> <p>You should not expose the underlying array through a property, as you will not be able to tell when users modify it. To allow modifying the array, you can either add a corresponding <code>SetMyArray( T[] array )</code> method, or use a custom indexer:</p> <pre><code>public T this[int index] { get { return this.myArray_[index]; } set { // TODO: validate new value; raise change event; etc. this.myArray_[index] = value; } } </code></pre> <p>(of course, by implementing a custom indexer, you will be duplicating the work of the BCL classes :)</p>
<p>If you're simply looking to expose a collection on your instance, then using a getter/setter to a private member variable seems like the most sensible solution to me (your first proposed option).</p>
5,543
<p>I have a database full of customer data. It's so big that it's really cumbersome to operate on, and I'd rather just slim it down to 10% of the customers, which is plenty for development. I have an awful lot of tables and I don't want to alter them all with "ON DELETE CASCADE", especially because this is a one-time deal.</p> <p>Can I do a delete operation that cascades through all my tables without setting them up first? If not, what is my best option?</p>
<p>Combining your advice and a script I found online, I made a procedure that will produce SQL you can run to perform a cascaded delete regardless of <code>ON DELETE CASCADE</code>. It was probably a big waste of time, but I had a good time writing it. An advantage of doing it this way is, you can put a <code>GO</code> statement between each line, and it doesn't have to be one big transaction. The original was a recursive procedure; this one unrolls the recursion into a stack table.</p> <pre><code>create procedure usp_delete_cascade ( @base_table_name varchar(200), @base_criteria nvarchar(1000) ) as begin -- Adapted from http://www.sqlteam.com/article/performing-a-cascade-delete-in-sql-server-7 -- Expects the name of a table, and a conditional for selecting rows -- within that table that you want deleted. -- Produces SQL that, when run, deletes all table rows referencing the ones -- you initially selected, cascading into any number of tables, -- without the need for "ON DELETE CASCADE". -- Does not appear to work with self-referencing tables, but it will -- delete everything beneath them. -- To make it easy on the server, put a "GO" statement between each line. declare @to_delete table ( id int identity(1, 1) primary key not null, criteria nvarchar(1000) not null, table_name varchar(200) not null, processed bit not null, delete_sql varchar(1000) ) insert into @to_delete (criteria, table_name, processed) values (@base_criteria, @base_table_name, 0) declare @id int, @criteria nvarchar(1000), @table_name varchar(200) while exists(select 1 from @to_delete where processed = 0) begin select top 1 @id = id, @criteria = criteria, @table_name = table_name from @to_delete where processed = 0 order by id desc insert into @to_delete (criteria, table_name, processed) select referencing_column.name + ' in (select [' + referenced_column.name + '] from [' + @table_name +'] where ' + @criteria + ')', referencing_table.name, 0 from sys.foreign_key_columns fk inner join sys.columns referencing_column on fk.parent_object_id = referencing_column.object_id and fk.parent_column_id = referencing_column.column_id inner join sys.columns referenced_column on fk.referenced_object_id = referenced_column.object_id and fk.referenced_column_id = referenced_column.column_id inner join sys.objects referencing_table on fk.parent_object_id = referencing_table.object_id inner join sys.objects referenced_table on fk.referenced_object_id = referenced_table.object_id inner join sys.objects constraint_object on fk.constraint_object_id = constraint_object.object_id where referenced_table.name = @table_name and referencing_table.name != referenced_table.name update @to_delete set processed = 1 where id = @id end select 'print ''deleting from ' + table_name + '...''; delete from [' + table_name + '] where ' + criteria from @to_delete order by id desc end exec usp_delete_cascade 'root_table_name', 'id = 123' </code></pre>
<p>This script has two issues: 1. You must indicate the condition 1=1 in order to delete all table base. 2. This creates the direct relations with the base table only. If the final table has another table parent relation, the the delete fail</p> <p>DELETE FROM [dbo].[table2] WHERE TableID in (select [ID] from [dbo].[table3] where 1=1)</p> <p>If table2 has a parent relation table1</p>
14,252
<p>I am trying to run a java based tool using a command line syntax as the following: java -cp archive.jar archiveFolder.theMainClassName.Although the class I am searching for, a main class, "theMainClassName" is in the archive.jar and in the archiveFolder given at input, I keep getting the error that my class is not seen. Does anybody have any ideas concerning this problem? Thank you in advance</p>
<p>Here's a concrete example of what <em>does</em> work, so you can compare your own situation.</p> <p>Take this code and put it anywhere, in a file called <code>MainClass.java</code>. (I've assumed a directory called <code>src</code> later. Normally you'd arrange the source to match the package, of course.)</p> <pre><code>package archiveFolder; public class MainClass { public static void main(String[] args) { System.out.println("I'm MainClass"); } } </code></pre> <p>Then run each of these commands:</p> <pre><code># Compile the source javac -d . src/MainClass.java # Build the jar file jar cf archive.jar archiveFolder # Remove the unpackaged binary, to prove it's not being used rm -rf archiveFolder # Or rmdir /s /q archiveFolder on Windows # Execute the class java -cp archive.jar achiveFolder.MainClass </code></pre> <p>The result:</p> <pre><code>I'm MainClass </code></pre> <p>How are you building your jar file? Is the code in the appropriate package?</p>
<p>I think others have covered some common stuff here. I'd jar tf the jar and make sure the class is listed. I'd also double-check that the class is public and the method is "public static void main(String[] arg)".</p>
37,407
<p>What is the difference between <code>find-grep</code> and <code>grep-find</code> in Emacs?</p>
<p>You can use <code>M-x describe-function</code> (or <code>C-h f</code> with default keybindings) to answer this question, here's the output for <code>find-grep</code>:</p> <pre><code>find-grep is an alias for `grep-find' in `progmodes/grep.el'. (find-grep COMMAND-ARGS) ... </code></pre>
<p>They seem the same. See <a href="http://www.impernix.org/Manuals/emacs/Grep-Searching.html" rel="nofollow noreferrer">the manual</a></p>
42,423
<p>how can i create an application to read all my browser (firefox) history? i noticed that i have in </p> <p>C:\Users\user.name\AppData\Local\Mozilla\Firefox\Profiles\646vwtnu.default</p> <p>what looks like a sqlite database (urlclassifier3.sqlite) but i don't know if its really what is used to store de history information. i searched for examples on how to do this but didn't find anything.</p> <p>ps: although the title is similar i believe this question is not the same as <a href="https://stackoverflow.com/questions/48805/how-do-you-access-browser-history">"How do you access browser history?"</a></p>
<p>I believe <code>places.sqlite</code> is the one you should be looking into for history (Firefox 3). Below are a couple of Mozilla wiki entries that have some info on the subject.</p> <ul> <li><a href="https://wiki.mozilla.org/Mozilla2:Unified_Storage" rel="noreferrer">Mozilla 2: Unified Storage</a></li> <li><a href="https://wiki.mozilla.org/Browser_History" rel="noreferrer">Browser History</a> <em>(see especially section "Database Design" here)</em></li> </ul> <p>In earlier versions of Firefox they stored history in a file called <code>history.dat</code>, which was encoded in a format called "Mork". <a href="http://www.jwz.org/hacks/mork.pl" rel="noreferrer">This perl script by Jamie Zawinski</a> can be used to parse Mork files.</p>
<p>The <a href="https://addons.mozilla.org/en-US/firefox/addon/5817" rel="nofollow noreferrer">Firefox SQLite Manager Addon</a> is a great tool. If you wish to learn about the Firefox Places design and DB schema visit <a href="https://developer.mozilla.org/en/Places" rel="nofollow noreferrer">Mozilla Places</a>.</p>
7,760