instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>In <code>SQL Server</code>, I can do something like this:</p> <pre><code>UPDATE tbl1 SET col2 = tbl2.col2 FROM table1 tbl1 INNER JOIN table2 tbl2 ON tbl1.col1 = tbl2.col1 </code></pre> <p>I haven't bothered to look whether this is part of any SQL standard or not, and I'm sure there are other ways to do it, but it is <em>astoundingly</em> useful.</p> <p>Here's my problem. I need to do something similar <em>in SQL</em> (i.e, not a host language) with SQLITE3. Can it be done?</p>
<p>This works for sqlite:</p> <pre><code>UPDATE tbl1 SET col2 = (SELECT col2 FROM tbl2 WHERE tbl2.col1 = tbl1.col1) </code></pre>
<p>I've discovered this can be done with <code>INSERT OR REPLACE INTO</code>. A little more verbose than T-SQL's equivalent, but just as handy.</p>
42,660
<p>This code works (C# 3)</p> <pre><code>double d; if(d == (double)(int)d) ...; </code></pre> <ol> <li>Is there a better way to do this?</li> <li>For extraneous reasons I want to avoid the double cast so; what nice ways exist other than this? (even if they aren't as good)</li> </ol> <p><em>Note:</em> Several people pointed out the (important) point that == is often problematic regrading floating point. In this cases I expect values in the range of 0 to a few hundred and they are supposed to be integers (non ints are errors) so if those points "shouldn't" be an issue for me.</p>
<pre><code>d == Math.Floor(d) </code></pre> <p>does the same thing in other words.</p> <p>NB: Hopefully you're aware that you have to be very careful when doing this kind of thing; floats/doubles will very easily accumulate miniscule errors that make exact comparisons (like this one) fail for no obvious reason.</p>
<p>Something like this</p> <pre><code>double d = 4.0; int i = 4; bool equal = d.CompareTo(i) == 0; // true </code></pre>
17,197
<p>What is the best FREE Datepicker that can be dropped into an ASPX application?</p>
<p>There's an excellent, free package that will AJAX enable the calendar control for use as a date picker.</p> <p>Here's the video tutorial: <a href="http://www.asp.net/LEARN/ajax-videos/video-124.aspx" rel="nofollow noreferrer">http://www.asp.net/LEARN/ajax-videos/video-124.aspx</a></p>
<p>Visual studio has one built-in.</p>
12,033
<p>When designing LINQ classes using the LINQ to SQL designer I've sometimes needed to reorder the classes for the purposes of having the resultant columns in a DataGridView appear in a different order. Unfortunately this seems to be exceedingly difficult; you need to cut and paste properties about, or delete them and re-insert them manually.</p> <p>I <em>know</em> you can reorder columns fairly easily in a DataGridView, however that would result in a lot of hardcoding and I want the designer to match up to the grid.</p> <p>Does anyone know of any easier way of achieving this or is cutting/pasting the only available method?</p> <p>I tried manually editing the .designer.cs file, but reordering properties there doesn't appear to do anything!</p> <p><strong>Edit:</strong> Just to make it clear - I want to reorder what's in the LINQ to SQL designer, not what's in the table. I haven't made an error in ordering requiring a reversion to the original table layout; rather I have a table which I want to possess a different ordering in Visual Studio than in SQL Server.</p>
<p>Using Linq-to-Sql, you can have columns in the DataGridView appear different than in the original table by:</p> <ol> <li>In your Linq query, extract the columns that you want, in the order than you want, and store them in a var. Then the autogenerate columns should show them in that order in the DataGridView</li> <li>Use Template columns in your DataGridView</li> <li>Do not use drag-and-drop on the Linq-to-Sql design surface to create your entities. Rather, create them by hand and associate them with the database table using table and column properties</li> </ol> <p>As far as I know, there is no drag-and-drop column reorder in the designer itself</p>
<p>If you are in the scenario where you have reordered the columns in the database, and you now want to have this new order be reflected in the designer, I think that you have to delete the table from the designer and then put it in again. Or if you use <a href="http://msdn.microsoft.com/en-us/library/bb386987.aspx" rel="nofollow noreferrer">SqlMetal</a> to generate your Linq-to-Sql classes, rerun it on your database and use the newly generated file.</p>
5,872
<p>We have a fairly complicated GUI in windows forms using C# and .Net 2.0. My problem is that whenever I drag any window over the GUI, it leaves artifacts over the form. I can't for the life of me figure out how to eliminate it. I've tried enabling double buffering, but it only helps, doesn't eliminate the problem. Other applications don't seem to have this issue, and I'm wondering what we're doing wrong.</p> <p><strong>Update In Response to answers</strong></p> <p>Most of the application is just using a set of third party controls (Infragistics) laid out on a panel. As far as I can tell there is nothing getting done in the GUI thread besides basic(non-cpu intensive) mouse click handling.</p>
<p>You might be doing too much work on the GUI thread. Off-loading some work to background threads will free the GUI up to process Windows messages more responsively.</p>
<p>Related to Jon B's answer, if your application is doing a lot of drawing using the Graphics object in .NET, those methods are fairly slow relative to Windows API calls.</p> <p>Another possibility is that your GUI might not be updating itself in the OnPaint event. Sometimes custom graphics code updates a drawing surface from a timer event, or else only updates the drawing surface when something changes in what needs to be displayed. Code written like this appears to work most of the time, but produces the problem that you describe when another window moves over your window.</p>
32,432
<p>We need a web content accelerator for static images to sit in front of our Apache web front end servers</p> <p>Our previous hosting partner used Tux with great success and I like the fact it's part of Red Hat Linux which we're using, but its last update was in 2006 and there seems little chance of future development. Our ISP recommends we use Squid in reverse caching proxy role.</p> <p>Any thoughts between Tux and Squid? Compatibility, reliability and future support are as important to us as performance.</p> <p>Also, I read in other threads here about Varnish; anyone have any real-world experience of Varnish compared with Squid, and/or Tux, gained in high-traffic environments?</p> <p>Cheers</p> <p>Ian</p> <p>UPDATE: We're testing Squid now. Using ab to pull the same image 10,000 times with a concurrency of 100, both Apache on its own and Squid/Apache burned through the requests very quickly. But Squid made only a single request to Apache for the image then served them all from RAM, whereas Apache alone had to fork a large number of workers in order to serve the images. It looks like Squid will work well in freeing up the Apache workers to handle dynamic pages.</p>
<p>In my experience varnish is much faster than squid, but equally importantly it's much less of a black box than squid is. Varnish gives you access to very detailed logs that are useful when debugging problems. It's configuration language is also much simpler and much more powerful that squid's.</p>
<p>We are about to roll out a varnish 2.01 server in front of an IIS 6 installation. The only caveats we've had was with our SSL (as varnish can't handle SSL). So we've also installed Nginx to handle those requests.</p> <p>In all our testing we've shown a 66% percent increase in the amount of traffic the site can handle.</p> <p>My only gripe is that varnish doesn't handle cookies well, and the documentation is still a bit scattered.</p>
36,965
<p>I have a search program that will be looking at a database from a database. If the date range is more than 3 weeks I want to alert them that it might take a while with all the data in the database. I have a confirm message box in a JavaScript function. I want to check the date range in the aspx.cs page. how do I totrigger the message box based on that criteria? here is a copy of some of my code on html. I am not sure how to approach the checkpoint.</p> <pre><code>function warning() { var answer = confirm("The date range you have selected will return a substantial amount of data and will take some time to process.\n\nAre you sure you want to continue?"); if (answer) return true; else return false; } </code></pre>
<p>A Confirmation Box to go ahead, pops up when the button is clicked</p> <pre><code>SearchButton.Attributes.Add("onclick", "javascript:return " + "confirm('" + "The date range you have selected will return a substantial amount of data and will take some time to process.\n\nAre you sure you want to continue?')"); </code></pre>
<p>Why check the date range on the server side? If you have the date range on the client side, its considerably less work.</p> <p>Otherwise, you will need to postpack (or partially post), and then check the date range, then render the warning javascript back out to the page...</p> <p>Time to rethink your method.</p>
43,471
<p>How do I truncate output in BASH? </p> <p>For example, if I "du file.name" how do I just get the numeric value and nothing more?</p> <p>later addition:<br> all solutions work perfectly. I chose to accept the most enlightning "cut" answer because I prefer the simplest approach in bash files others are supposed to be able to read.</p>
<p>If you know what the delimiters are then cut is your friend</p> <pre><code>du | cut -f1 </code></pre> <p>Cut defaults to tab delimiters so in this case you are selecting the first field. </p> <p>You can change delimiters: cut -d ' ' would use a space as a delimiter. (from <a href="https://stackoverflow.com/users/18771/tomalak">Tomalak</a>)</p> <p>You can also select individual character positions or ranges: </p> <pre><code>ls | cut -c1-2 </code></pre>
<p>If you just want the number of bytes of a single file, use the <code>-s</code> operator.</p> <pre><code>SIZE=-s file.name </code></pre> <p>That gives you a different number than <code>du</code>, but I'm not sure how exactly you're using this.</p> <p>This has the advantage of not having to run <code>du</code>, and having <code>bash</code> get the size of the file directly.</p> <p>It's hard to answer questions like this in a vacuum, because we don't know how you're going to use the data. Knowing that might suggest an entirely different answer.</p>
29,638
<p>I am working through a book which gives examples of Ranges being converted to equivalent arrays using their "to_a" methods</p> <p>When i run the code in irb I get the following warning</p> <pre><code> warning: default `to_a' will be obsolete </code></pre> <p>What is the the correct alternative to using to_a?</p> <p>are there alternate ways to populate an array with a Range?</p>
<p>You can create an array with a range using splat,</p> <pre><code>&gt;&gt; a=*(1..10) =&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>using <code>Kernel</code> <code>Array</code> method,</p> <pre><code>Array (1..10) =&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre> <p>or using to_a</p> <pre><code>(1..10).to_a =&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </code></pre>
<p>I just tried to use ranges from bigger to smaller amount and got the result I didn't expect:</p> <pre><code>irb(main):007:0&gt; Array(1..5) =&gt; [1, 2, 3, 4, 5] irb(main):008:0&gt; Array(5..1) =&gt; [] </code></pre> <p>That's because of ranges implementations.<br /> So I had to use the following option:</p> <pre><code>(1..5).to_a.reverse </code></pre>
23,231
<p>My company has a 3rd party application that runs on a <a href="http://www.progress.com/" rel="nofollow noreferrer">Progress</a> database. I've been building an application on top of their database using an ODBC connection.</p> <p>One of the "quirks" of Progress is that it doesn't honor SQL column widths, so it will allow 100 characters in a column defined as a varchar(50). When reading this data via ODBC, I get the following error:</p> <blockquote> <p>Column test_column in table PUB.test_table has value exceeding its max length or precision.</p> </blockquote> <p>The support techs at the company that build the application pointed me towards adding some work around flags in the registry for the ODBC connection, however, I can't find any documentation as to what these flags will do or what the possible values are. The registry keys are</p> <blockquote> <p>KEY_CURRENT_USER->Software->ODBC->ODBC.INI->MyODBCConnectionName->WorkArounds KEY_CURRENT_USER->Software->ODBC->ODBC.INI->MyODBCConnectionName->WorkArounds2</p> </blockquote> <p>Google has found me other problems that people have solved by adding these flags with specific values (including my personal favourite from <a href="http://thedailywtf.com/Articles/Oh,_the_Workarounds.aspx" rel="nofollow noreferrer">The Daily WTF</a>) but I can't find anywhere that tells me what the flags actually do. Do you know?</p>
<p>The link from @tom-bascom no longer works because Progress moved their KB. the comment from @stefan-moser on @mdb's question is appropriate. </p> <p>According to <a href="http://media.datadirect.com/download/docs/odbc/allodbc/reference/workarounds.html" rel="nofollow">Chapter 11 WorkAround Options</a> of the <a href="http://www.datadirect.com/download/docs/odbc/allodbc/help.htm" rel="nofollow">DataDirect Connect Series for ODBC Reference</a></p> <p>WorkArounds2=8192. Enabling this option causes Microsoft Access not to pass the error -7748. Microsoft Access only asks for data as a two-byte SQL_C_WCHAR, which is an insufficient buffer size to store the UCS2 character and the null terminator; thus, the driver returns a warning, "01004 Data truncated" and returns a null character to Microsoft Access. Microsoft Access then passes error -7748.</p> <p>references:</p> <ul> <li><a href="http://www.datadirect.com/techres/odbc.html" rel="nofollow">ODBC PRODUCT DOCUMENTATION</a></li> <li><a href="http://www.datadirect.com/download/docs/odbc/allodbc/help.htm" rel="nofollow">DataDirect Connect Series for ODBC Reference</a></li> <li><a href="http://media.datadirect.com/download/docs/odbc/allodbc/reference/workarounds.html" rel="nofollow">http://media.datadirect.com/download/docs/odbc/allodbc/reference/workarounds.html</a></li> </ul>
<p>The <a href="http://media.datadirect.com/download/docs/odbc/readme/unixread.htm" rel="nofollow noreferrer">README file for DataDirect Connect for ODBC</a> (a Unix-based ODBC driver) contains a list of workarounds in the "Driver WorkAround Options" section of the document.</p>
21,765
<p>My client wants me to enable a "Remember Me" checkbox when the user logs in. I am encrypting and storing both the username and password in a cookie.</p> <p>However, you cannot write to a textbox when it's in password mode.</p> <p>I've seen this done numerous times, so how are they doing it?</p> <p>thanks in advance!</p>
<p>How about instead of inserting the text into the login form, you just bypass the form completely and check the contents of the cookie right at the login page? Less work for the user, and it'll make it a little more seamless.</p>
<p>You can set the expiration of the cookie in 2 weeks to keep the user logged in. That's how ASP.NET authentication works with persistent authentication. Remember to update the expiration on every request.</p>
18,103
<p>In C#, if I have an inherited class with a default constructor, do I have to explicitly call the base class' constructor or will it be implicitly called?</p> <pre><code>class BaseClass { public BaseClass() { // ... some code } } class MyClass : BaseClass { public MyClass() // Do I need to put ": base()" here or is it implied? { // ... some code } } </code></pre>
<p>You do not need to explicitly call the base constructor, it will be implicitly called.</p> <p>Extend your example a little and create a Console Application and you can verify this behaviour for yourself:</p> <pre><code>using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { MyClass foo = new MyClass(); Console.ReadLine(); } } class BaseClass { public BaseClass() { Console.WriteLine("BaseClass constructor called."); } } class MyClass : BaseClass { public MyClass() { Console.WriteLine("MyClass constructor called."); } } } </code></pre>
<p>You don’t need call the base constructor explicitly it will be implicitly called, but sometimes you need pass parameters to the constructor in that case you can do something like:</p> <pre><code>using System; namespace StackOverflow.Examples { class Program { static void Main(string[] args) { NewClass foo = new NewClass("parameter1","parameter2"); Console.WriteLine(foo.GetUpperParameter()); Console.ReadKey(); } } interface IClass { string GetUpperParameter(); } class BaseClass : IClass { private string parameter; public BaseClass (string someParameter) { this.parameter = someParameter; } public string GetUpperParameter() { return this.parameter.ToUpper(); } } class NewClass : IClass { private BaseClass internalClass; private string newParameter; public NewClass (string someParameter, string newParameter) { this.internalClass = new BaseClass(someParameter); this.newParameter = newParameter; } public string GetUpperParameter() { return this.internalClass.GetUpperParameter() + this.newParameter.ToUpper(); } } } </code></pre> <p>Note: If someone knows a better solution please tells me.</p>
3,872
<p>I have limited experience with .net. My app throws an error this.dateTimeFormat is undefined which I tracked down to a known ajax bug. The workaround posted said to:</p> <p>"Register the following as a startup script:"</p> <pre><code>Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) { if (!this._upperAbbrMonths) { this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames); } return Array.indexOf(this._upperAbbrMonths, this._toUpper(value)); }; </code></pre> <p>So how do I do this? Do I add the script to the bottom of my aspx file?</p>
<p>You would use <a href="http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx" rel="noreferrer">ClientScriptManager.RegisterStartupScript()</a></p> <pre><code>string str = @"Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) { if (!this._upperAbbrMonths) { this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames); } return Array.indexOf(this._upperAbbrMonths, this._toUpper(value)); };"; if(!ClientScriptManager.IsStartupScriptRegistered("MyScript"){ ClientScriptManager.RegisterStartupScript(this.GetType(), "MyScript", str, true) } </code></pre>
<p>Put it in the header portion of the page</p>
15,147
<p>Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap?</p>
<p>One way you could do this would be to make the constructors private and only allow construction through a static method that returns a pointer. For example:</p> <pre><code>class Foo { public: ~Foo(); static Foo* createFoo() { return new Foo(); } private: Foo(); Foo(const Foo&amp;); Foo&amp; operator=(const Foo&amp;); }; </code></pre>
<p>You could create a header file that provides an abstract interface for the object, and factory functions that return pointers to objects created on the heap.</p> <pre><code>// Header file class IAbstract { virtual void AbstractMethod() = 0; public: virtual ~IAbstract(); }; IAbstract* CreateSubClassA(); IAbstract* CreateSubClassB(); // Source file class SubClassA : public IAbstract { void AbstractMethod() {} }; class SubClassB : public IAbstract { void AbstractMethod() {} }; IAbstract* CreateSubClassA() { return new SubClassA; } IAbstract* CreateSubClassB() { return new SubClassB; } </code></pre>
15,184
<p>I am working on an application that will be used as an extensible framework for other applications.</p> <p>One of the fundamental classes is called Node, and Nodes have Content. The SQL tables look like this:</p> <p>TABLE Node ( NodeId int, .... etc )</p> <p>TABLE NodeContentRelationship ( NodeId int, ContentType string, ContentId int)</p> <p>It will be up to the developers extending the application to create their own content types.</p> <p>Clearly this is bad from a relationship-database point of view as it is not possible to add a foreign key relationship to NodeContentRelationship.ContentId, even though it <em>is</em> a foreign key column.</p> <p>However, the solution is quite simple and powerful so I am reluctant to change it.</p> <p>What do you think - am I in for a world of pain down the track?</p>
<p>Beware the <a href="http://thedailywtf.com/Articles/The_Inner-Platform_Effect.aspx" rel="noreferrer">Inner Platform Effect</a>.</p> <p>If you're trying to build an 'extensible framework' which allows developers to store data of different 'content types' and relate them to each other in a generic fashion, you may find that others have already <a href="http://www.microsoft.com/sqlserver/2008/en/us/default.aspx" rel="noreferrer">solved</a> <a href="http://www.oracle.com/index.html" rel="noreferrer">this</a> <a href="http://www.mysql.com/" rel="noreferrer">problem</a>.</p>
<p>You're in for a world of hurt down the road if you ever want to actually report on this data. You just made it much much harder to write joins and such. The lack of constraints is bad, but the extra work needed on queries is (IMHO) worse.</p> <p>However, if you want other developers to be able to extend the system and store data in the database but not be able to change the database schema, there might not be a choice. In that case, the answer is to minimize how much gets stored this way. You might also speed it up slightly by replacing ContentType with a ContentTypeId defined in another table.</p>
37,668
<p>I need to change the credentials of an already existing Windows service using C#. I am aware of two different ways of doing this.</p> <ol> <li>ChangeServiceConfig, see <a href="http://www.pinvoke.net/default.aspx/advapi32.ChangeServiceConfig" rel="nofollow noreferrer">ChangeServiceConfig on pinvoke.net</a></li> <li>ManagementObject.InvokeMethod using Change as the method name.</li> </ol> <p>Neither seems a very "friendly" way of doing this and I was wondering if I am missing another and better way to do this.</p>
<p>Here is one quick and dirty method using the System.Management classes.</p> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.Management; namespace ServiceTest { class Program { static void Main(string[] args) { string theServiceName = "My Windows Service"; string objectPath = string.Format("Win32_Service.Name='{0}'", theServiceName); using (ManagementObject mngService = new ManagementObject(new ManagementPath(objectPath))) { object[] wmiParameters = new object[11]; wmiParameters[6] = @"domain\username"; wmiParameters[7] = "password"; mngService.InvokeMethod("Change", wmiParameters); } } } } </code></pre>
<p>ChangeServiceConfig is the way that I've done it in the past. WMI can be a bit flaky and I only ever want to use it when I have no other option, especially when going to a remote computer.</p>
15,307
<p>When running get svn fetch to pull the latest new branches from the upstream svn repository I got this error:</p> <pre><code>$ git svn fetch fatal: failed to unpack tree object 5ecb324e8b8fcb918acb253f33edc6ce49e49e0d read-tree 5ecb324e8b8fcb918acb253f33edc6ce49e49e0d: command returned error: 128 </code></pre> <p>Now every attempt at git svn on that local repo results in the same error. Originally I was running git version 1.5.6.4_0 and after the error I tried updating to 1.6.0.2_2 and the problem still persists.</p> <p>Is there any way to clean up this corruption? A fresh git svn clone of the upstream repository is fine, but I'd like to preserve my existing setup. I've looked through the docs and googled for the problem with no luck.</p>
<p>I had the same problem. It is due to a particular SVN revision that git-svn can't read or deal with somehow. Here is what i tried in order:</p> <ol> <li>Rewind to a revision known to work: <code>git svn reset -r 42</code></li> <li>Retry the fetch: <code>git svn fetch</code> — Fetches each revision starting from 42 until the guilty one (say 50), then shows the same error message.</li> <li>Fetch the parent: <code>git svn fetch --parent</code> — Don't ask me why. That fetches more revisions. No idea whether it's relevant though.</li> <li>Retry the fetch: <code>git svn fetch</code> — Still doesn't work.</li> <li>Fetch each of the next revisions: <ol> <li><code>git svn fetch -r 50</code> — Works.</li> <li><code>git svn fetch -r 51</code> — While no error message, go on.</li> <li><code>git svn fetch -r xx</code> — The error message shows up, it's the bad revision. Don't care.</li> <li><code>git svn fetch -r xx+1</code> — Works.</li> </ol></li> <li>Retry the fetch: <code>git svn fetch</code> — Works! Starts to fetch more revisions.</li> </ol> <p>The process ought to be cleaned up (probably near the first steps), but it worked for me, without having to start again with a fresh clone.</p>
<p>The most likely cause for this is a file or commit (that the tree references) is corrupted or missing. Or the tree itself could be corrupted. Check with:</p> <pre><code>git fsck --unreachable HEAD $(cat .git/refs/heads/*) </code></pre> <p>This will show a bunch of "dangling" files, which you don't care about; corrupted files will report "Invalid SHA1" or some such thing. I don't know how a missing file would report. Remove any corrupt items and <code>rsync</code> from your upstream repo to replace them. </p>
43,889
<p>Is there some reasonably cross platform way to create a thumbnail image given a URL? I know there are thumbnail web services that will do this, but I want a piece of software or library that will do this locally. I guess in Linux I could always spawn a browser window using a headless X server, but what about Windows or OS X?</p>
<p>You can use Firefox or XULRunner with some fairly simple XUL to create thumbnails as PNG dataURLs (that you could then write to file if needed). Robert O'Callahan has some excellent information on it here:</p> <p><a href="http://weblogs.mozillazine.org/roc/archives/2005/05/rendering_web_p.html" rel="nofollow noreferrer">http://weblogs.mozillazine.org/roc/archives/2005/05/rendering_web_p.html</a></p>
<p>There are a number of commercial packages that will do what you want. I'm not sure from reading your question if free is a requirement. But here are some applications I've found that are reasonably priced and which do exactly what you want. I have not used them myself, but they have free trial downloads so you can evaluate before you purchase.</p> <ul> <li><a href="http://www.guangmingsoft.net/htmltoimage/help.htm" rel="nofollow noreferrer">HTML to Image from Guanming Software</a> - Runs on Linux and Windows</li> <li><a href="http://www.sysimage.com/windows/html2image/" rel="nofollow noreferrer">HTML2Image from SysImage</a> - Runs on Windows</li> <li><a href="http://www.tooto.com/html2image/" rel="nofollow noreferrer">HTML2Image from Tooto</a> - Runs on Windows</li> <li><a href="http://www.converthtmltoimage.com/" rel="nofollow noreferrer">Convert HTML to Image from FrameworkTeam</a> - Windows command line tool</li> </ul>
9,082
<p>How can I remove duplicate values from a multi-dimensional array in PHP?</p> <p>Example array:</p> <pre><code>Array ( [0] =&gt; Array ( [0] =&gt; abc [1] =&gt; def ) [1] =&gt; Array ( [0] =&gt; ghi [1] =&gt; jkl ) [2] =&gt; Array ( [0] =&gt; mno [1] =&gt; pql ) [3] =&gt; Array ( [0] =&gt; abc [1] =&gt; def ) [4] =&gt; Array ( [0] =&gt; ghi [1] =&gt; jkl ) [5] =&gt; Array ( [0] =&gt; mno [1] =&gt; pql ) ) </code></pre>
<p>Here is another way. No intermediate variables are saved. </p> <p>We used this to de-duplicate results from a variety of overlapping queries.</p> <pre><code>$input = array_map("unserialize", array_unique(array_map("serialize", $input))); </code></pre>
<p>Based on the Answer marked as correct, adding my answer. Small code added just to reset the indices-</p> <pre><code>$input = array_values(array_map("unserialize", array_unique(array_map("serialize", $inputArray)))); </code></pre>
39,604
<p>Can you suggest how to create a test environment to simulate various types of bandwidths and traffic in a web app?</p> <p>Or maybe an open source program which does this against localhost?</p> <p>I think this is a very important subject when programming web apps but it is not a usual topic, the only way i can imagine to create such kind of environment is to use some kind of proxy in a local network but before start looking into the squid documentation i would like to hear your suggestions.</p>
<p>if you're using apache you may want to take a look at <a href="http://httpd.apache.org/docs/2.0/programs/ab.html" rel="noreferrer">apache ab</a></p>
<p>We use Loadrunner to do bandwidth and traffic simulation in our App. Loadrunner is can start agents on various machines and you can simulate one machine as running on dialup modem v/s another on DSL v/s another on Cable internet. We also use Loadrunner to simulate various kinds of traffic conditions from 10 user run to 500 user run. We can also insert think times in the script and simulate a real user executing the http request. The best part is that it comes with a recording studio where it will plug in with Internet explorer and you can record the whole scenario/Usecase that can be as simple as hitting one page to a full blown 50-60 page script or more.</p>
18,784
<p>Imagine you don't have the problem of feature creep, you have a motivated and stable team, clear defined problems to solve, AND you know the domain/language/tools related to your project.</p> <p>How do you <em>stick to a schedule</em> and accomplish that 1.0 milestone?<br> What is your approach to an <em>iterative shipping</em>?</p> <p>I'd like recommendations specially for a small team, where there are few or almost none communication problems.</p>
<ol> <li>Focus on features not implementation tasks.</li> <li>Work in iterations (like weekly or biweekly).</li> <li>Release working features to your staging environment in order of priority.</li> <li>Unit test your code as you go, so you're not slowed down by a buglist that increases geometrically as you approach the release date.</li> <li>Be prepared to cut scope from the less important features. Stuff always takes longer than you think it will.</li> <li>Make sure you sketch out the UI in advance (if there is a UI), and show it to potential users.</li> <li>Test, test, and test some more. This seems counter-intuitive, but it saves more time than takes.</li> </ol>
<p>Stage <strong><em>periodic</em></strong> (monthly? weekly?) product walkthroughs using the current accepted build, for the benefit of the Product Team. Begin these as early as possible. Demo every feature, regardless of their current usability; don't skip over the ones which are lagging behind.</p> <p>The point is to give the stakeholders a clear idea of the current state of the product over the course of the project. This way decisionmakers are more likely to tackle schedule risks promptly, rather than jeopardize the ship date.</p>
20,863
<p>At the risk of becoming the village idiot, can someone explain to me why generics are called generics? I understand their usage and benefits, but if the <a href="http://dictionary.reference.com/browse/generic" rel="noreferrer">definition of generic</a> is "general" and generic collections are type safe, then why isn't this a misnomer?</p> <p>For example, an ArrayList can hold anything that's an object:</p> <pre><code>ArrayList myObjects = new ArrayList(); myObjects.Add("one"); myObjects.Add(1); </code></pre> <p>while a generic collection of type string can only hold strings:</p> <pre><code>var myStrings = new List&lt;string&gt;(); myStrings.Add("one"); myStrings.Add("1"); </code></pre> <p>I'm just not clear on why it's called "generic". If the answer is "...which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code." from <a href="http://msdn.microsoft.com/en-us/library/512aeb7t(VS.80).aspx" rel="noreferrer">here</a>, then I suppose that makes sense. Perhaps I'm having this mental lapse because I only began programming after Java introduced generics, so I don't recall a time before them. But still...</p> <p>Any help is appreciated.</p>
<p>"Generic" is talking about the implementation. You write a single "Generic" list implementation that works with any type, instead of having to write specific implementations for each type you want to use.</p>
<p>I am not a "native" English Speaker, so I could be wrong but the point of the "Generics" is that the Define Generics types, isn't it?</p>
39,841
<p>I tried searching around, but I couldn't find anything that would help me out.</p> <p>I'm trying to do this in SQL:</p> <pre><code>declare @locationType varchar(50); declare @locationID int; SELECT column1, column2 FROM viewWhatever WHERE CASE @locationType WHEN 'location' THEN account_location = @locationID WHEN 'area' THEN xxx_location_area = @locationID WHEN 'division' THEN xxx_location_division = @locationID </code></pre> <p>I know that I shouldn't have to put '= @locationID' at the end of each one, but I can't get the syntax even close to being correct. SQL keeps complaining about my '=' on the first WHEN line...</p> <p>How can I do this?</p>
<pre><code>declare @locationType varchar(50); declare @locationID int; SELECT column1, column2 FROM viewWhatever WHERE @locationID = CASE @locationType WHEN 'location' THEN account_location WHEN 'area' THEN xxx_location_area WHEN 'division' THEN xxx_location_division END </code></pre>
<p>Try this query. Its very easy to understand:</p> <pre><code>CREATE TABLE PersonsDetail(FirstName nvarchar(20), LastName nvarchar(20), GenderID int); GO INSERT INTO PersonsDetail VALUES(N'Gourav', N'Bhatia', 2), (N'Ramesh', N'Kumar', 1), (N'Ram', N'Lal', 2), (N'Sunil', N'Kumar', 3), (N'Sunny', N'Sehgal', 1), (N'Malkeet', N'Shaoul', 3), (N'Jassy', N'Sohal', 2); GO SELECT FirstName, LastName, Gender = CASE GenderID WHEN 1 THEN 'Male' WHEN 2 THEN 'Female' ELSE 'Unknown' END FROM PersonsDetail </code></pre>
25,296
<p>You must have heard the archetypical story of a failing/failed project:</p> <ol> <li>A team of inexperienced programmers work 24x7</li> <li>Bugs are fixed only to introduce new bugs</li> <li>Customer is screaming that he could not even do the basic stuff (Saving/Querying) etc.</li> <li>Programmers used to having the spec handed down struggle to improvise</li> <li>No automated unit tests aggravate the situation</li> <li>Architecture document that looked nice on paper was not followed in practice</li> <li>Third party components used become bottlenecks not having been tested for fitness in the first place</li> <li>Milestone after milestone missed</li> <li>The team is not able to come up with a delivery date as nobody agrees as to the quantum of work actually needs to be done</li> <li>No technical leadership / or a Cowboy Coder that can take on the technical issues</li> </ol> <p>Now, If you were to be brought in as #10 what would be your first steps?</p> <p>Update: First of all: Thanks to you all for chipping in. Well... I'm being brought in as #10. I was the original Architect anchoring the solution when we made the proposal to the client. Then, unfortunately, I couldn't take on the delivery responsibilities as I was assigned somewhere else. :)</p> <p>Let's say it's a webification of an existing desktop application. I'm now being brought in as #10. Running away, sadly, is not an option. I'm sure this can still be reversed by following agile best practices and just wanted to tap the community for ideas.</p> <p>The larger question perhaps is this: If the development team does not have specs but only the (baselined) code for a running application, the original solution called for looking at the code and extracting business rules on the fly. Now, the inexperienced programmers are reluctant to look at VB 6.0 code and want documents! So how do you fight this if you were to instate Agile processes?</p>
<p>Vyas, I feel like I could have written this question. My previous job involved resurrecting a KVM project that had failed after a year's development. Specs were in the form of a user manual and developers' experience with similar products. I ended up teaching C to 3 assembly programmers and re-architecting from scratch. We brought the product successfully to market in 4 months. (Then I resigned. Go figure.)</p> <p>Some of the things I'd do again, particularly with an inexperienced team:</p> <p><em>1. A team of inexperienced programmers work 24x7</em><br> <em>10. No technical leadership / or a Cowboy Coder that can take on the technical issues</em> </p> <ul> <li>Give them a (short!) break from the project to "recharge." Maybe a day, maybe an afternoon, or maybe a long lunch on you. It will mark the end of the "old" project and the beginning of success.</li> <li>Get their agreement to work their butts off when they return, and promise that you will be their go-to guy, cheerleader, and flak jacket. You, collectively, are a team, and your job is to forge their path, eliminate distractions, and lead them. </li> <li>Plan an immediate success, no matter how small, and maintain a "can-do" attitude.</li> </ul> <p><em>8. Milestone after milestone missed</em><br> <em>9. The team is not able to come up with a delivery date as nobody agrees as to the quantum of work actually needs to be done</em><br> <em>3. Customer is screaming that he could not even do the basic stuff (Saving/Querying) etc.</em> </p> <ul> <li><strong>Take small bites!</strong> Break each piece down as far as possible, then deal with the small components. You'll identify "gotchas" early and be better able to scope the whole project.</li> <li><strong>Define your interfaces.</strong> Anytime you can isolate a chunk, <strong>do it.</strong> This allows parallel development, because you've already decided on parameters, preconditions, assumptions, what happens inside, and return values. You can stub it out, and <em>build other modules and tests independently.</em> </li> <li><strong>Prioritize.</strong> Focus on the defects and issues that affect the customer first. New features come last. If necessary, defer features rather than delivering buggy code.</li> <li><strong>Assign responsibilities.</strong> Volunteers are preferred, each in his/her area of expertise, but <em>one</em> person must be accountable for each task.</li> <li><strong>Track defects,</strong> and record everything that will help you reproduce, locate, and fix them. Document any that remain at delivery time, so the customer won't be surprised.</li> </ul> <p><em>4. Programmers used to having the spec handed down struggle to improvise</em><br> <em>6. Architecture document that looked nice on paper was not followed in practice</em></p> <ul> <li><em>You</em> will create the spec details as you go, each piece just before it's needed. It needn't be pretty, complete, or even written, as long as everyone understands the current task and you've got the big picture.</li> <li>Discuss the implementation, one piece at a time, when the developer is ready to code it. Write the skeleton yourself if necessary, and let the team fill in the "guts." You want to keep them focused on each task, without "improvising."</li> <li>Be available to answer questions as they arise. Your primary goal is to keep the team productive.</li> </ul> <p><em>2. Bugs are fixed only to introduce new bugs</em><br> <em>5. No automated unit tests aggr[a]vate the situation</em></p> <ul> <li>Plan and start unit testing ASAP. If possible, enlist resources outside the team.</li> <li>Fix small problems before they grow larger--or get hidden. Confidence in each small piece builds confidence in the whole.</li> </ul> <p><em>7. Third party components used become bottlenecks not having been tested for fitness in the first place</em></p> <ul> <li>Brainstorm solutions when you're not coding. Don't let them stop your progress if at all possible. Can you encapsulate or code around them? Replace them?</li> </ul> <p><strong>General suggestions:</strong></p> <ul> <li><strong>Stay ahead of the team.</strong> Anticipate and try to solve problems before your team hits them. Gather any necessary information before it's needed.</li> <li><strong>Communicate constantly.</strong> Make it clear that you want no surprises, and solicit concerns, questions, status, roadblocks, <em>etc</em> throughout each day. Encourage collaboration and share "discoveries" across the team.</li> <li><strong>Celebrate every success.</strong> Compliment a clever solution, bring donuts when a problem is solved, demonstrate a new working feature ... anything that shows the team you appreciate them.</li> <li><strong>Get each task done, then move ahead.</strong> Don't waste time tweaking, enhancing, or reworking anything that isn't a direct barrier to success. </li> <li><strong>Keep your promises</strong> to the team, the customer, and your management.</li> </ul> <p>Good luck -- please keep us posted!</p>
<p>If you were involved in the project from the beginning, I hate to say it, but the company should replace you (and the entire team). </p> <p>It should be reanalyzed with a competent team with real project management processes and lead by a project manager with experience in this situation.</p> <p>None of the original coders should work on the 'new project' of saving it. They can move to other projects (they don't have to be fired) but to get a fresh look at the project, everybody should be replaced.</p> <p>And of course, management has to understand and be on board with the fact that the project is going to be much later than expected. If management doesn't agree with this (replace team, find experienced leadership, take a step back and start again) then @Maxim is right - get out of there.</p>
29,042
<p>I'm not looking for the usual answer like Web-services. I'm looking for a light solution to be run in the same machine.</p> <p>Edit: I'm looking for way in Java to call .NET methods</p>
<p>I believe Java can talk to COM and .NET can expose COM interfaces. So that may be a very light weight solution that doesn't require any 3rd party. There is also the option of using sockets to communicate between the programs which wouldn't require a heavy instance of IIS to be installed on the machine.</p>
<p>We tried IKVM in our production environment but it kept crashing. We use JNBridge which is a commercial product but is very stable and performs well in our ASP.NET environment.</p>
35,974
<p>I have two arrays in PHP. The first array ($author_array) is comprised of user_ids in a particular order, like so: (8, 1, 6)</p> <p>The second array ($user_results) is comprised of an array of objects like so:</p> <pre><code>Array ( [0] =&gt; stdClass Object ( [ID] =&gt; 1 [user_login] =&gt; user1 ) [1] =&gt; stdClass Object ( [ID] =&gt; 6 [user_login] =&gt; user6 ) [2] =&gt; stdClass Object ( [ID] =&gt; 8 [user_login] =&gt; user8 ) ) </code></pre> <p>I'd like to "sort" the second array so it's in this order, which matches the order of the values in the first array of (8, 1, 6). So it'd look like this:</p> <pre><code>Array ( [0] =&gt; stdClass Object ( [ID] =&gt; 8 [user_login] =&gt; user8 ) [1] =&gt; stdClass Object ( [ID] =&gt; 1 [user_login] =&gt; user1 ) [2] =&gt; stdClass Object ( [ID] =&gt; 6 [user_login] =&gt; user6 ) ) </code></pre> <p>I'm weak on data structures. How could I do this? :-)</p> <p>Thanks in advance for your help!</p> <p>-Bob</p>
<p>Use <a href="http://php.net/uksort" rel="noreferrer">usort</a> and provide a custom comparison function which uses the position of the key in your "ordering" array to determine the sort order, e.g. something like:</p> <pre><code>function cmp($a, $b) { global $author_array; $pos1=array_search ($a-&gt;ID, $author_array); $pos2=array_search ($b-&gt;ID, $author_array); if ($pos1==$pos2) return 0; else return ($pos1 &lt; $pos2 ? -1 : 1); } usort($user_results, "cmp"); </code></pre>
<pre><code>public static function reorganizeBykey ($objects, array $keys){ $results = array(); foreach($keys as $key){ $i=0; foreach($objects as $object){ if($object-&gt;sourceName==$key){ $results[$i] = $object; } $i++; } } $others = (array_diff_assoc($objects,$results)); $results = array_merge($results,$others); return $results; } </code></pre> <p>I hope this is helpful – I had to use this to sort an <code>array()</code> by some <code>keys()</code> and then append what doesn't match at the end.</p>
46,344
<p>Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD.</p>
<p>You can add the catalog to the <code>XML_CATALOG_FILES</code> environment variable:</p> <pre><code>os.environ['XML_CATALOG_FILES'] = 'file:///to/my/catalog.xml' </code></pre> <p>See <a href="http://thread.gmane.org/gmane.comp.python.lxml.devel/5907" rel="noreferrer">this thread</a>. Note that entries in <code>XML_CATALOG_FILES</code> are space-separated URLs. You can use Python's <code>pathname2url</code> and <code>urljoin</code> (with <code>file:</code>) to generate the URL from a pathname.</p>
<p>It seems that lxml does not expose this libxml2 feature, grepping the source only turns up some #defines for the error handling:</p> <pre><code>C:\Dev&gt;grep -ir --include=*.px[id] catalog lxml-2.1.1/src | sed -r "s/\s+/ /g" lxml-2.1.1/src/lxml/dtd.pxi: catalog. lxml-2.1.1/src/lxml/xmlerror.pxd: XML_FROM_CATALOG = 20 # The Catalog module lxml-2.1.1/src/lxml/xmlerror.pxd: XML_WAR_CATALOG_PI = 93 # 93 lxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_MISSING_ATTR = 1650 lxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_ENTRY_BROKEN = 1651 # 1651 lxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_PREFER_VALUE = 1652 # 1652 lxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_NOT_CATALOG = 1653 # 1653 lxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_RECURSION = 1654 # 1654 lxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG=20 lxml-2.1.1/src/lxml/xmlerror.pxi:WAR_CATALOG_PI=93 lxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_MISSING_ATTR=1650 lxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_ENTRY_BROKEN=1651 lxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_PREFER_VALUE=1652 lxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_NOT_CATALOG=1653 lxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_RECURSION=1654 </code></pre> <p>From the <a href="http://xmlsoft.org/catalog.html" rel="nofollow noreferrer">catalog implementation in libxml2 page</a> it seems possible that the 'transparent' handling through installation in /etc/xml/catalog may still work in lxml, but if you need more than that you can always abandon lxml and use the default python bindings, which do expose the catalog functions.</p>
3,362
<p>In c++ what is object slicing and when does it occur?</p>
<p>"Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away.</p> <p>For example, </p> <pre><code>class A { int foo; }; class B : public A { int bar; }; </code></pre> <p>So an object of type <code>B</code> has two data members, <code>foo</code> and <code>bar</code>.</p> <p>Then if you were to write this:</p> <pre><code>B b; A a = b; </code></pre> <p>Then the information in <code>b</code> about member <code>bar</code> is lost in <code>a</code>.</p>
<p>when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off (discard) form the base class object.</p> <pre><code>class Base { int x; }; class Derived : public Base { int z; }; int main() { Derived d; Base b = d; // Object Slicing, z of d is sliced off } </code></pre>
34,598
<p>This is a question you can read everywhere on the web with various answers:</p> <pre><code>$ext = end(explode('.', $filename)); $ext = substr(strrchr($filename, '.'), 1); $ext = substr($filename, strrpos($filename, '.') + 1); $ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename); $exts = split("[/\\.]", $filename); $n = count($exts)-1; $ext = $exts[$n]; </code></pre> <p>etc.</p> <p>However, there is always "the best way" and it should be on Stack Overflow.</p>
<p>People from other scripting languages always think theirs is better because they have a built-in function to do that and not PHP (I am looking at Pythonistas right now :-)).</p> <p>In fact, it does exist, but few people know it. Meet <a href="http://php.net/manual/en/function.pathinfo.php" rel="noreferrer"><code>pathinfo()</code></a>:</p> <pre><code>$ext = pathinfo($filename, PATHINFO_EXTENSION); </code></pre> <p>This is fast and built-in. <code>pathinfo()</code> can give you other information, such as canonical path, depending on the constant you pass to it.</p> <p>Remember that if you want to be able to deal with non ASCII characters, you need to set the locale first. E.G:</p> <pre><code>setlocale(LC_ALL,'en_US.UTF-8'); </code></pre> <p>Also, note this doesn't take into consideration the file content or mime-type, you only get the extension. But it's what you asked for.</p> <p>Lastly, note that this works only for a file path, not a URL resources path, which is covered using PARSE_URL.</p> <p>Enjoy</p>
<p>Use </p> <pre><code>str_replace('.', '', strrchr($file_name, '.')) </code></pre> <p>for a quick extension retrieval (if you know for sure your file name has one).</p>
20,953
<p>I have a Delphi DLL with a function defined as:</p> <p>function SubmitJobStringList(joblist: tStringList; var jobno: Integer): Integer;</p> <p>I am calling this from C#. How do I declare the first parameter as a tStringList does not exist in C#. I currently have the declaration as:</p> <pre><code>[DllImport("opt7bja.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] public static extern int SubmitJobStringList(string[] tStringList, ref int jobno); </code></pre> <p>But when I call it I get a memory access violation exception.</p> <p>Anyone know how to pass to a tStringList correctly from C#?</p>
<p>You'll most likely not have any luck with this. The TStringList is more than just an array, it's a full-blown class, and the exact implementation details may differ from what is possible with .NET. Take a look at the Delphi VCL source code (that is, if you have it) and try to find out if you can rebuild the class in C#, and pass it with the help of your best friend, the Interop Marshaller. Note that even the Delphi string type is different from the .NET string type, and passing it without telling the marshaller what he should do, he will pass it as a char-array, most likely.</p> <p>Other than that, I would suggest changing the Delphi DLL. It's never a good thing to expose anything Delphi-specific in a DLL that is to be used by non-Delphi clients. Make the parameter an array of PChar and you should be fine.</p>
<p>I am not exactly clear your way of using delphi and C#. It seems you have created a Win32 DLL which you want to call from C#. Offcourse you must be using PInvoke for this.</p> <p>I would suggest that you create a .NET DLL using your source code since complete porting of VCL is available. I can further elaborate if you wish....</p>
18,368
<p>I need a code documentation tool similar to javadoc or c# xml doc for delphi code. What is the best tool? I prefer a technology, which is in the future compatible to the Microsoft sandcastle project.</p>
<p>Take a look at <a href="http://synopse.info/fossil/wiki?name=SynProject" rel="nofollow noreferrer">SynProject</a>, an Open Source tool written in Delphi.</p> <p>It was designed to handle a full documentation workflow, from specifications to release notes, including tests, architecture and design; and of course there is an integrated Delphi parser to generate architecture documentation from existing Delphi source code.</p> <p>For the architecture document, the source code can extract comments (ala PasDoc) then embed this text into the main Architecture document (with class hierarchy diagrams and unit dependencies).</p> <p>You write a plain text file using a wiki-like syntax in a dedicated text editor, then SynProject creates well formated Word documents from it. Some Wizards are available to access the content. But since it's stored as plain file, multiple programmers can write on it, using any SCM tool (SVN, Fossil...).</p> <p>For instance, I currently use it for writing maintenance documentation for a huge and old Delphi application (about 2,000,000 lines of code written in Delphi 5 and 6), with no prior available documentation. You describe the changes made to the code (by quoting the unit/class/method), then the tool will update all documentations to reflect and trace those modifications. SynProject was designed to be compliant with some very "delicate" regulation rules (IEC 62304), but can be used for any project due to its unique "flat" design.</p> <p><em>Note</em>: I'm posting this a long time after the question, because SynProject was not existing at this time, and can be worth looking at. This thread <a href="https://stackoverflow.com/questions/4937229">has been defined as a reference for that question</a>.</p>
<p>Sandcastle needs to get access to the assemblies in order to generate it's documentation, which means that it is only applicable for .net languages (although I'm not sure able Delphi.Net). However, Delphi 2007 and 2009 has an inline XML documentation very similar to C#. When you switch on the 'generate XML documentation' option in the project options, it will build XML documentation based on these comments. XSLT can then be used to generate whatever documentation format you need (this is the difficult bit).</p>
29,210
<p>This is in reference to the <a href="https://stackoverflow.com/questions/282944/jquery-one-slider-controls-another">question</a> previously asked</p> <p>The problem here is, each <code>slider</code> controls the other. It results in feedback. </p> <p>How do I possibly stop it?</p> <pre><code>$(function() { $("#slider").slider({ slide: moveSlider2 }); $("#slider1").slider({ slide: moveSlider1 }); function moveSlider2( e, ui ) { $('#slider1').slider( 'moveTo', Math.round(ui.value) ); } function moveSlider1( e, ui ) { $('#slider').slider( 'moveTo', Math.round(ui.value) ); } }); </code></pre>
<p>This is sort of a hack, but works:</p> <pre><code>$(function () { var slider = $("#slider"); var slider1 = $("#slider1"); var sliderHandle = $("#slider").find('.ui-slider-handle'); var slider1Handle = $("#slider1").find('.ui-slider-handle'); slider.slider({ slide: moveSlider1 }); slider1.slider({ slide: moveSlider }); function moveSlider( e, ui ) { sliderHandle.css('left', slider1Handle.css('left')); } function moveSlider1( e, ui ) { slider1Handle.css('left', sliderHandle.css('left')); } }); </code></pre> <p>Basically, you avoid the feedback by manipulating the css directly, not firing the slide event.</p>
<p>You could just give an optional parameter to your <code>moveSlider1</code> and <code>moveSlider2</code> functions that, when set to a true value, suppresses the recursion.</p>
37,492
<p>Is there any way to create a virtual drive in "(My) Computer" and manipulate it, somewhat like JungleDisk does it?</p> <p>It probably does something like:</p> <pre><code>override OnRead(object sender, Event e) { ShowFilesFromAmazon(); } </code></pre> <p>Are there any API:s for this? Maybe to write to an XML-file or a database, instead of a real drive.</p> <hr> <p>The <a href="http://dokan-dev.net/en/" rel="noreferrer">Dokan Library</a> seems to be the answer that mostly corresponds with my question, even though <a href="http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.aspx" rel="noreferrer">System.IO.IsolatedStorage</a> seems to be the most standardized and most Microsoft-environment adapted.</p>
<p>You can use the <a href="https://dokan-dev.github.io/" rel="nofollow noreferrer">Dokan library</a> to create a virtual drive. There is a .Net wrapper for interfacing with C#.</p>
<p>Yes, use the classes in <a href="http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.aspx" rel="nofollow noreferrer">System.IO.IsolatedStorage</a></p>
8,104
<p>So I have a large 2d array that i serialize, but when I attempt to unserialize the array it just throws the same error to the point of nearly crashing Firefox.</p> <p>The error is:</p> <pre><code>Warning: unserialize() [function.unserialize]: Node no longer exists in /var/www/dev/wc_paul/inc/analyzerTester.php on line 24 </code></pre> <p>I would include the entire serialized array that I echo out but last time I tried that on this form it crashed my Firefox.</p> <p>Does anyone have any idea why this might be happening?</p> <p>I'm sure this is an array. However, it was originally an XML response from another server that I then pulled values from to build the array. If it can't be serialized I can accept that I guess... but how should I go about saving it then?</p>
<p>Usually, when you get an error message, you can figure out a great deal by simply searching the web for that very message. For example, when you put <a href="http://www.google.co.uk/search?q=Node+no+longer+exists" rel="nofollow noreferrer">Node no longer exists</a> into Google, you end up with <a href="http://www.rhinocerus.net/node/16347" rel="nofollow noreferrer">a concise explanation of why this is happening, along with a solution</a>, as the very first hit.</p>
<p>to answer your second question about how else you could save the data</p> <p>why not output the xml responce directly to a file and save it locally, then read from the local file when required.</p>
14,860
<p>I am trying to join together several audio files into one mp4/m4a file containing chapter metadata.</p> <p>I am currently using QTKit to do this but unfortunately when QTKit exports to m4a format the metadata is all stripped out (this has been confirmed as a bug by Apple) see <a href="http://files.shinydevelopment.com/audiojoiner.zip" rel="nofollow noreferrer">sample code</a>. I think this rules QTKit out for this job, but would be happy to be proven wrong as it is a really neat API for it if it worked.</p> <p>So, I am looking for a way to concatenate audio files (input format does not really matter as I can do conversion) into an m4a file with chapters metadata.</p> <p>As an alternative to code, I am open to the idea of using an existing command line tool to accomplish this as long as it is redistributable as part of another application.</p> <p>Any ideas?</p>
<p><a href="http://audiobookmaker.sourceforge.net/" rel="nofollow noreferrer">Audiobook Maker</a> does something like this, and I believe it uses ffmpeg under the hood. It's open source, so maybe its worth a look?</p>
<p>Depending on where the bug is, you could try going straight to the QuickTime C APIs to write the movie file. You might also try adding the chapters track using the C APIs. </p> <p>Any word on when Apple will fix the bug? I am planning to create enhanced podcasts with QTKit, and need this to work. </p>
7,724
<p>I've been working on this for a few days now, and I've found several solutions but none of them incredibly simple or lightweight. The problem is basically this: We have a cluster of 10 machines, each of which is running the same software on a multithreaded ESB platform. I can deal with concurrency issues between threads on the same machine fairly easily, but what about concurrency on the same data on different machines? </p> <p>Essentially the software receives requests to feed a customer's data from one business to another via web services. However, the customer may or may not exist yet on the other system. If it does not, we create it via a web service method. So it requires a sort of test-and-set, but I need a semaphore of some sort to lock out the other machines from causing race conditions. I've had situations before where a remote customer was created twice for a single local customer, which isn't really desirable.</p> <p>Solutions I've toyed with conceptually are:</p> <ol> <li><p>Using our fault-tolerant shared file system to create "lock" files which will be checked for by each machine depending on the customer</p></li> <li><p>Using a special table in our database, and locking the whole table in order to do a "test-and-set" for a lock record.</p></li> <li><p>Using Terracotta, an open source server software which assists in scaling, but uses a hub-and-spoke model.</p></li> <li><p>Using EHCache for synchronous replication of my in-memory "locks."</p></li> </ol> <p>I can't imagine that I'm the only person who's ever had this kind of problem. How did you solve it? Did you cook something up in-house or do you have a favorite 3rd-party product?</p>
<p>you might want to consider using <a href="http://www.hazelcast.com" rel="noreferrer">Hazelcast</a> distributed locks. Super lite and easy.</p> <pre><code>java.util.concurrent.locks.Lock lock = Hazelcast.getLock ("mymonitor"); lock.lock (); try { // do your stuff }finally { lock.unlock(); } </code></pre> <p>Hazelcast - Distributed Queue, Map, Set, List, Lock</p>
<p>Back in the day, we'd use a specific "lock server" on the network to handle this. Bleh.</p> <p>Your database server might have resources specifically for doing this kind of thing. MS-SQL Server has application locks usable through the <em>sp_getapplock</em>/<em>sp_releaseapplock</em> procedures.</p>
11,786
<p>This seems like it should be simple but after a couple hours of googling I have not figured it out. I know I can add iCal links using ICS files, but this does not work on the iPhone.</p> <p>BTW, when I say iPhone I would like it to work on the touch also. Anyone have any luck with this?</p>
<p>You can get iPhone to download the .ics file (using Safari on a mobile web page) by using the webcal protocol:</p> <p>webcal://website.mobi/mymeeting.ics</p>
<p>Of course it is possible but only if your JavaScript application is installed on the device. Look at <a href="http://tetontech.wordpress.com" rel="nofollow noreferrer">http://tetontech.wordpress.com</a> to see how to make calls from JavaScript to Objective-C. You can then use this and the Calendar Store Programming Guide from the documentation in Xcode to do what you want.</p>
20,338
<p>In my <a href="http://www.codeplex.com/MEF" rel="nofollow noreferrer">MEF</a> usage, I have a bunch of imports that I want to make available in many other parts of my code. Something like:</p> <pre><code>[Export (typeof (IBarProvider))] class MyBarFactory : IBarPovider { [Import] public IFoo1Service IFoo1Service { get; set; } [Import] public IFoo2Service IFoo2Service { get; set; } [Import] public IFoo3Service IFoo3Service { get; set; } [Import] public IFoo4Service IFoo4Service { get; set; } [Import] public IFoo5Service IFoo5Service { get; set; } public IBar CreateBar() { return new BarImplementation(/* want to pass the imported services here */); } } class BarImplementation : IBar { readonly zib zib; public BarImplementation(/* ... */) { this.zib = new Zib(/* pass services here, too */); } } </code></pre> <p>I could pass each imported service as an individual parameter, but it's a lot of boring code. There's gotta be something better. Any ideas?</p>
<p>I'm not entirely sure this answers your question but have you considered using the constructor injection yet?</p> <pre><code>class BarImplementation : IBar { [ImportingConstructor] public BarImplementation(IFoo1Service foo1, IFoo2Service foo2, ...) { } } </code></pre> <p>By marking your constructor with the ImportingConstructor attribute it will essentially make all the parameters of that constructor required imports.</p>
<p>I thought about making an interface to provide these services:</p> <pre><code>partial class BarImplementation { public IRequiredServices { public IFoo1Service IFoo1Service { get; set; } public IFoo2Service IFoo2Service { get; set; } public IFoo3Service IFoo3Service { get; set; } public IFoo4Service IFoo4Service { get; set; } public IFoo5Service IFoo5Service { get; set; } } } </code></pre> <p>Then <code>MyBarFactory</code> implements <code>BarImplementation : BarImplementation.IRequiredServices</code>. That's easy to write, but then, how do I pass them down to <code>Zib</code>? I don't want to couple <code>Zib</code> to its consumer that way.</p>
24,215
<p>How do I export all of the names and email addresses from a distribution list in Outlook using code? I have access to an Outlook 2000 or Outlook 2007 client. Ideally I would like the code to be in C#.</p>
<p>I realize you asked about c#, but the following script from <a href="http://www.microsoft.com/technet/scriptcenter/resources/officetips/may05/tips0524.mspx" rel="nofollow noreferrer">http://www.microsoft.com/technet/scriptcenter/resources/officetips/may05/tips0524.mspx</a> may be of some use.</p> <pre><code>Const olFolderContacts = 10 Set objOutlook = CreateObject("Outlook.Application") Set objNamespace = objOutlook.GetNamespace("MAPI") Set colContacts = objNamespace.GetDefaultFolder(olFolderContacts).Items intCount = colContacts.Count For i = 1 To intCount If TypeName(colContacts.Item(i)) = "DistListItem" Then Set objDistList = colContacts.Item(i) Wscript.Echo objDistList.DLName For j = 1 To objDistList.MemberCount Wscript.Echo objDistList.GetMember(j).Name &amp; " -- " &amp; _ objDistList.GetMember(j).Address Next Wscript.Echo End If Next </code></pre>
<p>use outlook component model <a href="http://www.dotnetjunkies.ddj.com/Tutorial/2E1EEEAF-C78A-4A38-A830-AC204B12DF83.dcik" rel="nofollow noreferrer">http://www.dotnetjunkies.ddj.com/Tutorial/2E1EEEAF-C78A-4A38-A830-AC204B12DF83.dcik</a></p>
38,276
<p>I need to create a code editor for my own simple language:</p> <p>className.MethodName(parameterName = 2, ... )</p> <p>I've created the appropriate grammar and autogenerate parser using ANTLR tool. Now I would like to have an autocomplete for class, method, variables and parameter names. This list should be context dependent, f.e. for "class." it should display methods and for "class.Method(" - parameters. I was going to parse the text and display the list depending on in which node the cursor is. The problem is that for incomplete code like "aaa.bbb(" the parser produces an error instead of a syntax tree. Any idea how to solve this problem? Maybe I'm on the wrong way and I shouldn't parse code to display autocomplete?</p>
<p>You need to parse at least some parts of the code to know what to display.</p> <p>You either need a parser that allows parsing until it finds an error and continues from there later (or even just ignore it and tries to fix it itself to be able to continue parsing — but it gets very difficult here, so you can access the last node and use your grammar and the existing syntax tree to autocomplete it, or you cache the latest syntax tree and use something like regex to see when to autocomplete and use the cache to see what to autocomplete.</p> <p>The later suggestion might be the easier one but has the disadvantage that the cache might be out-to-date at the time you need the completion (i.e.: you might create a new class in a file, all completions based on that class won’t be available until the file has no errors).</p> <p>Sidenode: Seeing that you do parsing, you might be interested in <a href="http://en.wikipedia.org/wiki/Parsing_expression_grammar" rel="nofollow noreferrer">Parsing Expression Grammars</a>, they don’t exactly help you with that problem, though.</p>
<p>how about TextMate on the Mac or its clones on other platforms? I've just started with it, but it seems to have a very open plugin toolset.</p>
40,527
<p>I am using slideDown animation to show some divs in a newly added table row:</p> <pre><code>$("div", newRow).slideDown(10000, UpdateHours(response.d.Hours)); </code></pre> <p>however the UpdateHours() function is called long before the divs are finished animating. This is causing me a problem because the Updated Hours then get covered by the sliding divs.</p> <p>I made the slide very slow to illustrate the issue better.</p>
<p>I think it's trying to pass the result of the call UpdateHours(response.d.Hours) as the callback function, which would explain why it is being called so soon. One solution would be to create an anonymous function that calls UpdateHours.</p> <pre><code>$("div", newRow).slideDown(10000, function () { UpdateHours(response.d.Hours) }); </code></pre> <p>There is a demo for calling slideDown this way on the jQuery site. <a href="http://docs.jquery.com/Effects/slideDown" rel="noreferrer">http://docs.jquery.com/Effects/slideDown</a></p>
<p>I think you want this:</p> <p><code>$("div", newRow).slideDown(10000, function() { UpdateHours(response.d.Hours); });</code></p> <p>This creates an anonymous function that will be called as a callback - what you're doing is setting the callback to be the return value of <code>UpdateHours</code></p>
43,442
<p>I bet I've got elementary question, but I couldn't solve it for two nights. I've got 1 "ul" element and I just want it to move any amount of pixels every e.g. 2 sec to the left. I want him to move like this step by step and then come back to the original position and start moving again. I've been stucked, my script only moves it to the final position and finish. </p> <pre><code>window.onload = function moveUl(){ var eUl = document.getElementById('change'); var eLi = eUl.getElementsByTagName('li'); x = -300; function move(){ for(i=0;i&lt; eLi.length;i++){ eUl.style.marginLeft = i*x+'px'; } } setInterval(move,1000); } </code></pre> <p>This is the simpliest I can think of. I know this script executes whole loop after 1 sec, but I try to do something like this : Move this element to the left, wait, move more to left and so on. </p>
<p>Do you mean something like this?</p> <pre><code>window.onload = function moveUl() { var eUl = document.getElementById('change'); var eLi = eUl.getElementsByTagName('li'); var delta = 0; function move() { for(i=0;i&lt; eLi.length;i++) eUl.style.marginLeft = (-300*i+delta)+'px'; delta -= 100; // Prepares for the next step if ( delta == -1000 ) delta = 0; // Resets after 10 steps } setInterval(move,1000); } </code></pre>
<p>Is the problem you can't go back from where you started?</p> <p>Why not just add a new for loop in move</p> <pre><code> for(i=eLi.length; i&gt;0 ;i--){ eUl.style.marginLeft = i*x+'px'; } </code></pre> <p>Do you also want it to loop for ever ie start -> left -> start -> left and again?</p>
48,797
<p>One I am aware of is <a href="http://search.cpan.org/dist/Perl-Critic/" rel="nofollow noreferrer">Perl::Critic</a></p> <p>And my googling has resulted in no results on multiple attempts so far. :-(</p> <p>Does anyone have any recommendations here?</p> <p>Any resources to configure Perl::Critic as per our coding standards and run it on code base would be appreciated.</p>
<p>In terms of setting up a profile, have you tried <code>perlcritic --profile-proto</code>? This will emit to stdout all of your installed policies with all their options with descriptions of both, including their default values, in perlcriticrc format. Save and edit to match what you want. Whenever you upgrade Perl::Critic, you may want to run this command again and do a diff with your current perlcriticrc so you can see any changes to existing policies and pick up any new ones.</p> <p>In terms of running perlcritic regularly, set up a <a href="http://search.cpan.org/dist/Test-Perl-Critic/" rel="noreferrer">Test::Perl::Critic</a> test along with the rest of your tests. This is good for new code.</p> <p>For your existing code, use <a href="http://search.cpan.org/dist/Test-Perl-Critic-Progressive/" rel="noreferrer">Test::Perl::Critic::Progressive</a> instead. T::P::C::Progressive will succeed the first time you run it, but will save counts on the number of violations; thereafter, T::P::C::Progressive will complain if any of the counts go up. One thing to look out for is when you revert changes in your source control system. (You are using one, aren't you?) Say I check in a change and run tests and my changes reduce the number of P::C violations. Later, it turns out my change was bad, so I revert to the old code. The T::P::C::Progressive test will fail due to the reduced counts. The easiest thing to do at this point is to just delete the history file (default location t/.perlcritic-history) and run again. It should reproduce your old counts and you can write new stuff to bring them down again.</p> <p>Perl::Critic has a lot of policies that ship with it, but there are a bunch of add-on distributions of policies. Have a look at <a href="http://search.cpan.org/dist/Task-Perl-Critic/" rel="noreferrer">Task::Perl::Critic</a> and <a href="http://search.cpan.org/dist/Task-Perl-Critic-IncludingOptionalDependencies/" rel="noreferrer"> Task::Perl::Critic::IncludingOptionalDependencies</a>.</p> <p>You don't need to have a single perlcriticrc handle all your code. Create separate perlcriticrc files for each set of files you want to test and then a separate test that points to each one. For an example, have a look at the author tests for P::C itself at <a href="http://perlcritic.tigris.org/source/browse/perlcritic/trunk/Perl-Critic/xt/author/" rel="noreferrer">http://perlcritic.tigris.org/source/browse/perlcritic/trunk/Perl-Critic/xt/author/</a>. When author tests are run, there's a test that runs over all the code of P::C, a second test that applies additional rules just on the policies, and a third one that criticizes P::C's tests.</p> <p>I personally think that everyone should run at the "brutal" severity level, but knock out the policies that they don't agree with. Perl::Critic isn't entirely self compliant; even the P::C developers don't agree with everything Conway says. Look at the perlcriticrc files used on Perl::Critic itself and search the Perl::Critic code for instances of "## no critic"; I count 143 at present.</p> <p>(Yes, I'm one of the Perl::Critic developers.)</p>
<p>In addition to the cosmetic best practices, I always find it useful to run Devel::Prof on my unit test suite to check test coverage.</p>
7,456
<p>Hi I want to create form on my site, which is run using Micrsoft Sharepoint. </p>
<p>there are multiple ways to create/use forms in SharePoint. You can do this by </p> <ul> <li>implementing a web part</li> <li>designing/implementing an aspx page</li> <li>using InfoPath </li> </ul> <p>To decide which option is the right one for you depends on the problem you want so solve or the goal you want do archive. Perhaps some more details would be helpful. </p>
<p>there are multiple ways to create/use forms in SharePoint. You can do this by </p> <ul> <li>implementing a web part</li> <li>designing/implementing an aspx page</li> <li>using InfoPath </li> </ul> <p>To decide which option is the right one for you depends on the problem you want so solve or the goal you want do archive. Perhaps some more details would be helpful. </p>
35,471
<p>I am trying to validate the WPF form against an object. The validation fires when I type something in the textbox lose focus come back to the textbox and then erase whatever I have written. But if I just load the WPF application and tab off the textbox without writing and erasing anything from the textbox, then it is not fired. </p> <p>Here is the Customer.cs class: </p> <pre><code>public class Customer : IDataErrorInfo { public string FirstName { get; set; } public string LastName { get; set; } public string Error { get { throw new NotImplementedException(); } } public string this[string columnName] { get { string result = null; if (columnName.Equals("FirstName")) { if (String.IsNullOrEmpty(FirstName)) { result = "FirstName cannot be null or empty"; } } else if (columnName.Equals("LastName")) { if (String.IsNullOrEmpty(LastName)) { result = "LastName cannot be null or empty"; } } return result; } } } </code></pre> <p>And here is the WPF code: </p> <pre><code>&lt;TextBlock Grid.Row="1" Margin="10" Grid.Column="0"&gt;LastName&lt;/TextBlock&gt; &lt;TextBox Style="{StaticResource textBoxStyle}" Name="txtLastName" Margin="10" VerticalAlignment="Top" Grid.Row="1" Grid.Column="1"&gt; &lt;Binding Source="{StaticResource CustomerKey}" Path="LastName" ValidatesOnExceptions="True" ValidatesOnDataErrors="True" UpdateSourceTrigger="LostFocus"/&gt; &lt;/TextBox&gt; </code></pre>
<p>If you're not adverse to putting a bit of logic in your code behind, you can handle the actual <em>LostFocus</em> event with something like this:</p> <p><strong>.xaml</strong></p> <pre><code>&lt;TextBox LostFocus="TextBox_LostFocus" .... </code></pre> <hr> <p><strong>.xaml.cs</strong></p> <pre><code>private void TextBox_LostFocus(object sender, RoutedEventArgs e) { ((Control)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource(); } </code></pre>
<p>I've gone through the same problem and found an ultra simple way to resolve this : in the Loaded event of your window, simply put txtLastName.Text = String.Empty. That's it!! Since the property of your object has changed (been set to an empty string), the validation's firing !</p>
12,921
<p>UDP doesnot sends any ack back, but will it send any response?</p> <p>I have set up client server UDP program. If I give client to send data to non existent server then will client receive any response?</p> <p>My assumption is as;</p> <p>Client -->Broadcast server address (ARP) Server --> Reply to client with its mac address(ARP) Client sends data to server (UDP)</p> <p>In any case Client will only receive ARP response. If server exists or not it will not get any UDP response? </p> <p>Client is using sendto function to send data. We can get error information after sendto call.</p> <p>So my question is how this info is available when client doesn't get any response. Error code can be get from WSAGetLastError.</p> <p>I tried to send data to non existent host and sendto call succeeded . As per documentation it should fail with return value SOCKET_ERROR.</p> <p>Any thoughts??</p>
<p>You can never receive an error, or notice for a UDP packet that did not reach destination.</p>
<p>If you need reliable UDP as in ordering or verification such that TCP/IP will give you take a look at RUDP or Reliable UDP. Sometimes you do need verification but a mixture of UDP and TCP can be held up on the TCP reliability causing a bottleneck.</p> <p>For most large scale MMO's for isntance UDP and Reliablity UDP are the means of communication and reliability. All RUDP does is add a smaller portion of TCP/IP to validate and order certain messages but not all.</p> <p>A common game development networking library is Raknet which has this built in.</p> <p>RUDP <a href="http://www.javvin.com/protocolRUDP.html" rel="nofollow noreferrer">http://www.javvin.com/protocolRUDP.html</a></p> <p>An example of RUDP using Raknet and Python <a href="http://pyraknet.slowchop.com/" rel="nofollow noreferrer">http://pyraknet.slowchop.com/</a></p>
43,247
<p>Recently I used a class that inherits from a collection instead of having the collection instantiated within the class, is this acceptable or does it create unseen problems further down the road? Examples below for the sake of clarity:</p> <pre><code>public class Cars : List&lt;aCar&gt; </code></pre> <p>instead of something like:</p> <pre><code>public class Cars { List&lt;aCar&gt; CarList = new List&lt;aCar&gt;(); } </code></pre> <p>Any thoughts?</p>
<p>The problem with this is that your Cars class will still have the interface it inherits from List, which may allow operations you don't want.</p>
<p>Is the "Cars" class really required? Has some added functionality than "List" ? If not, you should use "List" ( or better "IList" ).</p> <p>If class "Cars" has any added functionality, there is two main scenarios:</p> <ul> <li>This class is "final" class, there is no big possibility, the someone others need extended it. Then is this construction OK.</li> <li>This class will be probably used as base class. Then I recommend use this construction:</li> </ul> <p>.</p> <pre><code>public class CarList&lt;T&gt; : List&lt;T&gt; where T : Car { // some added functionality } </code></pre> <p>If you want be more flexible in future, you should use a composition:</p> <pre><code>public class CarList&lt;T&gt; : IList&lt;T&gt; where T : Car { private IList&lt;T&gt; innerList; public CarList() { this.innerList = new List&lt;T&gt;(); } // implementation of IList&lt;T&gt; // some added functionality } </code></pre>
45,535
<p>I've got a C# program with values in a config file. What I want is to store ampersands for an url value like...</p> <pre><code>&lt;appSettings&gt; &lt;add key="myurl" value="http://www.myurl.com?&amp;cid=&amp;sid="/&gt; &lt;/appSettings&gt; </code></pre> <p>But I get errors building my site. The ampersand is not allowed. I've tried various forms of escaping the ampersands to no avail. Anyone know of the correct form to do this? All suggestions are welcome.</p>
<p>Use "<code>&amp;amp;</code>" instead of "&amp;".</p>
<p>I think you should be able to use the HTML escape character (&amp;). They can be found at <a href="http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php" rel="nofollow noreferrer">http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php</a></p>
49,228
<p>My WCF Service uses wsHttpBinding and works fine from the client when the service is gerenated by the client using the default options as follows:</p> <pre><code>RServiceClient R = new RServiceClient(); </code></pre> <p>However, at some point I'll need to be able to specify the location of the service, presumably by changing the endpoint address as follows:</p> <pre><code>RServiceClient R = new RServiceClient(); R.Endpoint.Address = new EndpointAddress(new Uri "http://xxx.xxxx.xxx:80/RServer/RService.svc")); </code></pre> <p>However, when I do specify the exact endpoint, I get a SecurityNegotiationException: System.ServiceModel.Security.SecurityNegotiationException was unhandled Message="The caller was not authenticated by the service." Source="mscorlib"....</p> <p>The WCF service runs on IIS and has anonymous access enabled under IIS admin. Also, this error occurs when the client is run from the same machine as the service under an admin account - I havn't got to the scary part of running it over the net yet!</p> <p>Any Ideas?</p>
<p>By default, wsHttpBinding uses Windows authentication. I'm not sure how hosting in IIS affects that scenario. </p> <p>If you don't want security turned on, you can add an element for security and set the mode element to "None" to the config on both ends to turn off the default setting.</p> <p>I think this may do the trick -- I've added the section for wsHttpBinding and set the bindingConfiguration of your service to point to the newly added binding properties:</p> <pre><code>&lt;system.serviceModel&gt; &lt;bindings&gt; &lt;wsHttpBinding&gt; &lt;binding name="wsHttpBind"&gt; &lt;security mode="None"&gt; &lt;transport clientCredentialType="None" protectionLevel="EncryptAndSign" /&gt; &lt;message clientCredentialType="None" algorithmSuite="Default" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/wsHttpBinding&gt; &lt;/bindings&gt; &lt;services&gt; &lt;service behaviorConfiguration="ServiceBehavior" name="RService"&gt; &lt;endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpBind" name="RService" contract="IRService"&gt; &lt;identity&gt; &lt;dns value="localhost" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; &lt;endpoint address="mex" binding="mexHttpBinding" name="MetadataExchange" contract="IMetadataExchange" /&gt; &lt;/service&gt; &lt;/services&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="ServiceBehavior"&gt; &lt;!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --&gt; &lt;serviceMetadata httpGetEnabled="true"/&gt; &lt;!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --&gt; &lt;serviceDebug includeExceptionDetailInFaults="true"/&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;/system.serviceModel&gt; </code></pre>
<p>Are you using MessageSecurity with certificates? this could be a certificate issue (wrong hostname, self-signed certificate not installed, etc..)</p>
30,615
<p>I'm getting this worthless error in my code. it's very consistant and restarting the compiler hasn't done anything. Has anyone else ever solved this? </p> <pre><code>while( int CharPos = _Message.Pos(_What) ) { _Message.Insert( _With, CharPos); _Message.Delete(CharPos + 1, 1); } </code></pre>
<p>Well... apparently the compiler breaks when you try to declare an int in the while loop's condition.</p>
<p>This is expected to be addressed in the soon to be released Update 3 for RAD Studio 2009.</p>
43,902
<p>Here's a quicky question. Which method name makes the most sense for an Objective-C Cocoa application?</p> <pre><code>-(void) doSomethingWithAnimation:(BOOL)animated </code></pre> <p>or:</p> <pre><code>-(void) doSomething:(BOOL)animated </code></pre> <p>or even:</p> <pre><code>-(void) doSomethingAnimated:(BOOL)animated </code></pre>
<p>I think the Cocoa convention would give your examples the following semmantics (ignoring the BOOL type for the argument, obviously):</p> <pre><code>-(void) doSomethingWithAnimation:(BOOL)animated </code></pre> <p>would actually expect an Animation as the parameter (i.e. something that represents the animation.</p> <pre><code>-(void) doSomething:(BOOL)animated </code></pre> <p>would expect the Something to do.</p> <pre><code>-(void) doSomethingAnimated:(BOOL)animated </code></pre> <p>would, as Noah answered, do something with optional animation.</p>
<p>Here's another option to consider: make two methods, <code>-doSomething</code> and <code>-doSomethingWithAnimation</code>.</p> <p>Then, if you want, you can have them both tail-call a third, private method, and give that method any name you want. :)</p>
29,077
<p>I have an xPC target application that talks to a device over RS-232. I am using the xPC serial block for this.<br> To talk to this device I first have to start at a default speed, say, 9600 bps, request a change of speed to, say 57600 bps, then change the speed on my side to match it.<br> The problem with the xPC block is that it forces you to choose a specific speed before running, and can't change it at run time. Is there a way/trick/hack to do this?</p>
<p>Here is my take so far. I don't think it can be done using existing Simulink blocks. I think I am going to have to take the xpcserial C code that comes with Matlab, take the code that sets the RS-232 speed, and wrap it in my own S-function.</p>
<p>Ian,</p> <p>What I've done before on this stuff is just modify the registers behind XPC target's back. It's ugly, but xPCTarget is ugly in the first place. </p> <p>Try modify Line Control Register and set the divisors directly -- all you need is the serial port IO address, and you know that.</p> <p>It's worth a shot anyway, you're going to have to do it anyway.</p>
6,480
<p>I have a c# asp.net web app. Breakpoints in the database layer are no longer stopping execution but the breakpoints in the UI layer are still working okay. Can anyone hazard a guess why this might be happening?</p> <p>I've checked all the usual suspects (Debug build is on for all projects) and recompiled all projects in solution...</p>
<p>I would ensure that the UI layer is referencing the appropriate 'debug' .dll's. I'd also consider pressing <kbd>CTRL</kbd>+<kbd>ALT</kbd>+<kbd>U</kbd> (<code>Modules View</code>) when you're debugging to see if symbols are loaded for your BLL and DAL <code>.dlls</code>. If not then Visual Studio is unable to find <code>.PDBs</code> for that file.<br> Are debug files <code>.PDBs</code> in the same directory as the <code>.dlls</code> that are being referenced from the Modules window?</p>
<p>Have you tried deleting your bin directories before recompiling?</p>
8,489
<p>I have the feeling that is easy to find samples, tutorials and simple examples on Flex.<br> It seems harder to find tips and good practices based on real-life projects.<br> Any tips on how to :</p> <ul> <li>How to write maintainable actionscript code</li> <li>How to ensure a clean separation of concern. Has anybody used an MVC framework such as cairngorm, puremvc or easymvc on a real Flex project ?</li> <li>How to fetch data from a server with blazeds/amfphp ?</li> <li>How to reduce latency for the end-user ?</li> <li>...</li> </ul>
<p>I work often with Flex in my job, and I will be happy to help.. but your questions deserve an article for each one :) I'll try some short answer.</p> <p>Maintenable code: I think that the same rules of any other OO languages apply. Some flex-specific rules I'm use to follow: use strong typed variables, always consider dispatching events as the way for your UI components talk each other (a little more initial work, very flexible and decoupled later).</p> <p>Frameworks: looked at it, read the documentation.. very nice, but I still feel that their complications are not balanced by the benefits they provide. Anyway I'd like to change my mind on this point..</p> <p>Talking with server: Right now I'm using BlazeDS, it works very well.. there are many tutorials on the subject out there, if you find any trouble setting up it I would be happy to help.</p> <p>Latency: Do you mean in client/server comunications? If so, you should explore the various type of channels BlazeDS implements.. pull-only, two-way http polling, near real-time on http (comet).. if you need more, LiveCycle Data Services ES, the commrcial implementation from which BlazeDS is born, among other things offer another protocol called RTMP, it isn't http-tunnelled so there can be problem with firewalls and proxies, but it offers better performance (there is a free closed-source version of LCDS). I use the standard http channels in intranet environments, and found no real performance problems even with large datasets.</p> <p>Well.. quite a lot of stuff, can't be more specific now on each of this points, ask you if need :)</p>
<p>I have found the MVC framework RIAWave <a href="http://ria.richtechmedia.com/go.php?http://ria.richtechmedia.com/flexsample/sample.rar" rel="nofollow noreferrer">link</a> to be absolutely incredible. It is super lightweight and easy to use. I found Cairngorm and PureMVC to have a pretty steep learning curve and they both feel a bit too bulky for me. RIAWave stays out of the way and just gives you the MVC basics to work with.</p> <p>AMFPHP on the backend is very nice as well. AMFPHP also has an apache module that will take care of serializing/unserializing the sent and received data all in C which is blazing fast.</p> <p>If latency is a worry, you will want to make sure you get a good webhost or even deploy to multiple data centers so that your users are never far from a server. Sounds like a bit early to be worrying about that though.</p>
12,159
<p>I previously asked how to do this in Groovy. However, now I'm rewriting my app in Perl because of all the CPAN libraries.</p> <p>If the page contained these links:</p> <pre> &lt;a href="http://www.google.com"&gt;Google&lt;/a&gt; &lt;a href="http://www.apple.com"&gt;Apple&lt;/a&gt; </pre> <p>The output would be:</p> <pre> Google, http://www.google.com Apple, http://www.apple.com </pre> <p>What is the best way to do this in Perl?</p>
<p>Please look at using the <a href="http://search.cpan.org/dist/WWW-Mechanize/" rel="noreferrer">WWW::Mechanize</a> module for this. It will fetch your web pages for you, and then give you easy-to-work with lists of URLs.</p> <pre><code>my $mech = WWW::Mechanize-&gt;new(); $mech-&gt;get( $some_url ); my @links = $mech-&gt;links(); for my $link ( @links ) { printf "%s, %s\n", $link-&gt;text, $link-&gt;url; } </code></pre> <p>Pretty simple, and if you're looking to navigate to other URLs on that page, it's even simpler.</p> <p>Mech is basically a browser in an object.</p>
<p>We can use regular expression to extract the link with its link text. This is also the one way.</p> <pre><code>local $/ = ''; my $a = &lt;DATA&gt;; while( $a =~ m/&lt;a[^&gt;]*?href=\"([^&gt;]*?)\"[^&gt;]*?&gt;\s*([\w\W]*?)\s*&lt;\/a&gt;/igs ) { print "Link:$1 \t Text: $2\n"; } __DATA__ &lt;a href="http://www.google.com"&gt;Google&lt;/a&gt; &lt;a href="http://www.apple.com"&gt;Apple&lt;/a&gt; </code></pre>
31,725
<p>I infrequently (monthly/quarterly) generate hundreds of Crystal Reports reports using Microsoft SQL Server 2005 database views. Are those views wasting CPU cycles and RAM during all the time that I am not reading from them? Should I instead use stored procedures, temporary tables, or short-lived normal tables since I rarely read from my views?</p> <p>I'm not a DBA so I don't know what's going on behind the scenes inside the database server.</p> <p>Is it possible to have too many database views? What's considered best practice?</p>
<p>For the most part, it doesn't matter. Yes, SQL Server will have more choices when it parses SELECT * FROM table (it'll have to look in the system catalogs for 'table') but it's highly optimized for that, and provided you have sufficient RAM (most servers nowadays do), you won't notice a difference between 0 and 1,000 views.</p> <p>However, from a people-perspective, trying to manage and figure out what "hundreds" of views are doing is probably impossible, so you likely have a lot of duplicated code in there. What happens if some business rules change that are embedded in these redundant views?</p> <p>The main point of views is to encapsulate business logic into a pseudo table (so you may have a person table, but then a view called "active_persons" which does some magic). Creating a view for each report is kind of silly unless each report is so isolated and unique that there is no ability to re-use.</p>
<p>The views are only going to take up cpu/memory resources when they are called.</p> <p>Anyhow, best practice would be to consolidate what can be consolidated, remove what can be removed, and if it's literally only used by your reports, choose a consistent naming standard for the views so they can easily be grouped together when looking for a particular view.</p> <p>Also, unless you really need transactional isolation, consider using the NOLOCK table hint in your queries.</p> <p>-- Kevin Fairchild</p>
6,140
<p>I've had a hard time finding good ways of taking a time format and easily determining if it's valid then producing a resulting element that has some formatting using XSLT 1.0.</p> <p>Given the following xml:</p> <pre><code>&lt;root&gt; &lt;srcTime&gt;2300&lt;/srcTime&gt; &lt;/root&gt; </code></pre> <p>It would be great to produce the resulting xml:</p> <pre><code>&lt;root&gt; &lt;dstTime&gt;23:00&lt;/dstTime&gt; &lt;/root&gt; </code></pre> <p>However, if the source xml contains an invalid 24 hour time format, the resulting <em>dstTime</em> element should be blank.</p> <p>For example, when the invalid source xml is the following:</p> <pre><code>&lt;root&gt; &lt;srcTime&gt;NOON&lt;/srcTime&gt; &lt;/root&gt; </code></pre> <p>The resulting xml should be:</p> <pre><code>&lt;root&gt; &lt;dstTime&gt;&lt;/dstTime&gt; &lt;/root&gt; </code></pre> <p>The question is, what's the <strong>best XSLT 1.0</strong> fragment that could be written to produce the desired results? The hope would be to keep it quite simple and not have to parse the every piece of the time (i.e. pattern matching would be sweet if possible).</p>
<p>There aren't any regular expressions in XSLT 1.0, so I'm afraid that pattern matching isn't going to be possible.</p> <p>I'm not clear if <code>&lt;srcTime&gt;23:00&lt;/srcTime&gt;</code> is supposed to be legal or not? If it is, try:</p> <pre><code>&lt;dstTime&gt; &lt;xsl:if test="string-length(srcTime) = 4 or string-length(srcTime) = 5"&gt; &lt;xsl:variable name="hour" select="substring(srcTime, 1, 2)" /&gt; &lt;xsl:if test="$hour &gt;= 0 and 24 &gt; $hour"&gt; &lt;xsl:variable name="minute"&gt; &lt;xsl:choose&gt; &lt;xsl:when test="string-length(srcTime) = 5 and substring(srcTime, 3, 1) = ':'"&gt; &lt;xsl:value-of select="substring(srcTime, 4, 2)" /&gt; &lt;/xsl:when&gt; &lt;xsl:when test="string-length(srcTime) = 4"&gt; &lt;xsl:value-of select="substring(srcTime, 3, 2)" /&gt; &lt;/xsl:when&gt; &lt;/xsl:choose&gt; &lt;/xsl:variable&gt; &lt;xsl:if test="$minute &gt;= 0 and 60 &gt; $minute"&gt; &lt;xsl:value-of select="concat($hour, ':', $minute)" /&gt; &lt;/xsl:if&gt; &lt;/xsl:if&gt; &lt;/xsl:if&gt; &lt;/dstTime&gt; </code></pre> <p>If it isn't, and four digits is the only thing that's legal then:</p> <pre><code>&lt;dstTime&gt; &lt;xsl:if test="string-length(srcTime) = 4"&gt; &lt;xsl:variable name="hour" select="substring(srcTime, 1, 2)" /&gt; &lt;xsl:if test="$hour &gt;= 0 and 24 &gt; $hour"&gt; &lt;xsl:variable name="minute" select="substring(srcTime, 3, 2)" /&gt; &lt;xsl:if test="$minute &gt;= 0 and 60 &gt; $minute"&gt; &lt;xsl:value-of select="concat($hour, ':', $minute)" /&gt; &lt;/xsl:if&gt; &lt;/xsl:if&gt; &lt;/xsl:if&gt; &lt;/dstTime&gt; </code></pre>
<p>Have a look at: <a href="http://www.exslt.org/" rel="nofollow noreferrer">http://www.exslt.org/</a> specifically the "dates and times" section. I haven't dug deep into it but it looks like it may be what your looking for.</p>
17,210
<p>Anyone knows a way to define refactoring in a more formal way?</p> <p>UPDATE.</p> <blockquote> <p>A refactoring is a pair R = (pre; T) where pre is the precondition that the program must satisfy, and T is the program transformation.</p> </blockquote>
<p>It's an interesting question and one I hadn't considered. I did a little googling and came up with this <a href="http://wwwiti.cs.uni-magdeburg.de/iti_db/forschung/ramses/publications/ADI2006.pdf" rel="nofollow noreferrer">paper</a> (PDF) on refactoring in AOP that attempts to apply some mathematical modeling to aspects to show the that functional aspects have the same flexibility as traditional aspects but with reduced complexity. I didn't read the whole paper, but you might find something there.</p> <p>Another interesting idea would be to think of refactorings along the same lines as compiler optimizations. Essentially, the compiler refactors your code on the fly, although with different goals than code-level refactoring. You'd have to somehow quantify code complexity and readability in a reasonable way to demonstrate how a particular refactoring affects it. Coming up with the model would probably be the hard part.</p> <p>I also found this <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.58.2327" rel="nofollow noreferrer">paper</a> that establishes an algebra of OO programming and derives some basic laws, then uses those basic rules to derive a more complicated refactoring.</p> <p>Interesting stuff. Hope this helps.</p>
<p>Well not directly, but in terms of money - I can say Yes. I can't come up with an equation on that :)</p> <p>Code well-written, free of complexity (that could be due to refactoring) can save time/effort and hence money.</p>
38,607
<p>Singletons are a hotly debated design pattern, so I am interested in what the Stack Overflow community thought about them.</p> <p>Please provide reasons for your opinions, not just "Singletons are for lazy programmers!"</p> <p>Here is a fairly good article on the issue, although it is against the use of Singletons: <a href="http://web.archive.org/web/20090303174418/http://scientificninja.com/advice/performant-singletons" rel="nofollow noreferrer">scientificninja.com: performant-singletons</a>.</p> <p>Does anyone have any other good articles on them? Maybe in support of Singletons?</p>
<p>In defense of singletons:</p> <ul> <li><strong>They are not as bad as globals</strong> because globals have no standard-enforced initialization order, and you could easily see nondeterministic bugs due to naive or unexpected dependency orders. Singletons (assuming they're allocated on the heap) are created after all globals, and in a very predictable place in the code.</li> <li><strong>They're very useful for resource-lazy / -caching systems</strong> such as an interface to a slow I/O device. If you intelligently build a singleton interface to a slow device, and no one ever calls it, you won't waste any time. If another piece of code calls it from multiple places, your singleton can optimize caching for both simultaneously, and avoid any double look-ups. You can also easily avoid any deadlock condition on the singleton-controlled resource.</li> </ul> <p>Against singletons:</p> <ul> <li><strong>In C++, there's no nice way to auto-clean-up after singletons.</strong> There are work-arounds, and slightly hacky ways to do it, but there's just no simple, universal way to make sure your singleton's destructor is always called. This isn't so terrible memory-wise -- just think of it as more global variables, for this purpose. But it can be bad if your singleton allocates other resources (e.g. locks some files) and doesn't release them.</li> </ul> <p>My own opinion:</p> <p>I use singletons, but avoid them if there's a reasonable alternative. This has worked well for me so far, and I have found them to be testable, although slightly more work to test.</p>
<p>I really disagree on the <em>bunch of global variables in a fancy dress</em> idea. Singletons are really useful when used to solve the right problem. Let me give you a real example.</p> <p>I once developed a small piece of software to a place I worked, and some forms had to use some info about the company, its employees, services and prices. At its first version, the system kept loading that data from the database every time a form was opened. Of course, I soon realized this approach was not the best one.</p> <p>Then I created a singleton class, named <em>company</em>, which encapsulated everything about the place, and it was completely filled with data by the time the system was opened.</p> <p>It was not just a bunch of variables in a fancy dress because this was had dozens of responsibilities, like communicating with persistence layer to save/retrieve data about the company, deal with employees and prices collections, etc.</p> <p>Plus, it was a fixed, system-wide, easily accessible point to have the company data.</p>
3,295
<p>I have a custom application with a simple app.config specifying SQL Server name and Database, I want to prompt the user on application install for application configuration items and then update the app.config file.</p> <p>I admit I'm totally new to setup projects and am looking for some guidance. Thank You Mark Koops</p>
<p>I had problems with the code Gulzar linked to on a 64 bit machine. I found the link below to be a simple solution to getting values from the config ui into the app.config.</p> <p><a href="http://raquila.com/software/configure-app-config-application-settings-during-msi-install/" rel="noreferrer">http://raquila.com/software/configure-app-config-application-settings-during-msi-install/</a></p>
<p>Create custom dialogs for use in your Visual Studio Setup projects: <a href="http://www.codeproject.com/Articles/18834/Create-custom-dialogs-for-use-in-your-Visual-Studi" rel="nofollow">http://www.codeproject.com/Articles/18834/Create-custom-dialogs-for-use-in-your-Visual-Studi</a></p>
30,969
<p>We need to remotely create an Exchange 2007 distribution list from Asp.Net.</p> <p>Near as I can tell, the only way to create a distribution list in the GAL is via the exchange management tools. Without installing this on our web server, is there any way to create a distribution list remotely? There are some third party components that allow you to create personal distribution lists, but these only live in a users Contacts folder and are not available to all users within the company.</p> <p>Ideally there would be some kind of web services call to exchange or an API we could work with. The Exchange SDK provides the ability to managing Exchange data (e.g. emails, contacts, calendars etc.). There doesn't appear to be an Exchange management API.</p> <p>It looks like the distribution lists are stored in AD as group objects with a special Exchange attributes, but there doesn't seem to be any documentation on how they are supposed to work. </p> <p>Edit: We could reverse engineer what Exchange is doing with AD, but my concern is that with the next service pack of Exchange this will all break. </p> <p>Is there an API that I can use to manage the distribution lists in Active Directory without going through Exchange? </p>
<p>SelectMany - i.e.</p> <pre><code> IEnumerable&lt;List&lt;string&gt;&gt; someList = ...; IEnumerable&lt;string&gt; all = someList.SelectMany(x =&gt; x); </code></pre> <p>For each item in someList, this then uses the lambda "x => x" to get an IEnumerable&lt;T&gt; for the inner items. In this case, each "x" is a List&lt;T&gt;, which is already IEnumerable&lt;T&gt;.</p> <p>These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified):</p> <pre><code>static IEnumerable&lt;TResult&gt; SelectMany&lt;TSource, TResult&gt;( this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, IEnumerable&lt;TResult&gt;&gt; selector) { foreach(TSource item in source) { foreach(TResult result in selector(item)) { yield return result; } } } </code></pre> <p>Although that is simplified somewhat.</p>
<p>Make a simple method. No need for LINQ:</p> <pre><code>IEnumerable&lt;string&gt; GetStrings(IEnumerable&lt;List&lt;string&gt;&gt; lists) { foreach (List&lt;string&gt; list in lists) foreach (string item in list) { yield return item; } } </code></pre>
18,114
<p>I understand how Map is easily parallelizable - each computer/CPU can just operate on a small portion of the array.</p> <p>Is Reduce/foldl parallelizable? It seems like each computation depends on the previous one. Is it just parallelizable for certain types of functions?</p>
<p>If your reduction underlying operation is associative*, you can play with the order of operations and locality. Therefore you often have a tree-like structure in the 'gather' phase, so you can do it in several passes in logarithmic time:</p> <pre><code>a + b + c + d \ / \ / (a+b) (c+d) \ / ((a+b)+(c+d)) </code></pre> <p>instead of (((a+b)+c)+d)</p> <p>If your operation is commutative, further optimization are possible as you can gather in different order (it may be important for data alignment when those operations are vector operations for example)</p> <p>[*] your real desired mathematical operations, not those on effective types like floats of course.</p>
<p>It depends on your Reduce step. In a Hadoop-style implementation of MapReduce, your Reducer is getting called once <em>per key,</em> with all the rows relevant to that key.</p> <p>So, for example, your Mapper might be taking in a lot of unordered web server logs, adding some metadata (e.g., geocoding), and emitting [key, record] pairs with a cookie ID as the key. Your Reducer would then be called once per cookie ID and would be fed all the data for that cookie, and could compute aggregate info such as visit frequency or average pages viewed per visit. Or you could key on geocode data, and gather aggregate stats based on geography.</p> <p>Even if you're not doing per-key aggregate analysis - indeed, even if you're computing something over the whole set - it might be possible to break your computation into chunks, each of which could be fed to a Reducer.</p>
42,683
<p>I would like to keep a list of a certain class of objects in my application. But I still want the object to be garbage collected. Can you create <strong>weak references</strong> in .NET?</p> <p>For reference:</p> <ul> <li><a href="https://stackoverflow.com/questions/346762">Garbage Collecting objects which keep track of their own instances in an internal Map</a></li> <li><a href="https://stackoverflow.com/questions/258505">Create a weak reference to an object</a></li> </ul> <p>Answer From MSDN:</p> <blockquote> <p>To establish a weak reference with an object, you create a WeakReference using the instance of the object to be tracked. You then set the Target property to that object and set the object to null. For a code example, see WeakReference in the class library.</p> </blockquote>
<p>Yes, there's a generic weak reference class.</p> <p><a href="http://msdn.microsoft.com/en-us/library/xt0a1s34.aspx" rel="noreferrer">MSDN > Weak Reference</a></p>
<p>Here is the full (non thread safe) implementation sample of <code>WeakReference</code></p> <pre><code>ClassA objA = new ClassA(); WeakReference wr = new WeakReference(objA); // do stuff GC.Collect(); ClassA objA2; if (wr.IsAlive) objA2 = wr.Target as ClassA; else objA2 = new ClassA(); // create it directly if required </code></pre> <p><code>WeakReference</code> is in the <code>System</code> namespace hence no need to include any special assembly for it.</p>
45,135
<p>I found this guide for using the flash parameters, thought it might be useful to post here, since Flash CS3 lacks a usage example for reading these parameters.</p> <p>See answers for the link</p>
<p>Not sure why <a href="http://blogs.adobe.com/pdehaan/2006/07/using_flashvars_with_actionscr.html" rel="nofollow noreferrer">his example</a> calls LoaderInfo. The <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/DisplayObject.html" rel="nofollow noreferrer">DisplayObject</a> class has its own (readonly) <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/DisplayObject.html#loaderInfo" rel="nofollow noreferrer">loaderinfo</a> property. As long as your main class extends a DisplayObject, you can call the property directly</p> <pre><code>package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var test1:String = ''; if (this.loaderInfo.parameters.test1 !== undefined) { test1 = this.loaderInfo.parameters.test1; } } } } </code></pre> <p>From the doc:</p> <blockquote> <p>Returns a LoaderInfo object containing information about loading the file to which this display object belongs. The loaderInfo property is defined only for the root display object of a SWF file or for a loaded Bitmap (not for a Bitmap that is drawn with ActionScript). To find the loaderInfo object associated with the SWF file that contains a display object named myDisplayObject, use myDisplayObject.root.loaderInfo.</p> </blockquote>
<pre><code>var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters; </code></pre> <p>The entire article is at:</p> <p><a href="http://blogs.adobe.com/pdehaan/2006/07/using_flashvars_with_actionscr.html" rel="nofollow noreferrer">http://blogs.adobe.com/pdehaan/2006/07/using_flashvars_with_actionscr.html</a></p> <p>Important note! This will only work in the main class. If you'll try to load the parameters in a subclass you'll get nothing.</p>
13,433
<p>Are there any good examples (websites or books) around of how to build a full text search engine in F#? </p>
<pre><code> HttpConnectionManagerParams cmparams = new HttpConnectionManagerParams(); cmparams.setSoTimeout(10000); cmparams.setTcpNoDelay(true); HttpConnectionManager manager = new SimpleHttpConnectionManager(); manager.setParams(cmparams); params = new HttpClientParams(); params.setSoTimeout(5000); client = new HttpClient(params, manager); </code></pre> <p>I wonder why I have two different SoTimeouts set. Maybe I was trying to find out which one was actually active, as I had the same problems as you when I used it.</p> <p>The above is in live code at our place right now, but I cannot say whether it works because it's correct, or because providence is smiling down on me (and the other end is usually always available).</p>
<blockquote> <p>cmparams.setSoTimeout(10000);</p> </blockquote> <p>This one is for all HttpClient by default.</p> <blockquote> <p>params.setSoTimeout(5000);</p> </blockquote> <p>And this one is for a particular httpclient.</p>
16,046
<p>I'm trying to determine if any changes were made to a particular entity object. Essentially, I want to know if SubmitChanges() will actually change anything. I would prefer to be able to determine this after SubmitChanges() has been called, but it doesn't really matter.</p> <p>Anyone know how I would do this?</p>
<p>Take a look at the <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.getchangeset.aspx" rel="noreferrer">GetChangeset</a> function on your DataContext.</p>
<p>This is what I came up with:</p> <pre><code>Public Function HasChanges(ByVal obj As Object) As Boolean Dim cs = GetChangeSet() If cs.Updates.Contains(obj) Or cs.Inserts.Contains(obj) Or cs.Deletes.Contains(obj) Then Return True Return False End Function </code></pre>
46,951
<p>I have a ASP.Net 2.0 website that is currently using a custom MembershipProvider and the standard login control. I would like to replace the login control with the one from DotNetOpenId.</p> <p>I override the ValidateUser which checks the username and password, but I shouldn't need to implement this when using OpenId.</p> <p>Is it possible to use OpenId and still have the membership provider available to me to so that I can still use it to access the current logged in user?</p> <p>Or is it the case the there is need for the using provider model anymore?</p>
<p>There is no inbuilt provider available. But you can always implement your own provider.</p> <p>Or you can check out <a href="http://www.codeplex.com/OpenIDMembership" rel="nofollow noreferrer">this one</a> available in codePlex. </p>
<p>This is the premier .NET OpenID library, by Andrew Arnott, MSFT employee: <a href="http://code.google.com/p/dotnetopenid/" rel="nofollow noreferrer">http://code.google.com/p/dotnetopenid/</a></p> <p>Not sure about integration with Membership.</p>
17,179
<p>I am wondering if anyone is already using Entity Framework with an Oracle database in a production environment? There seems to be no support for EF in ODP.Net and only 3rd party data providers (OraDirect) seem to be available to connect with Oracle. Someone mentioned asample data provider available on Codeplex but it is presented with the message that it should never be used in a production environment.</p> <p>Are you using EF with an Oracle database already?</p>
<p>Personally, I wouldn't attempt this yet. The message on the sample data provider is warning enough. The level of validation you would need to go through to be comfortable using EF in this configuration wouldn't be worth the effort, IMO.</p>
<p>I've installed this from Oracle</p> <p><a href="http://www.oracle.com/technetwork/topics/dotnet/downloads/oracleefbeta-302521.html" rel="nofollow">http://www.oracle.com/technetwork/topics/dotnet/downloads/oracleefbeta-302521.html</a></p> <p>The only problem i have accoured is when i have a table with a SEQ+Trigger to have "auto ident" field, the framework doesn't return the number on "SaveChanges()" when i adds a contextobject. But the record itself gets inserted fine.</p> <p>Otherwise it seems ok.</p> <p>The app i'm doing is only to be used internaly in the company. But as the companys main system is Microsoft XAL on Oracle, there proberly will be more apps done this way. So ofcourse hope for a stable realease soon.</p> <p>\T</p>
14,158
<p>I am currently in the process of replacing the IBM WebService framework with Axis2. When generating the code from the WSDL file, I use the Maven plugin WSDL2Code. However, the code created is always wrong. Or rather, the packagenames are always wrong, which in turn makes every method called uncallable (creating even more errors, up to 10.000+ errors in eclipse).</p> <p>Here's an example of what is actually going on (this is just an example I made specifically to get advice):</p> <pre><code> &lt;plugin&gt; &lt;groupId&gt;org.apache.axis2&lt;/groupId&gt; &lt;artifactId&gt;axis2-wsdl2code-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.4.1&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;Test&lt;/id&gt; &lt;goals&gt; &lt;goal&gt;wsdl2code&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;packageName&gt;test.testpackage&lt;/packageName&gt; &lt;databindingName&gt;xmlbeans&lt;/databindingName&gt; &lt;wsdlFile&gt;${basedir}/wsdl/service.wsdl&lt;/wsdlFile&gt; &lt;outputDirectory&gt;${basedir}/testdirectory&lt;/outputDirectory&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>In theory, this should generate code with the package name "test.testpackage" in the directory testdirectory/test/testpackage. However, instead it creates the following package: Src.test.testpackage in the directory testdirectory.src.test.testpackage. It always adds a "src" to both package name and directory - if I change the package name to src.test.testpackage, it will generate the following package: src.src.test.testpackage.</p> <p>This, of course, leads to a huge problem, because every generated file has the following error: "The declared package "src.test.testpackage" does not match the expected package "src.src.test.testpackage"</p> <p>I'm at a complete loss here. I simply can't find any reason at all why it should add "src" everywhere. I've noticed an auto-generated build.xml file containing a value called sourcedirectory = x/src (or something similar), but there's nothing I can do to affect this value (trying to change it and then save the file makes no difference, obviously, since it's just generated again the next time I run maven).</p> <p>Oh, and I generally use the command "mvn clean install" and version 1.4.1 of WSDL2Code, so it's not one of the old wsdl2code:wsdl2code bugs. </p> <p>If anyone has any idea of what is actually wrong here, I'd greatly appreciate it. </p> <p>Thanks in advance.</p>
<p>Version 1.4.1 has a few more configuration options that are not really documented (have a look at the the source of org.apache.axis2.maven2.wsdl2code.WSDL2CodeMojo)...</p> <p>Just use &lt;flattenFiles&gt;true&lt;/flattenFiles&gt; - that should solve your problem :-)</p>
<p>Maybe 'src' is part of ${basedir} ?</p>
43,275
<p>I'm working in a small company and weeks away from deploying a web-app that will be used a lot. Everyone at one location will have to learn to use it, and although I think it's pretty easy and intuitive I may be biased.<br> I've written a help guide with plenty of screenshots that's available on every page, but I'll still need to train everyone. What's the best way? How do you take a step back and explain code you've been working on for weeks?</p>
<p><strong>First try to avoid the training:</strong></p> <p>Perform <a href="http://en.wikipedia.org/wiki/Usability_testing" rel="noreferrer">usability testing</a> to ensure your web app is intuitive. Usability testing is a very important aspect of testing and it is often ignored. How you see your system will probably be very different as how a new user sees your system.</p> <p>Also add contextual help as often as you can. For example when I hover over a tag in stack overflow, I know exactly what clicking it will do, because it tells me. </p> <p>Also this may seem obvious, but make sure you link to your documentation from the site itself. People may not think of looking in your documentation unless its right in front of their eyes.</p> <p><strong>About training documentation:</strong></p> <p>Try to split up your material into how your users would use the system. I personally like the "trails" option that Sun created for their <a href="http://java.sun.com/docs/books/tutorial/" rel="noreferrer">Java tutorials</a>. In this tutorial you can do several things, and you can chose on which trail you'd like to go.</p> <p>Support random reads in your help documentation. If they have a task to do in your web app, then they should be able to get help on that without reading a bunch of unrelated content. </p> <p>Make sure your documentation is searchable. </p> <p><strong>About actual training sessions:</strong></p> <p>If you are actually performing training sessions, stay away from explaining anything related to your code at all. You don't need to know about the engine to drive a car.</p> <p>Try to split up your training sessions into very focused aspects of your system. If you only have 1 training session available to you then just do one specialized use case of your system + the overall description of the system. Refer to the different parts of documentation where they can get help.</p> <p><strong>Letting the community help itself:</strong></p> <p>No matter how extensive your documentation is, you'll always have cases that you didn't cover. That's why it's a good idea to have a forum available to all users of the system. Allow them to ask each other questions. </p> <p>You can review this forum and add content to your documentation as needed. </p> <p>You could also open up a wiki for the documentation itself, but this is probably not desirable if your user base isn't very large. </p>
<p>Try a few users first, one or two in a small company. Mostly watch, help as little as possible. This tells you what needs to be fixed, and it creates an experienced user base - so you are not the "training bottleneck" anymore. </p> <p>Turn core requirements/use cases/storycards into HowTo / walkthroughs for your documentation.</p> <p>For a public training, prepare a 10..15 minute presentation (just that, not more!) that covers key concepts that the <strong>users</strong> absolutely must understand, than show your core walkthroughs. Reserve extra time for questions about how to solve various tasks. </p> <p>Think as a user, not as a techie: - noone cares if it's a SQL database and you spent a lot of time to get the locking mechanisms right. They do care about "does it slow me down" and "does something bad happen when two people do that at the same time". Our job is to make complicated things look easy.</p> <p>It may help to put the documentation on the intranet in an editable form - page "comments", or wiki maybe. And/or put up a "error wiki" for error messages and blips - where you or your users can quickly add recomendations, workarounds and reasons for anything that does not go as expected.</p>
29,262
<p>I currently use the following command, but it's a little unwieldy to type. What's a shorter alternative?</p> <pre><code>find . -name '*.txt' -exec grep 'sometext' '{}' \; -print </code></pre> <p>Here are my requirements:</p> <ul> <li>limit to a file extension (I use SVN and don't want to be searching through all those .svn directories)</li> <li>can default to the current directory, but it's nice to be able to specify a different directory</li> <li>must be recursive</li> </ul> <p><strong>UPDATE:</strong> Here's my best solution so far:</p> <pre><code>grep -r 'sometext' * --include='*.txt' </code></pre> <p><strong>UPDATE #2:</strong> After using grep for a bit, I realized that I like the output of my first method better. So, I followed the suggestions of several responders and simply made a shell script and now I call that with two parameters (extension and text to find).</p>
<p>grep has -r (recursive) and --include (to search only in files and directories matching a pattern).</p>
<p>I usualy avoid the "man find" by using <code>grep $(find . -name "*,txt")</code></p>
27,500
<p>I've read on Wikipedia and other sites about <a href="https://en.wikipedia.org/wiki/OSGi" rel="noreferrer">OSGi</a>, but I don't really see the big picture. It says that it's a component-based platform, and that you can reload modules at runtime. Also the "practical example" given everywhere is the Eclipse Plugin Framework.</p> <p>My questions are:</p> <ol> <li><p>What is the clear and simple definition of OSGi?</p></li> <li><p>What common problems does it solve?</p></li> </ol> <p>By "common problems" I mean problems we face everyday, like "What can OSGi do for making our jobs more efficient/fun/simple?"</p>
<p>I've found the following benefits from OSGi:</p> <ul> <li>Each plugin is a versioned artifact that has its own classloader.</li> <li>Each plugin depends on both specific jars that it contains and also other specific versioned plug-ins.</li> <li>Because of the versioning and isolated classloaders, different versions of the same artifact can be loaded at the same time. If one component of your application relies on one version of a plug-in and another depends on another version, they both can be loaded at the same time.</li> </ul> <p>With this, you can structure your application as a set of versioned plugin artifacts that are loaded on demand. Each plugin is a standalone component. Just as Maven helps you structure your build so it is repeatable and defined by a set of specific versions of artifacts it is created by, OSGi helps you do this at runtime. </p>
<p>It is also being used to bring additional portability of middleware and applications on the mobile side. Mobile side is available for WinMo, Symbian, Android for example. As soon as integration with device features occurs, can get fragmented.</p>
13,169
<p>I have some code that gives a user id to a utility that then send email to that user.</p> <pre><code>emailUtil.sendEmail(userId, "foo"); public void sendEmail(String userId, String message) throws MailException { /* ... logic that could throw a MailException */ } </code></pre> <p><code>MailException</code> could be thrown for a number of reasons, problems with the email address, problems with the mail template etc.</p> <p>My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened.</p> <p><strong>Edit:</strong> As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a <strong>valid</strong> email address, or it could fail.. etc.</p> <p>My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well).</p> <p>Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was.</p>
<p>I usually start with a general exception and subclass it as needed. I always can catch the general exception (and with it all subclassed exceptions) if needed, but also the specific.</p> <p>An example from the Java-API is IOException, that has subclasses like FileNotFoundException or EOFException (and much more).</p> <p>This way you get the advantages of both, you don't have throw-clauses like:</p> <pre><code>throws SpecificException1, SpecificException2, SpecificException3 ... </code></pre> <p>a general</p> <pre><code>throws GeneralException </code></pre> <p>is enough. But if you want to have a special reaction to special circumstances you can always catch the specific exception.</p>
<p>I would just go by</p> <pre><code>throw new exception("WhatCausedIt") </code></pre> <p>if you want to handle your exceptions, you could pass a code instead of "WhatCausedIt" an then react to the different answers with a switch statement. </p>
4,179
<p>It seems redundant to have zlib compress a web page during every request. It is also the bottleneck of my files' response times. Is there a way to cache the zlib'd file so that it is compressed only once at each modification? Or should I just keep wishing?</p>
<p>If you want a quick and lazy solution, just make gzipped copies of your most used files and turn <a href="http://httpd.apache.org/docs/2.2/content-negotiation.html" rel="nofollow noreferrer">MultiViews</a> on for them. This still has CPU overhead to calculate the right file to send but it's less than a gzip every time. If you want to take it further you can create static type-map files.</p> <p>Also you could consider using Lighttpd if possible instead of Apache. It has a mod_compress which does exactly what you want.</p>
<p>Hm, I think mod_cache will do the job. <a href="http://httpd.apache.org/docs/2.0/mod/mod_cache.html" rel="nofollow noreferrer">http://httpd.apache.org/docs/2.0/mod/mod_cache.html</a></p>
22,476
<p>I am trying to be a "good" programmer and have unit tests for my ColdFusion application but haven't been able to find a code coverage tool that can tie into the test that I'm using. For those of you who do unit tests on your ColdFusion code, how have you approached this problem?</p>
<p><a href="http://www.houseoffusion.com/groups/cf-talk/thread.cfm/threadid:53046" rel="nofollow noreferrer">Many</a> <a href="http://www.pbell.com/index.cfm/2006/10/20/What-is-Code-Coverage-Analysis--and-why-should-you-care" rel="nofollow noreferrer">have</a> <a href="http://coolskool.blog-city.com/what_coldfusion_tools_do_you_want.htm" rel="nofollow noreferrer">asked</a>, but to date there remains no ColdFusion code coverage tool.</p> <p>The latest ColdFusion features .NET integration in addition to J2EE integration, so if you require code coverage metrics (ie, customer requirements) then (aside from choosing something other than ColdFusion) you might define what parts need such coverage and break them out into .NET or J2EE objects which you can profile with readily available tools.</p> <p>Alternately, you can do some analysis yourself - use a parser to insert <a href="http://livedocs.adobe.com/coldfusion/7/htmldocs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=ColdFusion_Documentation&amp;file=00001221.htm" rel="nofollow noreferrer">cftrace</a> tags after every control statement and then parse the results.</p> <p>Lastly, ColdFusion does have some <a href="http://www.bennadel.com/blog/116-Finding-Template-Execution-Stack-in-ColdFusion.htm" rel="nofollow noreferrer">basic stack trace</a> ability - I don't know if it goes deeper than that, but it's worth exploring to see what you can parse from that.</p> <p>I hope this helps!</p> <p>-Adam Davis</p>
<p><a href="http://www.houseoffusion.com/groups/cf-talk/thread.cfm/threadid:53046" rel="nofollow noreferrer">Many</a> <a href="http://www.pbell.com/index.cfm/2006/10/20/What-is-Code-Coverage-Analysis--and-why-should-you-care" rel="nofollow noreferrer">have</a> <a href="http://coolskool.blog-city.com/what_coldfusion_tools_do_you_want.htm" rel="nofollow noreferrer">asked</a>, but to date there remains no ColdFusion code coverage tool.</p> <p>The latest ColdFusion features .NET integration in addition to J2EE integration, so if you require code coverage metrics (ie, customer requirements) then (aside from choosing something other than ColdFusion) you might define what parts need such coverage and break them out into .NET or J2EE objects which you can profile with readily available tools.</p> <p>Alternately, you can do some analysis yourself - use a parser to insert <a href="http://livedocs.adobe.com/coldfusion/7/htmldocs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=ColdFusion_Documentation&amp;file=00001221.htm" rel="nofollow noreferrer">cftrace</a> tags after every control statement and then parse the results.</p> <p>Lastly, ColdFusion does have some <a href="http://www.bennadel.com/blog/116-Finding-Template-Execution-Stack-in-ColdFusion.htm" rel="nofollow noreferrer">basic stack trace</a> ability - I don't know if it goes deeper than that, but it's worth exploring to see what you can parse from that.</p> <p>I hope this helps!</p> <p>-Adam Davis</p>
5,049
<p>When I debug in Visual Studio, Firefox opens and that is annoying because of the hookups that Internet Explorer and Visual Studio have, such as when you close the Internet Explorer browser that starting debug opened, Visual Studio stops debugging. How can I get Visual Studio to open Internet Explorer instead without having to set Internet Explorer as my default browser?</p>
<p>Scott Guthrie has made a post on <a href="http://weblogs.asp.net/scottgu/archive/2005/11/18/430943.aspx" rel="noreferrer">how to change Visual Studio's default browser</a>:</p> <blockquote> <p>1) Right click on a .aspx page in your solution explorer</p> <p>2) Select the "browse with" context menu option</p> <p>3) In the dialog you can select or add a browser. If you want Firefox in the list, click "add" and point to the firefox.exe filename</p> <p>4) Click the "Set as Default" button to make this the default browser when you run any page on the site.</p> </blockquote> <p>I however dislike the fact that this isn't as straightforward as it should be.</p>
<p>Another way is to do the following in Visual Studio:</p> <ol> <li>Select Debug</li> <li>Options and Settings</li> <li>Expand Environment</li> <li>Select Web Browser</li> <li>Click the '<strong>Internet Explorer Options</strong>' button</li> <li>Select the '<strong>Programs</strong>' tab</li> <li>Select '<strong>Make Default</strong>' button for Internet Explorer</li> </ol>
10,540
<p>Another poster asked about <a href="https://stackoverflow.com/questions/224138/infinite-loops-top-or-bottom">preferred syntax for infinite loops</a>.</p> <p>A follow-up question: <i>Why</i> do you use infinite loops in your code? I typically see a construct like this:</p> <pre><code>for (;;) { int scoped_variable = getSomeValue(); if (scoped_variable == some_value) { break; } } </code></pre> <p>Which lets you get around not being able to see the value of scoped_variable in the <code>for</code> or <code>while</code> clause. What are some other uses for "infinite" loops?</p>
<p>A loop like:</p> <pre><code>while (true) { // do something if (something else) break; // do more } </code></pre> <p>lets you break out of the loop in the middle, rather than at the start (while/for) or end (do-while).</p> <p>If you've got a complex condition, you might also want to use this style to make the code clearer.</p>
<p>I used to use them when waiting for multiple threads to complete in c#, but now I use the ThreadPool class.</p>
27,696
<p>I'm looking at the following code snippet:</p> <pre><code>my @ret = &lt;someMethod&gt; return (undef) if( $DB_ERROR ); return (undef) unless ($#ret &gt;= 0); </code></pre> <p>Does <code>$#</code> just give you a count of elements in a array?</p>
<p><code>$#arrayname</code> gives you the index of the last element, so if array <code>@ret</code> has 2 elements then <code>$#ret</code> is 1. </p> <p>And, as noted by Barry Brown, an empty array gives -1.</p> <p>To get the length you can use the array in scalar context:</p> <pre><code>print scalar @ret; </code></pre>
<p>To summarize everyone else, that code is much more legible if written like this:</p> <pre><code>my @ret = someMethod(); return if $DB_ERROR; return unless @ret; </code></pre>
29,878
<p>Here's my table: </p> <pre><code>CREATE TABLE `alums_alumphoto` ( `id` int(11) NOT NULL auto_increment, `alum_id` int(11) NOT NULL, `photo_id` int(11) default NULL, `media_id` int(11) default NULL, `updated` datetime NOT NULL, PRIMARY KEY (`id`), KEY `alums_alumphoto_alum_id` (`alum_id`), KEY `alums_alumphoto_photo_id` (`photo_id`), KEY `alums_alumphoto_media_id` (`media_id`), CONSTRAINT `alums_alumphoto_ibfk_1` FOREIGN KEY (`media_id`) REFERENCES `media_mediaitem` (`id`), CONSTRAINT `alum_id_refs_id_706915ea` FOREIGN KEY (`alum_id`) REFERENCES `alums_alum` (`id`), CONSTRAINT `photo_id_refs_id_63282119` FOREIGN KEY (`photo_id`) REFERENCES `media_mediaitem` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=63 DEFAULT CHARSET=utf8 </code></pre> <p>I want to delete the column <code>photo_id</code>, which presumably will also require deleting the foreign key constraint and the index.</p> <p>The problem is that I get errors when I try to drop the column: </p> <pre>ERROR 1025 (HY000): Error on rename of '.\dbname\#sql-670_c5c' to '.\dbname\alums_alumphoto' (errno: 150)</pre> <p>... when I try to drop the index (same as above), and when I try to drop the foreign key constraint: </p> <pre>ERROR 1091 (42000): Can't DROP 'photo_id_refs_id_63282119'; check that column/key exists)</pre> <p>What order should I be doing all of this in? What precise commands should I be using?</p>
<p>Precisely, try this : </p> <p>First drop the Foreign Key or Constraint :</p> <pre><code>ALTER TABLE `alums_alumphoto` DROP FOREIGN KEY `photo_id_refs_id_63282119`; </code></pre> <p>The previous command removes the Foreign Key Constraint on the column. Now you can drop the column <code>photo_id</code> (the index is removed by MySQL on dropping the column) :</p> <pre><code>ALTER TABLE `alums_alumphoto` DROP COLUMN `photo_id`; </code></pre> <p>Aternatively, you could combine these 2 operations into one : </p> <pre><code>ALTER TABLE `alums_alumphoto` DROP FOREIGN KEY `photo_id_refs_id_63282119` , DROP COLUMN `photo_id`; </code></pre>
<p>Try combining the DROP KEY and DROP FOREIGN KEY statements.</p> <pre><code>ALTER TABLE `alums_alumphoto` DROP KEY KEY `alums_alumphoto_photo_id`, DROP FOREIGN KEY `photo_id_refs_id_63282119`; ALTER TABLE `alums_alumphoto` DROP COLUMN `photo_id`; </code></pre>
44,013
<p>Up till now I have been developing my personal and school projects at home without using any form of revision control software to handle my changes and whatnot.</p> <p>My question is, <strong>how feasible is it to use a Version Control application</strong> (such as <a href="http://en.wikipedia.org/wiki/TortoiseSVN" rel="nofollow noreferrer">TortoiseSVN</a>) <strong>for personal projects I do for myself</strong> (and even school projects) ?</p> <p>Is it worth the hassle of checking in, committing changes and all that routine, just for 'home-projects' instead of just making manual backups?</p> <p><strong>Links</strong>:</p> <ul> <li><a href="http://tortoisesvn.tigris.org/" rel="nofollow noreferrer">Tortoise SVN</a></li> <li><a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-serversetup-svnserve.html" rel="nofollow noreferrer">SvnServe Server</a></li> </ul>
<p>Completely.</p> <p>Credits also to <a href="http://blogs.embarcadero.com/nickhodges/2010/04/23/39416" rel="noreferrer">http://blogs.embarcadero.com/nickhodges/2010/04/23/39416</a>:</p> <ul> <li><strong>Sometimes we do stupid mistakes.</strong> Having a source control safety net is a must.</li> <li><strong>Tag important milestones.</strong> Even in home development you may want to mark a set of files and revisions as being a specific software version.</li> <li><strong>You train for your professional life.</strong> Putting in your head the work methodology associated with using source control prepares you professionally.</li> <li><strong>Storage efficiency.</strong> Current source control systems store revisions as a delta difference to the previous revision. This means that it is more disk efficient as the entire file is not stored but only the differences.</li> <li><strong>You have the history for all your source tree.</strong> You can rapidly see what was changed and when was changed. Compare files from different revisions and merge easily.</li> <li><strong>You can branch to experiment.</strong> If you have some experiments in mind you can create a branch (a new independent development line) and test it. In the end, if you are satisfied with the results, merge it in the HEAD (main development line). You get all this for free without having to create a copy and receive the same benefits from using the source control even while experimenting.</li> </ul>
<p>I find that it is extremely helpful to have a SVN server setup because I find myself going back through revisions and other 'throw away' projects because I remembered some function or way of doing something that I could use now. Having the SVN server, I know that the code is stored at home and I can pull it up later.</p>
47,098
<p>What are good reasons to prohibit inheritance in Java, for example by using final classes or classes using a single, private parameterless constructor? What are good reasons of making a method final?</p>
<p>Your best reference here is Item 19 of Joshua Bloch's excellent book &quot;Effective Java&quot;, called &quot;Design and document for inheritance or else prohibit it&quot;. (It's item 17 in the second edition and item 15 in the first edition.) You should really read it, but I'll summarize.</p> <p>The interaction of inherited classes with their parents can be surprising and unpredictable if the ancestor wasn't designed to be inherited from.</p> <p>Classes should therefore come in two kinds:</p> <ol> <li><p>Classes <em>designed to be **extended</em>**, and with enough documentation to describe how it should be done</p> </li> <li><p>Classes <em>marked **final</em>**</p> </li> </ol> <p>If you are writing purely internal code, this may be a bit of overkill. However, the extra effort involved in adding five characters to a class file is very small. If you are writing only for internal consumption, then a future coder can always remove the 'final' - you can think of it as a warning saying &quot;this class was not designed with inheritance in mind&quot;.</p>
<p>You want to make a method final so that overriding classes does not change its behavior. When you want to be able to change the behavior make the method public. When you override a public method it can be changed. </p>
26,916
<p>Alright, so I just finished my last compiler error (so I thought) and these errors came up:</p> <pre><code>1&gt;GameEngine.obj : error LNK2001: unresolved external symbol "public: static double WeaponsDB::PI" (?PI@WeaponsDB@@2NA) 1&gt;Component.obj : error LNK2001: unresolved external symbol "public: static double WeaponsDB::PI" (?PI@WeaponsDB@@2NA) 1&gt;Coordinate.obj : error LNK2019: unresolved external symbol "public: static double WeaponsDB::PI" (?PI@WeaponsDB@@2NA) referenced in function "public: double __thiscall Coordinate::distanceFrom(class Coordinate *)" (?distanceFrom@Coordinate@@QAENPAV1@@Z) 1&gt;Driver.obj : error LNK2001: unresolved external symbol "public: static double WeaponsDB::PI" (?PI@WeaponsDB@@2NA) 1&gt;Environment.obj : error LNK2001: unresolved external symbol "public: static double WeaponsDB::PI" (?PI@WeaponsDB@@2NA) 1&gt;Environment.obj : error LNK2001: unresolved external symbol "public: static bool Environment::spyFlag" (?spyFlag@Environment@@2_NA) 1&gt;Environment.obj : error LNK2001: unresolved external symbol "private: static class Environment * Environment::instance_" (?instance_@Environment@@0PAV1@A) 1&gt;Environment.obj : error LNK2019: unresolved external symbol "public: static void __cdecl Environment::spyAlertOver(void)" (?spyAlertOver@Environment@@SAXXZ) referenced in function "public: void __thiscall Environment::notificationOfSpySuccess(void)" (?notificationOfSpySuccess@Environment@@QAEXXZ) 1&gt;GameDriver.obj : error LNK2019: unresolved external symbol "public: static void __cdecl MainMenu::gameOver(int)" (?gameOver@MainMenu@@SAXH@Z) referenced in function "public: static void __cdecl GameDriver::run(void)" (?run@GameDriver@@SAXXZ) 1&gt;GameDriver.obj : error LNK2019: unresolved external symbol "public: static void __cdecl GameDriver::gatherInput(void)" (?gatherInput@GameDriver@@SAXXZ) referenced in function "public: static void __cdecl GameDriver::run(void)" (?run@GameDriver@@SAXXZ) 1&gt;GameDriver.obj : error LNK2019: unresolved external symbol "public: static void __cdecl GameDriver::ticker(void)" (?ticker@GameDriver@@SAXXZ) referenced in function "public: static void __cdecl GameDriver::run(void)" (?run@GameDriver@@SAXXZ) 1&gt;GameDriver.obj : error LNK2001: unresolved external symbol "public: static int GameDriver::ticks" (?ticks@GameDriver@@2HA) 1&gt;GameDriver.obj : error LNK2001: unresolved external symbol "public: static bool GameDriver::evaluatingInputFlag" (?evaluatingInputFlag@GameDriver@@2_NA) 1&gt;GameDriver.obj : error LNK2001: unresolved external symbol "public: static bool GameDriver::keyQuitFlag" (?keyQuitFlag@GameDriver@@2_NA) 1&gt;GameDriver.obj : error LNK2001: unresolved external symbol "public: static bool GameDriver::keyToggleWeaponRightFlag" (?keyToggleWeaponRightFlag@GameDriver@@2_NA) 1&gt;GameDriver.obj : error LNK2001: unresolved external symbol "public: static bool GameDriver::keyToggleWeaponLeftFlag" (?keyToggleWeaponLeftFlag@GameDriver@@2_NA) 1&gt;GameDriver.obj : error LNK2001: unresolved external symbol "public: static bool GameDriver::keyFireFlag" (?keyFireFlag@GameDriver@@2_NA) 1&gt;GameDriver.obj : error LNK2001: unresolved external symbol "public: static bool GameDriver::keyLeftFlag" (?keyLeftFlag@GameDriver@@2_NA) 1&gt;GameDriver.obj : error LNK2001: unresolved external symbol "public: static bool GameDriver::keyRightFlag" (?keyRightFlag@GameDriver@@2_NA) 1&gt;GameDriver.obj : error LNK2001: unresolved external symbol "public: static bool GameDriver::keyUpFlag" (?keyUpFlag@GameDriver@@2_NA) 1&gt;GameDriver.obj : error LNK2001: unresolved external symbol "public: static bool GameDriver::keyDownFlag" (?keyDownFlag@GameDriver@@2_NA) 1&gt;GUI_Env.obj : error LNK2001: unresolved external symbol "private: static struct BITMAP * GUI_Env::buffer" (?buffer@GUI_Env@@0PAUBITMAP@@A) 1&gt;GUI_Info.obj : error LNK2001: unresolved external symbol "private: static struct BITMAP * GUI_Info::buffer" (?buffer@GUI_Info@@0PAUBITMAP@@A) 1&gt;MenuDriver.obj : error LNK2019: unresolved external symbol "public: static void __cdecl MainMenu::displayMenu(void)" (?displayMenu@MainMenu@@SAXXZ) referenced in function "public: static void __cdecl MenuDriver::start(void)" (?start@MenuDriver@@SAXXZ) 1&gt;SpaceObjectFactory.obj : error LNK2001: unresolved external symbol "private: static class SpaceObjectFactory * SpaceObjectFactory::_instance" (?_instance@SpaceObjectFactory@@0PAV1@A) 1&gt;Spy.obj : error LNK2019: unresolved external symbol "public: virtual bool __thiscall UnFormationable::sameTypeOfSpaceObjectAs(class SpaceObject *)" (?sameTypeOfSpaceObjectAs@UnFormationable@@UAE_NPAVSpaceObject@@@Z) referenced in function "public: virtual bool __thiscall Spy::sameTypeOfSpaceObjectAs(class SpaceObject *)" (?sameTypeOfSpaceObjectAs@Spy@@UAE_NPAVSpaceObject@@@Z) 1&gt;WeaponsDB.obj : error LNK2001: unresolved external symbol "private: static class WeaponsDB * WeaponsDB::_instance" (?_instance@WeaponsDB@@0PAV1@A) 1&gt;C:\Users\Owner\Desktop\Bosconian\code\Bosconian\Debug\Bosconian.exe : fatal error LNK1120: 23 unresolved externals </code></pre> <p>Alright, here's a brief overview.</p> <p>PI is a static constant in WeaponsDB and is referenced by other classes using WeaponsDB::PI and the appropriate #include (what's wrong with this?)</p> <p>Most other errors stem from static variables and static methods for timers from the allegro gaming library.</p> <p>What causes these errors and how might I get rid of them?</p> <p>Thanks in advance</p> <p>----------------Edits-------------------</p> <p>As requested, where the WeaponsDB::PI is declared and defined. It is declared in WeaponsDB.h:</p> <pre><code>public: static double PI; </code></pre> <p>But it is defined in another class Driver.cpp:</p> <pre><code>WeaponsDB::PI = 4*atan(1.0); </code></pre> <p>If this is one of the problems with my code I would love to know why this causes an error.</p>
<p>Most often, when the linker is failing to detect a static member it is because you to forgot to really define it somewhere, as it was pointed before:</p> <pre><code>// header class X { static const int y; }; // cpp const int X::y = 1; </code></pre> <p>But in your case, as you are not only missing static variables but also all the rest of the members my bet is that you are not linking the implementation file(s) (.cpp) in your project. You must provide a compilation unit that defines the symbols that were declared in the header, and make the environment compile and link it together. If the symbols belong to a compilation unit in an external library (from your current project) then you must remember to link with the library.</p>
<p>Declaring a variable in one place and assigning it a value in another place shouldn't cause any errors. Make sure you include WeaponsDB.h at the top of all files that reference objects defined there. </p> <p>Ex: at the top of Driver.cpp, make sure "#include WeaponsDB.h" appears.</p> <p>Hope this helps!</p>
49,818
<p>I'm new to Ruby, and I'm trying the following: </p> <pre><code>mySet = numOfCuts.times.map{ rand(seqLength) } </code></pre> <p>but I get the 'yield called out of block' error. I'm not sure what his means. BTW, this question is part of a more general question I asked <a href="https://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby"><strong>here</strong></a>.</p>
<p>The problem is that the times method expects to get a block that it will yield control to. However you haven't passed a block to it. There are two ways to solve this. The first is to not use times:</p> <pre><code>mySet = (1..numOfCuts).map{ rand(seqLength) } </code></pre> <p>or else pass a block to it:</p> <pre><code>mySet = [] numOfCuts.times {mySet.push( rand(seqLength) )} </code></pre>
<p>Integer.times expects a block. The error message means the <code>yield</code> statement inside the <code>times</code> method can not be called because you did not give it a block.</p> <p>As for your code, I think what you are looking for is a range: </p> <pre><code>(1..5).map{ do something } </code></pre> <p>Here is thy rubydoc for the <a href="http://www.ruby-doc.org/core/classes/Integer.html#M001160" rel="nofollow noreferrer">Integer.times</a> and <a href="http://www.ruby-doc.org/core-1.8.7/classes/Range.html" rel="nofollow noreferrer">Range</a>.</p>
14,502
<p>I'm a php guy, but I have to do some small project in JSP. I'm wondering if there's an equivalent to htmlentities function (of php) in JSP.</p>
<pre><code>public static String stringToHTMLString(String string) { StringBuffer sb = new StringBuffer(string.length()); // true if last char was blank boolean lastWasBlankChar = false; int len = string.length(); char c; for (int i = 0; i &lt; len; i++) { c = string.charAt(i); if (c == ' ') { // blank gets extra work, // this solves the problem you get if you replace all // blanks with &amp;nbsp;, if you do that you loss // word breaking if (lastWasBlankChar) { lastWasBlankChar = false; sb.append("&amp;nbsp;"); } else { lastWasBlankChar = true; sb.append(' '); } } else { lastWasBlankChar = false; // // HTML Special Chars if (c == '"') sb.append("&amp;quot;"); else if (c == '&amp;') sb.append("&amp;amp;"); else if (c == '&lt;') sb.append("&amp;lt;"); else if (c == '&gt;') sb.append("&amp;gt;"); else if (c == '\n') // Handle Newline sb.append("&amp;lt;br/&amp;gt;"); else { int ci = 0xffff &amp; c; if (ci &lt; 160 ) // nothing special only 7 Bit sb.append(c); else { // Not 7 Bit use the unicode system sb.append("&amp;#"); sb.append(new Integer(ci).toString()); sb.append(';'); } } } } return sb.toString(); } </code></pre>
<p>I suggest using escapeXml set to true attribute of JSTL's directly in JSP</p> <pre><code>&lt;c:out value="${string}" escapeXml="true" /&gt; </code></pre>
42,549
<p>As a developer, how do you use gdb to track down bugs within your code? What techniques tricks do you use to make your life easier?</p>
<p>In general you find something that isn't how it should be, and work backwards until you understand why.</p> <p>The most obvious is the most useful: Setting a breakpoint on a function or line number and walking through the code line by line.</p> <p>Another handy tip is to have show functions for all your structures/objects even if they are never used in your program, because you can run these functions from within gdb:</p> <pre><code>gdb&gt; p show_my_struct(struct) My custom display of Foo: ... </code></pre> <p>Watchpoints can be really handy too, but may slow down your program a lot. These break the flow when the value of a variable or address changes.:</p> <pre><code>gdb&gt; watch foo Watchpoint4: foo gdb&gt; </code></pre>
<p>Use ddd, a visual front-end for gdb. It lets you do things easily with a few mouse clicks and visualise how the code works, plus in the debugger console you have an intercative gdb.</p>
16,966
<p>What do you do if members of your team are not cooperative during scrum meetings? They either provide a very high level definition of what they are currently working on, ("working on feature x"), or go into extremely irrelevant details, <strong>in spite of being well educated in SCRUM methodology</strong>. This causes the scrum meeting to be ineffective and boring.</p> <p>As a scrum master, what are your techniques to getting the best out of people during the meeting?</p> <p>Edited to add:</p> <p><strong>What technique do you use to stop someone who is talking too much, without being offensive?</strong></p> <p><strong>What technique do you use to encourage someone to provide a more detailed answer?</strong></p> <p><strong>How do you react when you find yourself being the only one who listens, while other team members just sit there and maybe even fall asleep?</strong></p>
<p>First of all... make sure folks are standing up... and not even leaning on the wall or a desk.</p> <p>At a high level, I would say that, whenever you face issues on the team, the best response is to <em>ask the team</em> for solutions. However, here are some of the techniques I've used for the issues you're facing.</p> <p><strong>Talks too much</strong> </p> <ul> <li>have him/her stand on one leg</li> <li>have him/her hold the scrum "speaking" token in an outstretched hand while they speak.</li> <li>Add a flip chart to the scrum to list tabled issues... when someone gets longwinded on a topic that is not scrum-meeting-worthy, interrupt and say "Hey - great point. I'm not sure everyone needs to discuss this, how 'bout if we park this for a follow-up discussion?" A key to making this successful is to actually follow-up afterwards and get the side conversation scheduled. Alternatively, the speaker may just say "Not necessary... I'll be working with Joe this afternoon on this" or something like that, which accomplishes the goal of reducing the windedness without the need to schedule the follow-up.</li> </ul> <p><strong>Need more detail</strong>. Is this for the scrum master's benefit or the team's? </p> <ul> <li>wait until afterwards to ask the individual more detailed questions. If you think the team also needs to know them, coach the team member by conveying (in your after-scrum questioning) that "this is the sort of thing that I think Joe Smith would be helped in hearing from you, what do you think?"</li> </ul> <p><strong>Team doesn't listen</strong>. </p> <ul> <li>Ask them on an individual basis. "Sally, I noticed that you don't seem to be getting much out of the Scrum. How can we adjust it to make it valuable for you?".</li> <li>Post questions to others during the scrum. Like if Sally says "I integrated with Bob's code yesterday", ask Bob "how'd that go?" (I'd use this sparingly... to guard against scrums taking too long).</li> <li>I've found that sometimes team members tend towards old habits by looking at the scrum master or project manager when they speak. When this happens alot, I alter my gaze to look away, which almost forces the speaker to gain eye contact with other members of the team, which may help the other members of the team to pay attention.</li> </ul>
<p>Ask for the specific details you need. People won't be aware of stuff you are interested in.</p> <p>Also try to put forth some guidelines for better and effective presentation before the meeting.</p>
9,647
<p>How to arrange a Makefile to compile a kernel module with multiple .c files?</p> <p>Here is my current Makefile. It was auto generated by <a href="http://www.kdevelop.org/" rel="noreferrer">KDevelop</a></p> <pre><code>TARGET = nlb-driver OBJS = nlb-driver.o MDIR = drivers/misc EXTRA_CFLAGS = -DEXPORT_SYMTAB CURRENT = $(shell uname -r) KDIR = /lib/modules/$(CURRENT)/build PWD = $(shell pwd) DEST = /lib/modules/$(CURRENT)/kernel/$(MDIR) obj-m += $(TARGET).o default: make -C $(KDIR) M=$(PWD) modules $(TARGET).o: $(OBJS) $(LD) $(LD_RFLAG) -r -o $@ $(OBJS) ifneq (,$(findstring 2.4.,$(CURRENT))) install: su -c "cp -v $(TARGET).o $(DEST) &amp;&amp; /sbin/depmod -a" else install: su -c "cp -v $(TARGET).ko $(DEST) &amp;&amp; /sbin/depmod -a" endif clean: -rm -f *.o *.ko .*.cmd .*.flags *.mod.c make -C $(KDIR) M=$(PWD) clean -include $(KDIR)/Rules.make </code></pre>
<p>In my case the project consists of 6 files: </p> <ul> <li><code>monter_main.c</code>, <code>monter_main.h</code></li> <li><code>monter_cdev.c</code>, <code>monter_cdev.h</code></li> <li><code>monter_pci.c</code>, <code>monter_pci.h</code></li> </ul> <p><code>monter_main.c</code> is the main file of my module. </p> <p>Remember that you shouldn't have a file with the same name as the module you're trying to build (e.g. <code>monter.c</code> and <code>monter.ko</code>) unless you've got all code in that one file.</p> <p>Here are my Makefiles:</p> <ul> <li><p><strong>Makefile</strong></p> <pre><code>KDIR ?= /lib/modules/`uname -r`/build default: $(MAKE) -C $(KDIR) M=$$PWD install: $(MAKE) -C $(KDIR) M=$$PWD modules_install clean: $(MAKE) -C $(KDIR) M=$$PWD clean </code></pre></li> <li><p><strong>Kbuild</strong></p> <pre><code>obj-m := monter.o monter-objs := monter_main.o monter_cdev.o monter_pci.o </code></pre></li> </ul>
<p>I would assume that just listing more object files in the second line would do the trick.</p>
45,513
<p>What are all <a href="http://en.wikipedia.org/wiki/Hayes_command_set" rel="nofollow noreferrer">AT</a> commands required for <a href="http://en.wikipedia.org/wiki/General_Packet_Radio_Service" rel="nofollow noreferrer">GPRS</a> communication?</p>
<p>A more specific answer, if you're using a MultiTech Multimodem GPRS (or similar) and Tmobile's internet service (one of the higher tiers usually used with laptops). The uppercase names starting with "M" were the names of the states in the modem control state machine I was using. The data I was collecting was simple GPS strings, which were being stored by a PHP script on my server to be displayed here: <a href="http://www.ubasics.com/wmr/" rel="nofollow noreferrer">http://www.ubasics.com/wmr/</a> . A very basic tracking/telemetry application.</p> <p>Reset the modem:</p> <pre><code>MRESET: ATZ </code></pre> <p>Attach to the provider's network:</p> <pre><code>MPROVIDERINIT: at+cgdcont=1,"IP","internet3.voicestream.com",,0,0 MIPINIT: at+wopen=1 MPPPINIT: at#pppmode=1 MCHECKPIN: at+cpin? MGSMREGISTER: at+creg=1 </code></pre> <p>Attach to the providers GPRS network:</p> <pre><code>MGPRSREGISTER: at+cgreg=1 MGPRSATTACH: at+cgatt=1 MGPRSMODE: at#gprsmode=1 </code></pre> <p>Attach to the provider's internet PPP server:</p> <pre><code>MSERVERINIT: AT#APNSERV="internet3.voicestream.com" MUSERNAME: AT#APNUN="" MPASSWORD: AT#APNPW="" MSIGNAL: AT+CSQ MSTARTPPP: at#connectionstart </code></pre> <p>Attach the Modem's internal stack to an HTTP port:</p> <pre><code>MTCPSERVER: AT#TCPSERV="www.ubasics.com" MTCPPORT: AT#TCPPORT=80 MOPENSOCKET: at#otcp </code></pre>
<p>Most of the mobile phone specific AT commands are standardised and specified in <a href="http://www.3gpp.org/ftp/Specs/html-info/27007.htm" rel="nofollow noreferrer">27.007</a> (SMS related commands are in <a href="http://www.3gpp.org/ftp/Specs/html-info/27005.htm" rel="nofollow noreferrer">27.005</a>). For Sony Ericsson phones there is a document <a href="http://developer.sonyericsson.com/getDocument.do?docId=65054" rel="nofollow noreferrer">Developers' Guidelines - AT Commands (5.50 MB)</a> available.</p> <p>Beware that GPRS AT commands are far from trivial. If your phone is correctly configured and all you want it to start a IP connection using the first defined internet account, you can run</p> <pre><code>ATD*98*1# </code></pre> <p>or</p> <pre><code>ATD*99***1# </code></pre> <p>to start PPP negotiation (see "Extension of ATD – Request GPRS service" in the Sony Ericsson document).</p>
32,644
<p>Wondering if anyone has gotten the infamous "database is locked" error from Trac and how you solved it. It is starting to occur more and more often for us. Will we really have to bite the bullet and migrate to a different DB backend, or is there another way?</p> <p>See these two Trac bug entries for more info:</p> <p><a href="http://trac.edgewall.org/ticket/3446" rel="nofollow noreferrer">http://trac.edgewall.org/ticket/3446</a></p> <p><a href="http://trac.edgewall.org/ticket/3503" rel="nofollow noreferrer">http://trac.edgewall.org/ticket/3503</a></p> <p><strong>Edit 1</strong> Thanks for the answer and the recommendation, which seems to confirm our suspicion that migrating to PostgreSQL seems to be the best option. The SQLite to PostgreSQL script is here: <a href="http://trac-hacks.org/wiki/SqliteToPgScript" rel="nofollow noreferrer">http://trac-hacks.org/wiki/SqliteToPgScript</a> Here goes nothing...</p> <p><strong>Edit 2 (solved)</strong> The migration went pretty smooth and I expect we won't be seeing the locks any more. The speed isn't noticeably better as far as I can tell, but at least the locks are gone. Thanks!</p>
<p>That's a problem with the current SQLite adapter. There are scripts to migrate to postgres and I can really recommend that, postgres is a lot speeder for trac.</p>
<p>I don't think this is 100% fixed just yet. We experience this error a couple dozen times a day. In our case, we have 30+ people updating Trac <em>constantly</em> as we use it for tracking pretty much everything, and not just bugs. From ticket #3446:</p> <blockquote> <p>Quite obviously, this is [...] due to our database access patterns... which currently limit our concurrency to at most one write access each few seconds</p> </blockquote>
15,283
<p>I would like to have alternate behavior during a print stylesheet on a web page. Something along the lines of:</p> <blockquote> <p>If this page is being printed, don't bother calling SWFObject to summon an .swf into existence. Just leave the HTML that the Flash will replace.</p> </blockquote> <p>I've tried things like setting a known element to a known style that exists for the screen but not for the print stylesheet. But getting a "style" via Javascript doesn't get a <em>computed</em> style.</p> <p>Summary: In a cross-browser way, is it possible to tell which stylesheet is in effect?</p>
<p>It sounds like you're confused that print style-sheets are used when you view a printer-friendly page, but that is not the case. A print style sheet isn't applied until the user actually sends the page to the printer. At this point, any javascript that is going to run has already finished.</p> <p>What you want to do is put your SWFObject inside a div container, and have the container styled as <code>display:none;</code> for the print media.</p>
<p>You could use JavaScript to access the stylesheets in the document and then check if the 'Print' stylesheet is active. Once you determined which CSS is active then you could manage your content.</p> <p>The <code>getActiveStyleSheet</code> function would looks something like this:</p> <pre><code>function getActiveStyleSheet() { var i, a; for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) { if (a.getAttribute("rel").indexOf("style") != -1 &amp;&amp; a.getAttribute("title") &amp;&amp; !a.disabled) return a.getAttribute("title"); } return null; } </code></pre> <p>You can find the code here: <a href="http://www.alistapart.com/articles/alternate/" rel="nofollow noreferrer">http://www.alistapart.com/articles/alternate/</a>.</p>
44,882
<p>How does one do this?</p> <p>If I want to analyze how something is getting compiled, how would I get the emitted assembly code?</p>
<p>Use the <a href="https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S" rel="noreferrer">-S</a> option to <code>gcc</code> (or <code>g++</code>), optionally with <a href="https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fverbose-asm" rel="noreferrer">-fverbose-asm</a> which works well at the default <a href="https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-O0" rel="noreferrer">-O0</a> to attach C names to asm operands as comments. It works less well at any optimization level, which you normally want to use to get asm worth looking at.</p> <pre class="lang-none prettyprint-override"><code>gcc -S helloworld.c </code></pre> <p>This will run the preprocessor (cpp) over <em>helloworld.c</em>, perform the initial compilation and then stop before the assembler is run. For useful compiler options to use in that case, see <em><a href="https://stackoverflow.com/questions/38552116/how-to-remove-noise-from-gcc-clang-assembly-output">How to remove &quot;noise&quot; from GCC/clang assembly output?</a></em> (or just <strong>look at your code on <a href="https://godbolt.org/" rel="noreferrer">Matt Godbolt's online Compiler Explorer</a></strong> which filters out directives and stuff, and has highlighting to match up source lines with asm using debug information.)</p> <p>By default, this will output the file <code>helloworld.s</code>. The output file can be still be set by using the <a href="https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-o" rel="noreferrer">-o</a> option, including <code>-o -</code> to write to <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29" rel="noreferrer">standard output</a> for pipe into <a href="https://en.wikipedia.org/wiki/Less_(Unix)" rel="noreferrer">less</a>.</p> <pre class="lang-none prettyprint-override"><code>gcc -S -o my_asm_output.s helloworld.c </code></pre> <p>Of course, this only works if you have the original source. An alternative if you only have the resultant object file is to use <a href="https://linux.die.net/man/1/objdump" rel="noreferrer">objdump</a>, by setting the <code>--disassemble</code> option (or <code>-d</code> for the abbreviated form).</p> <pre class="lang-none prettyprint-override"><code>objdump -S --disassemble helloworld &gt; helloworld.dump </code></pre> <p><code>-S</code> interleaves source lines with normal disassembly output, so this option works best if debugging option is enabled for the object file (<a href="https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#index-g" rel="noreferrer">-g</a> at compilation time) and the file hasn't been stripped.</p> <p>Running <code>file helloworld</code> will give you some indication as to the level of detail that you will get by using <em>objdump</em>.</p> <p>Other useful <code>objdump</code> options include <code>-rwC</code> (to show symbol relocations, disable line-wrapping of long machine code, and demangle C++ names). And if you don't like AT&amp;T syntax for x86, <code>-Mintel</code>. See <a href="https://man7.org/linux/man-pages/man1/objdump.1.html" rel="noreferrer">the man page</a>.</p> <p>So for example, <code>objdump -drwC -Mintel -S foo.o | less</code>. <code>-r</code> is very important with a <code>.o</code> that only has <code>00 00 00 00</code> placeholders for symbol references, as opposed to a linked executable.</p>
<p>Use "-S" as an option. It displays the assembly output in the terminal.</p>
16,578
<p>What is the shortest chunk of C++ you can come up with to safely clean up a <code>std::vector</code> or <code>std::list</code> of pointers? (assuming you have to call delete on the pointers?)</p> <pre><code>list&lt;Foo*&gt; foo_list; </code></pre> <p>I'd rather not use Boost or wrap my pointers with smart pointers.</p>
<p>Since we are throwing down the gauntlet here... "Shortest chunk of C++"</p> <pre><code>static bool deleteAll( Foo * theElement ) { delete theElement; return true; } foo_list . remove_if ( deleteAll ); </code></pre> <p>I think we can trust the folks who came up with STL to have efficient algorithms. Why reinvent the wheel?</p>
<pre><code>for (list&lt;Foo*&gt;::const_iterator i = foo_list.begin(), e = foo_list.end(); i != e; ++i) delete *i; foo_list.clear(); </code></pre>
39,516
<p>Are there any more generic tools that can "compile" or basically merge multiple PHP files into a single file based on includes and autoloading classes? I'm thinking of something similar to Doctrine's compiling functionality or the compiling that many of the major JS frameworks do for "production" sites to lighten the file size and improve performance.</p> <p>Before writing a script to do it myself, I just want to find out if anything worth looking at already exists (Google hasn't been much help so far).</p> <p><strong>Edit:</strong> I've actually written a <a href="http://www.nickawilliams.com/2008/09/04/the-new-phar-php-package/" rel="nofollow noreferrer">blog post</a> about the .phar archive format and am very excited about that. I was actually more concerned about performance, but it sounds like merging files would not yield any benefit.</p> <p>Does anyone have any real data that might suggest the performance gain (or lack thereof) from merging multiple scripts into a single file?</p>
<p>Out of curiosity, why do you want to do this? If it's for performance, don't bother. Just use regular includes instead of auto-loading, and it will have much of the same effect. For performance you're better off looking at one of the run-time caching solutions.</p>
<p>I have run across the <a href="http://www.codeplex.com/YUICompressor" rel="nofollow noreferrer">YUI Compressor for .NET</a> that is hosted on codeplex.</p> <p>It will compress both JavaScript and CSS files in your project.</p> <p>I haven't tried it yet, but I am very interested in it.</p> <p>You can easily integrate it into your msbuild script.</p> <p>For more information you can visit <a href="http://developer.yahoo.com/yui/compressor/" rel="nofollow noreferrer">http://developer.yahoo.com/yui/compressor/</a></p>
20,270
<p>The mouse hovers over an element and a tip appears. The tip overflows the page, triggering a scrollbar, which changes the layout just enough so that the underlying element that triggered the tip is no longer under the mouse pointer, so the tip goes away.</p> <p>The tip goes away, so the scrollbar goes away, and now the mouse is again over the element.</p> <p>Wash, rinse, repeat.</p> <p>If I could make sure that tip isn't too big so as to trigger scrollbars, that would solve my problem.</p> <p>EDIT: After reading comments, some things to clarify: The div contains text which can vary. If I can, I want to show all the text. The div's location needs to be near the element the mouse's tip is over. So the key is, I need to know whether to truncate the text.</p> <p>I did find this link:<br> <a href="http://www.howtocreate.co.uk/tutorials/javascript/browserwindow" rel="nofollow noreferrer">http://www.howtocreate.co.uk/tutorials/javascript/browserwindow</a><br> which contains this piece of the puzzle, figuring out how big the browser window is: </p> <pre><code>function alertSize() { var myWidth = 0, myHeight = 0; if( typeof( window.innerWidth ) == 'number' ) { //Non-IE myWidth = window.innerWidth; myHeight = window.innerHeight; } else if( document.documentElement &amp;&amp; ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { //IE 6+ in 'standards compliant mode' myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight; } else if( document.body &amp;&amp; ( document.body.clientWidth || document.body.clientHeight ) ) { //IE 4 compatible myWidth = document.body.clientWidth; myHeight = document.body.clientHeight; } window.alert( 'Width = ' + myWidth ); window.alert( 'Height = ' + myHeight ); } </code></pre>
<p><strong>edit</strong>: in response to the comments, it sounds like you're trying to have the tooltip appear, without affecting the positioning of existing elements (and thus causing the scrollbar on the main window).</p> <p>if that's the case, you want to define your tooltip's position as absolute, as this will remove it from the flow of elements (so when it appears it won't push the rest of the page down).</p> <p>for example, you could start it hidden:</p> <pre><code>#tooltip { position: absolute; height: 100px; width: 200px; border: 1px solid #444444; background-color: #EEEEEE; display: none; } </code></pre> <p>then, on your mouseover event (or whatever it's called on), set the <code>top</code> and <code>left</code> css of the #tooltip to where ever you want it, and switch the display to <code>block</code>. as it's positioned absolutely, it won't cause the flicker.</p>
<p>Seems to me that what you need is cursor position within the client browser window. Then you can do your calculations to place the tooltip so it doesn't cross the border.</p> <p>What I found on the web is a short article discussing this in diffrent browsers: <a href="http://javascript.about.com/library/blmousepos.htm" rel="nofollow noreferrer">Mouse Cursor Position</a>. Maybe this could help you fix your problem? </p> <p>And some more info about browser size can be found <a href="http://javascript.about.com/od/guidesscriptindex/a/screen.htm" rel="nofollow noreferrer">here</a>.</p> <p>Hope it helps.</p>
25,924
<p>I have a .net project (MySolution.Common) that uses the app.config. I am using the project MySolution.Common in an InteropUserControl project called MySolution.InteropCtrl. MySolution.InteropCtrl is embedded into a VB6 project. When the MySolution.InteropCtrl is in the VB6 project, It cannot find the app.config file. Everything in the InteropControl works in VB6 except for what depends on the information in the app.config file. What do I need to change so the MySolution.InteropCtrl can see the app.config file while in VB6?</p>
<p>I'm not 100% sure on this. But I'll throw out some possibilities. First of all, app.config is not the correct name for the file. While it is app.config in your project, it gets auto-renamed to <em>binary</em>.exe.config or <em>binary</em>.dll.config (depending on project type) where <em>binary</em> is the name of the project.</p> <p>Secondly, I'm not 100% sure if dll.config files are always properly loaded and read by .NET when the application loads. I don't believe it happens automatically, and that there is an extra call you have to make to read the config file if its for the dll. If you reneame the config file to match your exe, then it will definitely load and be available to you.</p>
<p>Two options:</p> <p>1) Find your vb.exe path and put your config in there, as VB6.exe.config.</p> <p>2) If you don't need to use the IDE just make your MyApp.exe an put it in your project's folder as MyApp.exe.config, then run the exe and it will find it.</p>
21,200
<p>I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'.</p> <p>It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way. </p> <p>What's the simplest way of doing this?</p> <p>[Edit: Just to avoid confusion in an answer below, this is a <strong>JavaScript</strong> question, not a Java one.]</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var d = new Date(); d.setDate(d.getDate() - 1); console.log(d);</code></pre> </div> </div> </p>
<p><code>setDate(dayValue)</code></p> <p><code>dayValue</code> is an integer from 1 to 31, representing the day of the month.</p> <p>from <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setDate" rel="nofollow noreferrer">https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setDate</a></p> <p>The behaviour solving your problem (and mine) seems to be out of specification range.</p> <p>What seems to be needed are addDate(), addMonth(), addYear() ... functions.</p>
5,190
<p>Any recommendations for a javascript form validation library. I could try and roll my own (but I'm not very good at javascript). Needs to support checking for required fields, and preferably regexp validation of fields.</p>
<p>I am about to start implementing javascript validation in my forms using <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" rel="noreferrer">jQuery Validation</a>. I think that StackOverflow users this jQuery plugin as well. It seems to be a very mature validation library, however it does build on top of jQuery, so it might not fit for you.</p> <p>Like Tom said, don't forget that server side validation.</p>
<p>I've used <a href="http://tetlaw.id.au/view/javascript/really-easy-field-validation" rel="nofollow noreferrer">this library</a> for a couple of personal projects. It's pretty good, though I have had to make my own modifications to it a couple of times - nothing major, though, and it's easy enough to do so.</p> <p>I'm sure you already do this, but also validate all of your information on the server-side, as well. Client-side-only validation is rarely, if ever, a good idea. </p>
3,841
<p>I'm having a bit of trouble with the UTL_MAIL package in Oracle 10g, and was wondering if anyone had any solutions?</p> <p>I connect to my DB as SYSMAN and load the following two scripts;</p> <p><strong>@C:\oracle\product\10.2.0\db_1\rdbms\admin\utlmail.sql</strong></p> <p><strong>@C:\oracle\product\10.2.0\db_1\rdbms\admin\prvtmail.plb</strong></p> <p>I set up the SMTP server;</p> <p><strong>ALTER SYSTEM SET smtp_out_server='mymailserver.fake:25' SCOPE=BOTH;</strong></p> <p>I grant the user the required permission;</p> <p><strong>GRANT execute ON utl_mail TO MYUSER;</strong></p> <p>But then if I connect to the "MYTABLESPACE" (where MYUSER exists), I get the following error if I make reference to UTL_MAIL.SEND;</p> <p><strong>PLS-00201: identifier 'UTL_MAIL.SEND' must be declared</strong></p> <p>If I prefix it with SYSMAN though (SYSMAN.UTL_MAIL.SEND), it works, but I don't want to do this as this procedure that contains this call has no knowledge of the tablespace which installed the scripts.</p> <p>Is there a way to install these scripts so that they are accessible universally, and do not require the SYSMAN prefix to execute?</p> <p>Cheers,</p> <p>Chris</p>
<p>I'm pretty sure that public synonyms will be the only difference.</p> <pre><code>SELECT * FROM ALL_SYNONYMS WHERE OWNER = 'PUBLIC' and table_name LIKE 'UTL%' </code></pre> <p>will confirm or deny</p>
<p>logon as sys and run the scripts</p>
23,963
<p>I'm writing some JavaScript code to parse user-entered functions (for spreadsheet-like functionality). Having parsed the formula I <em>could</em> convert it into JavaScript and run <code>eval()</code> on it to yield the result.</p> <p>However, I've always shied away from using <code>eval()</code> if I can avoid it because it's evil (and, rightly or wrongly, I've always thought it is even more evil in JavaScript, because the code to be evaluated might be changed by the user).</p> <p>So, when it is OK to use it?</p>
<p>I'd like to take a moment to address the premise of your question - that eval() is "<em>evil</em>". The word "<em>evil</em>", as used by programming language people, usually means "dangerous", or more precisely "able to cause lots of harm with a simple-looking command". So, when is it OK to use something dangerous? When you know what the danger is, and when you're taking the appropriate precautions.</p> <p>To the point, let's look at the dangers in the use of eval(). There are probably many small hidden dangers just like everything else, but the two big risks - the reason why eval() is considered evil - are performance and code injection.</p> <ul> <li>Performance - eval() runs the interpreter/compiler. If your code is compiled, then this is a big hit, because you need to call a possibly-heavy compiler in the middle of run-time. However, JavaScript is still mostly an interpreted language, which means that calling eval() is not a big performance hit in the general case (but see my specific remarks below).</li> <li>Code injection - eval() potentially runs a string of code under elevated privileges. For example, a program running as administrator/root would never want to eval() user input, because that input could potentially be "rm -rf /etc/important-file" or worse. Again, JavaScript in a browser doesn't have that problem, because the program is running in the user's own account anyway. Server-side JavaScript could have that problem.</li> </ul> <p>On to your specific case. From what I understand, you're generating the strings yourself, so assuming you're careful not to allow a string like "rm -rf something-important" to be generated, there's no code injection risk (but please remember, it's <em>very very hard</em> to ensure this in the general case). Also, if you're running in the browser then code injection is a pretty minor risk, I believe.</p> <p>As for performance, you'll have to weight that against ease of coding. It is my opinion that if you're parsing the formula, you might as well compute the result during the parse rather than run another parser (the one inside eval()). But it may be easier to code using eval(), and the performance hit will probably be unnoticeable. It looks like eval() in this case is no more evil than any other function that could possibly save you some time.</p>
<p>Only during testing, if possible. Also note that eval() is much slower than other specialized JSON etc. evaluators.</p>
24,070
<p>Is there any way to change the autonumber field to a number datatype, when the field is used a primary key and linked to other tables?</p>
<p>You will have to delete the relationship(s) between the table and any foreign key columns on other tables first. Change the data type and then recreate the relationship(s).</p>
<p>As far as I'm aware there's no way to change this. In Access 2007 it can be changed from Long Integer to Replication ID. In previous versions I don't recall any way of doing this - if I recall correctly it was automatically set to Long Integer but there's no way to control what Access does with the AutoNumber.</p> <p>Edit (question modified): You'll have to drop the relationships with the other tables in order to modify it, once you've dropped the relationship you'll be able to change the type and then recreate the relationship.</p>
45,353