instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>is there anyway to have an image act as an ajax actionlink? I can only get it to work using text. Thanks for your help!</p>
|
<p>From Stephen Walthe, from his <a href="http://www.asp.net/mvc/tutorials/older-versions/contact-manager/iteration-1-create-the-application-cs" rel="noreferrer">Contact manger project</a> </p>
<pre><code> public static class ImageActionLinkHelper
{
public static string ImageActionLink(this AjaxHelper helper, string imageUrl, string altText, string actionName, object routeValues, AjaxOptions ajaxOptions)
{
var builder = new TagBuilder("img");
builder.MergeAttribute("src", imageUrl);
builder.MergeAttribute("alt", altText);
var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions);
return link.Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing));
}
}
</code></pre>
<p>You can now type in your aspx file :</p>
<pre><code><%= Ajax.ImageActionLink("../../Content/Delete.png", "Delete", "Delete", new { id = item.Id }, new AjaxOptions { Confirm = "Delete contact?", HttpMethod = "Delete", UpdateTargetId = "divContactList" })%>
</code></pre>
|
<pre><code>actionName+"/"+routeValues Proje/ControlName/ActionName/Id
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace MithatCanMvc.AjaxHelpers
{
public static class ImageActionLinkHelper
{
public static IHtmlString ImageActionLink(this AjaxHelper helper, string imageUrl, string altText, string actionName, string routeValues, AjaxOptions ajaxOptions)
{
var builder = new TagBuilder("img");
builder.MergeAttribute("src", imageUrl);
builder.MergeAttribute("alt", altText);
var link = helper.ActionLink("[replaceme]", actionName+"/"+routeValues, ajaxOptions).ToHtmlString();
return MvcHtmlString.Create(link.Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing)));
}
}
}
</code></pre>
| 44,410
|
<p>I need to move backwards through an array, so I have code like this:</p>
<pre><code>for (int i = myArray.Length - 1; i >= 0; i--)
{
// Do something
myArray[i] = 42;
}
</code></pre>
<p>Is there a better way of doing this?</p>
<p>Update: I was hoping that maybe C# had some built-in mechanism for this like:</p>
<pre><code>foreachbackwards (int i in myArray)
{
// so easy
}
</code></pre>
|
<p>While admittedly a bit obscure, I would say that the most typographically pleasing way of doing this is</p>
<pre><code>for (int i = myArray.Length; i --> 0; )
{
//do something
}
</code></pre>
|
<p>NOTE: This post ended up being far more detailed and therefore off topic, I apologize.</p>
<p>That being said my peers read it and believe it is valuable 'somewhere'. This thread is not the place. I would appreciate your feedback on where this should go (I am new to the site).</p>
<hr>
<p>Anyway this is the C# version in .NET 3.5 which is amazing in that it works on any collection type using the defined semantics. This is a default measure (reuse!) not performance or CPU cycle minimization in most common dev scenario although that never seems to be what happens in the real world (premature optimization).</p>
<p>*** Extension method working over any collection type and taking an action delegate expecting a single value of the type, all executed over each item in reverse **</p>
<p>Requres 3.5:</p>
<pre><code>public static void PerformOverReversed<T>(this IEnumerable<T> sequenceToReverse, Action<T> doForEachReversed)
{
foreach (var contextItem in sequenceToReverse.Reverse())
doForEachReversed(contextItem);
}
</code></pre>
<p>Older .NET versions or do you want to understand Linq internals better? Read on.. Or not..</p>
<p>ASSUMPTION: In the .NET type system the Array type inherits from the IEnumerable interface (not the generic IEnumerable only IEnumerable).</p>
<p>This is all you need to iterate from beginning to end, however you want to move in the opposite direction. As IEnumerable works on Array of type 'object' any type is valid, </p>
<p>CRITICAL MEASURE: We assume if you can process any sequence in reverse order that is 'better' then only being able to do it on integers. </p>
<p>Solution a for .NET CLR 2.0-3.0:</p>
<p>Description: We will accept any IEnumerable implementing instance with the mandate that each instance it contains is of the same type. So if we recieve an array the entire array contains instances of type X. If any other instances are of a type !=X an exception is thrown:</p>
<p>A singleton service:</p>
<p>public class ReverserService
{
private ReverserService() { }</p>
<pre><code> /// <summary>
/// Most importantly uses yield command for efficiency
/// </summary>
/// <param name="enumerableInstance"></param>
/// <returns></returns>
public static IEnumerable ToReveresed(IEnumerable enumerableInstance)
{
if (enumerableInstance == null)
{
throw new ArgumentNullException("enumerableInstance");
}
// First we need to move forwarad and create a temp
// copy of a type that allows us to move backwards
// We can use ArrayList for this as the concrete
// type
IList reversedEnumerable = new ArrayList();
IEnumerator tempEnumerator = enumerableInstance.GetEnumerator();
while (tempEnumerator.MoveNext())
{
reversedEnumerable.Add(tempEnumerator.Current);
}
// Now we do the standard reverse over this using yield to return
// the result
// NOTE: This is an immutable result by design. That is
// a design goal for this simple question as well as most other set related
// requirements, which is why Linq results are immutable for example
// In fact this is foundational code to understand Linq
for (var i = reversedEnumerable.Count - 1; i >= 0; i--)
{
yield return reversedEnumerable[i];
}
}
}
public static class ExtensionMethods
{
public static IEnumerable ToReveresed(this IEnumerable enumerableInstance)
{
return ReverserService.ToReveresed(enumerableInstance);
}
}
</code></pre>
<p>[TestFixture]
public class Testing123
{</p>
<pre><code> /// <summary>
/// .NET 1.1 CLR
/// </summary>
[Test]
public void Tester_fornet_1_dot_1()
{
const int initialSize = 1000;
// Create the baseline data
int[] myArray = new int[initialSize];
for (var i = 0; i < initialSize; i++)
{
myArray[i] = i + 1;
}
IEnumerable _revered = ReverserService.ToReveresed(myArray);
Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));
}
[Test]
public void tester_why_this_is_good()
{
ArrayList names = new ArrayList();
names.Add("Jim");
names.Add("Bob");
names.Add("Eric");
names.Add("Sam");
IEnumerable _revered = ReverserService.ToReveresed(names);
Assert.IsTrue(TestAndGetResult(_revered).Equals("Sam"));
}
[Test]
public void tester_extension_method()
{
// Extension Methods No Linq (Linq does this for you as I will show)
var enumerableOfInt = Enumerable.Range(1, 1000);
// Use Extension Method - which simply wraps older clr code
IEnumerable _revered = enumerableOfInt.ToReveresed();
Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));
}
[Test]
public void tester_linq_3_dot_5_clr()
{
// Extension Methods No Linq (Linq does this for you as I will show)
IEnumerable enumerableOfInt = Enumerable.Range(1, 1000);
// Reverse is Linq (which is are extension methods off IEnumerable<T>
// Note you must case IEnumerable (non generic) using OfType or Cast
IEnumerable _revered = enumerableOfInt.Cast<int>().Reverse();
Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));
}
[Test]
public void tester_final_and_recommended_colution()
{
var enumerableOfInt = Enumerable.Range(1, 1000);
enumerableOfInt.PerformOverReversed(i => Debug.WriteLine(i));
}
private static object TestAndGetResult(IEnumerable enumerableIn)
{
// IEnumerable x = ReverserService.ToReveresed(names);
Assert.IsTrue(enumerableIn != null);
IEnumerator _test = enumerableIn.GetEnumerator();
// Move to first
Assert.IsTrue(_test.MoveNext());
return _test.Current;
}
}
</code></pre>
| 34,793
|
<p>i remember there being a way of marking a section of code in eclipse (special comment or annotation?) which made the autoformatter ignore that section. Or I may have drempt this...</p>
<p>Used mainly when I have strings which wrap onto several lines and i don't want the autoformatter to rearrange this.</p>
|
<p>Since eclipse 3.5 (or 3.6) this is possible:
- Go to project properties -- Java Code Style -- Formatter -- Edit...
- choose the tab marked "Off/On Tags",
- include the tags in comments in your source code, like</p>
<pre><code>/* @formatter:on */
</code></pre>
|
<p>You can mark the code you want to format and selct format with right mouse click in this section. This is a "whitlist" solution, perhaps it helps...</p>
| 45,918
|
<p>When developing an application wich will be used inside an intranet do you think Silverlight and WCF is a good solution ?</p>
<p>Whould you use WCF Services or WCF Web Services to expose your model to the client ?<br>
<br>When consuming a WCF Service the proxies will be generated under a reference and you can only have 1 service reference per service, How can I have the application domain model created under the same service reference ?</p>
<p>Thanks.
<br>A. Lampard.</p>
|
<p>Not yet. I had a difficult time getting WCF configured, and Silverlight 2 beta was not well documented. </p>
|
<p>Your questions is way too broad. It's really hard to answer these kinds of questions, since, really, "any" technology is good for "any" solution. Otherwise everybody would just use one! </p>
<p>What's your application supposed to do, how soon you need to get it done, is there any existing investment in the same or other technologies...etc.? </p>
<p>Having said that, to answer your question: yes.</p>
<p>Not sure if I understand your second question... not sure why would you want more than one reference per service...?</p>
| 36,526
|
<p>I have a program that, for the most part, operates in the background. Let's say it DoesWork(). Once a week, I want it to notify the user on some of the work it has completed over the past few days. It will be a basic status report, listing some files that have been downloaded.</p>
<p>Initially, I wanted to sent this status update via email, so I looked into that but there are a lot of problems. I need an SMTP server so I looked at GMail. It's okay but has a daily limit of 500 emails, so this wouldn't be suitable for release. Also, there would be issues with the same email account password being given out in each copy of the program, which as I understand it, is a risk even if the password is stored using encryption.</p>
<p>Then I thought maybe I could use the user's own email account to send email to his/her self. This has a couple of complications too: the user would need to specify all of the smtp information for his/her email account, which is too complicated for the target user. Also, I don't want to have to have people entering their email account password into my program just to send emails. I don't think that's a good habit to promote.</p>
<p>Is there any way I could do this via email? Email was my first choice because it's a system of notification that users will already be checking. It's fairly non-intrusive.</p>
<p>Is it necessary to setup my own smtp server? If so, how can I do that?</p>
<p>If email is a no-go, I was also thinking about just generating a local HTML file with the relevent information, and then having a notification popup from the program once a week to inform the user that a new update report is ready. I think this is totally doable, it's just overly instrusive and not my first choice. I want to piggyback on a system that the user is already using.</p>
<p>Thanks!
-greg</p>
|
<p>An alternative is to have the program generate an RSS feed and direct the user how to subscribe to it. Also, once a new update is generated, show the update toast for about a minute, then hide it automatically and change your systray icon to something different. In about a day change it back to the original icon. Also, give the user a setting to turn the toast off permanently.</p>
<p>Relying on email is not a good idea, as you would have to collect the user emails and deal with the privacy issues for that, you would be effectively DOSing any third party SMTP server or would have to invest in the infrastructure for your own.</p>
|
<p>Does it need to be a weekly digest? Instead, how about using <a href="http://growl.info/" rel="nofollow noreferrer">Growl</a> (or equivalent) to notify the user of the tasks being completed in real-time, in the background?</p>
| 31,409
|
<p>Given say 11/13/2008 - 12/11/2008 as the value posted back in TextBox, what would be the best way to parse out the start and end date using C#?</p>
<p>I know I could use:</p>
<pre><code>DateTime startDate = Convert.ToDateTime(TextBoxDateRange.Text.Substring(0, 10));
DateTime endDate = Convert.ToDateTime(TextBoxDateRange.Text.Substring(13, 10));
</code></pre>
<p>Is there a better way?</p>
|
<pre><code>var dates = TextBoxDateRange.Text.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
var startDate = DateTime.Parse(dates[0], CultureInfo.CurrentCulture);
var endDate = DateTime.Parse(dates[1], CultureInfo.CurrentCulture);
</code></pre>
|
<p>Instead of Convert.ToDateTime, it could be worth to use DateTime.Parse and explicitely put in the Culture you desire. If I try that example with any European Culture, i get an Error because 11/13/2008 points to the 11th Day in the 13th Month of 2008...</p>
<pre><code> CultureInfo ci = new CultureInfo("en-us");
var startDate = DateTime.Parse(components[0], ci);
</code></pre>
| 40,147
|
<p>I have an NHibernate Dao..lets call it MyClassDao for want of a better name.</p>
<p>I am writing the following code.</p>
<pre><code>MyClassDao myDao = new MyClassDao();
var values = myDao.GetByCriteria(Restrictions.Eq("Status", someStatusValue));
</code></pre>
<p>I am using this in a Unit Test to pull back values from the database. However, it is taking over 30 seconds to run the test which is too long in my opinion...so what I'd like to do is limit the result set being pulled back...say to about 5 values.</p>
<p>in sql I would do something like the following to to achieve something like this</p>
<pre><code>set rowcount 5
select * from whatever_table
set rowcount 0
</code></pre>
<p>Is there a way...without using the NHibernate Query language to restrict the size of a result set?</p>
|
<p>Use ICriteria.SetMaxResults()</p>
|
<p>I have something like this in my repository to help with the unbound result sets</p>
<pre><code>public IQueryable<T> SelectWithLimit<T>(int maxResults) where T : class
{
ICriteria criteria = SessionWrapper.Session.CreateCriteria(typeof (T)).SetMaxResults(maxResults);
return criteria.List<T>().AsQueryable();
}
</code></pre>
| 49,900
|
<p>If you use Image.Save Method to save an image to a EMF/WMF, you get an exception (<a href="http://msdn.microsoft.com/en-us/library/ktx83wah.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ktx83wah.aspx</a>)</p>
<p>Is there another way to save the image to an EMF/WMF?
Are there any encoders available?</p>
|
<p><code>Image</code> is an abstract class: what you want to do depends on whether you are dealing with a <code>Metafile</code> or a <code>Bitmap</code>.</p>
<p>Creating an image with GDI+ and saving it as an EMF is simple with <code>Metafile</code>. Per Mike's <a href="https://stackoverflow.com/questions/152729/gdi-c-how-to-save-an-image-as-emf/152830#152830">post</a>:</p>
<pre><code>var path = @"c:\foo.emf"
var g = CreateGraphics(); // get a graphics object from your form, or wherever
var img = new Metafile(path, g.GetHdc()); // file is created here
var ig = Graphics.FromImage(img);
// call drawing methods on ig, causing writes to the file
ig.Dispose(); img.Dispose(); g.ReleaseHdc(); g.Dispose();
</code></pre>
<p>This is what you want to do most of the time, since that is what EMF is for: saving vector images in the form of GDI+ drawing commands.</p>
<p>You can save a <code>Bitmap</code> to an EMF file by using the above method and calling <code>ig.DrawImage(your_bitmap)</code>, but be aware that this does not magically covert your raster data into a vector image.</p>
|
<p>It appears there is much confusion over vector vs. bitmap. All of the code in this thread generates bitmap (non-vector) files - it does not preserve the vector GDI calls. To prove this to yourself, download the "EMF Parser" tool and inspect the output files: <a href="http://downloads.zdnet.com/abstract.aspx?docid=749645" rel="nofollow">http://downloads.zdnet.com/abstract.aspx?docid=749645</a>.</p>
<p>This issue has caused many developers considering anguish. Sure would be nice if Microsoft would fix this and properly support their own EMF format.</p>
| 18,428
|
<p>Is it possible Firebug may be incorrectly adding downloads to the Net tab when things may be loaded from the cache?</p>
<p>I have some code in a Javascript gallery which is meant to lazily download an image when the thumbnail is clicked and then display it once downloaded. It is meant to determine if it's been downloaded already first (via an array with Boolean values), and if it has been downloaded before, simply display from cache.</p>
<p>I thought it was working fine for a while (because of the speed at which they would appear when clicked twice), but I recently looked into Firebug's Net tab and it seems to be downloading the large image every time (and the total file size gets bigger with every click).</p>
<p>I'm not sure what I have done wrong as a bit of debugging has informed me the Boolean values are being updated correctly.</p>
<p>So my question is, could Firebug be incorrect (I doubt it), or is there any way I can force it to display from cache (I thought using the exact same path to the image for the image.src would do this)</p>
<p>This was my first venture into objects in Javascript so I'm not 100% confident about my code so please be kind!</p>
|
<p>The image appearing in the net tab in firebug does not mean it is downloaded from the server. Check the HTTP response code that firebug reports for the image - for me after one visit, it kept returning "304 - Not Modified" which means it is being loaded from the cache.</p>
<p>You can avoid the extra HTTP request that checks if the cache is still fresh by sending<a href="http://www.askapache.com/htaccess/apache-speed-expires.html" rel="nofollow noreferrer">far-future headers</a> for components you want to cache hard. Bear in mind though, that in order to force the client to re-download a component that was cached this way you'll have to change the filename.</p>
|
<p>I checked your site and using CacheViewer confirmed that it is indeed caching it and fetching it from disk, with an expiration one month from today. If you want you could also use plsicing by combining all the images into one large image and only show the area of interest, although I typically use splicing for small images, like paging icons, etc. ANyway, your site looks great and like the way you delay loading the large images.</p>
| 45,807
|
<p>I've be working with a Java application run through the command-line. It deals with XML files, specially the dblp.xml database which has more than 400MB. </p>
<p>I was using JVM 5 and my app needed sort of 600-700MB of memory to processe the dblp.xml. After updating to JVM 6, it starting needing more than 1gb of memory (something I don't have), although it runs a bit faster.</p>
<p>I'm pretty sure of the memory consumption difference, because I've already tested both again and again in this same computer. Resulting in the same difference of memory consumption.</p>
<p>I didn't set any special parameters, just -Xmx800M or -Xmx1000M.
Running with Ubuntu Hardy Heron on a dual core 1.7ghz, with 1,5gb of memory
Using only the top/ps commands to measure</p>
<p>Any one have an idea why this occurs? I really wanted to use JVM 6, because in my production server it is the JVM in use, and I'm not quite able to change easily.</p>
<p>Thanks</p>
|
<p>My advice would be to use a tool like <a href="http://www.ej-technologies.com/products/jprofiler/overview.html" rel="nofollow noreferrer">JProfiler</a> to try to get a handle on exactly where your memory consumption increased. If you can't spend on JProfiler, check out this list of <a href="http://java-source.net/open-source/profilers" rel="nofollow noreferrer">open source java profiling tools</a>.</p>
<p>Guessing at the cause of performance problems is a bad idea, because you are almost always wrong in your guess, and you waste time optimizing the wrong piece of the system. Once you have some objective data, you may be able to come up with an optimization reducing your memory consumption.</p>
<p>If it is true that the newer JVM is trading memory for speed (by caching) then there is likely a jvm arg you can use to stop this behavior. Best bet is to check out the release notes for Java 6 and see if any such feature is mentioned.</p>
|
<p>sounds like the newer JVM is trading memory space for speed (ie, caching or what not)?</p>
| 41,309
|
<p>I am trying to hide some divs before the user prints this giant form, then display the divs again afterward. Thus I want to ignore the rest of the page, and only print the form itself.</p>
<p>Sure I <em>could</em> open a separate page when the user clicks the print button. The only thing is that the form is really long and it would be quite tedious to do that.</p>
<p><br>
Edit: My previous question did not actually reflect what I was looking for. So I changed it to the current one.</p>
<p>Also thanks to all that suggested window.onbeforeprint and window.onafterprint. That was relevant to my edited question.</p>
|
<h2>First, The Ok Way:</h2>
<p>Take a look at window.onbeforeprint and window.onafterprint (the original question asked about how to do it programmatically I believe). </p>
<h2>Now, the Better Way:</h2>
<p>A better way to do this is with a style that is specifically for printing. In other words, your div might look like this:</p>
<pre><code><div class="someClass noPrint">My Info</div>
</code></pre>
<p>You would then have this in your stylesheet:</p>
<pre><code>.someClass {font-family:arial;}
@media print {
.noPrint { display: none; }
}
</code></pre>
<h2>Another Option</h2>
<p>You could also put this in a separate stylesheet if you wanted so you don't have to mix styles:</p>
<pre><code><link rel="stylesheet" type="text/css" media="print" href="print.css">
</code></pre>
<p>Your screen stylesheet could have ".someClass" defined one way and then your print stylesheet could have it defined a completely different way.</p>
|
<p>You may want to consider creating a style sheet specifically for printing using <a href="http://www.alistapart.com/stories/goingtoprint/" rel="nofollow noreferrer">media="print"</a></p>
| 27,683
|
<p>Let's say I have a table that represents a super class, <strong>students</strong>. And then I have N tables that represent subclasses of that object (<strong>athletes</strong>, <strong>musicians</strong>, etc). How can I express a constraint such that a student must be modeled in one (not more, not less) subclass?</p>
<p>Clarifications regarding comments:</p>
<ul>
<li>This is being maintained manually, not through an ORM package.</li>
<li>The project this relates to sits atop SQL Server (but it would be nice to see a generic solution)</li>
<li>This may not have been the best example. There are a couple scenarios we can consider regarding subclassing, and I just happened to invent this student/athlete example.</li>
</ul>
<p>A) In true object-oriented fashion, it's possible that the superclass can exist by itself and need not be modeled in any subclasses.</p>
<p>B) In real life, any object or student can have multiple roles.</p>
<p>C) The particular scenario I was trying to illustrate was requiring that every object be implemented in exactly one subclass. Think of the superclass as an abstract implementation, or just commonalities factored out of otherwise disparate object classes/instances.</p>
<p>Thanks to all for your input, especially Bill.</p>
|
<p>Here are a couple of possibilities. One is a <code>CHECK</code> in each table that the <code>student_id</code> does not appear in any of the other sister subtype tables. This is probably expensive and every time you need a new subtype, you need to modify the constraint in all the existing tables.</p>
<pre><code>CREATE TABLE athletes (
student_id INT NOT NULL PRIMARY KEY,
FOREIGN KEY (student_id) REFERENCES students(student_id),
CHECK (student_id NOT IN (SELECT student_id FROM musicians
UNION SELECT student_id FROM slackers
UNION ...))
);
</code></pre>
<p><strong>edit:</strong> @JackPDouglas correctly points out that the above form of CHECK constraint is not supported by Microsoft SQL Server. Nor, in fact, is it valid per the SQL-99 standard to reference another table (see <a href="http://kb.askmonty.org/v/constraint_type-check-constraint" rel="nofollow noreferrer">http://kb.askmonty.org/v/constraint_type-check-constraint</a>).</p>
<p>SQL-99 defines a metadata object for multi-table constraints. This is called an <em>ASSERTION</em>, however I don't know any RDBMS that implements assertions.</p>
<p>Probably a better way is to make the primary key in the <code>students</code> table a compound primary key, the second column denotes a subtype. Then restrict that column in each child table to a single value corresponding to the subtype represented by the table. <strong>edit:</strong> no need to make the PK a compound key in child tables.</p>
<pre><code>CREATE TABLE athletes (
student_id INT NOT NULL PRIMARY KEY,
student_type CHAR(4) NOT NULL CHECK (student_type = 'ATHL'),
FOREIGN KEY (student_id, student_type) REFERENCES students(student_id, student_type)
);
</code></pre>
<p>Of course <code>student_type</code> could just as easily be an integer, I'm just showing it as a char for illustration purposes.</p>
<p>If you don't have support for <code>CHECK</code> constraints (e.g. MySQL), then you can do something similar in a trigger.</p>
<p>I read your followup about making sure a row exists in <em>some</em> subclass table for every row in the superclass table. I don't think there's a practical way to do this with SQL metadata and constraints. The only option I can suggest to meet this requirement is to use <a href="http://martinfowler.com/eaaCatalog/singleTableInheritance.html" rel="nofollow noreferrer">Single-Table Inheritance</a>. Otherwise you need to rely on application code to enforce it.</p>
<p><strong>edit:</strong> JackPDouglas also suggests using a design based on <a href="http://www.martinfowler.com/eaaCatalog/classTableInheritance.html" rel="nofollow noreferrer">Class Table Inheritance</a>. See <a href="https://stackoverflow.com/questions/5522320/what-is-the-best-way-to-enforce-a-subset-relationship-with-integrity-constraint/5522344#5522344">his example</a> or my examples of the similar technique <a href="https://stackoverflow.com/questions/987654/in-a-stackoverflow-clone-what-relationship-should-a-comments-table-have-to-quest/987709#987709">here</a> or <a href="https://stackoverflow.com/questions/1408556/is-it-possible-to-constrain-a-table-to-have-a-value-in-only-one-of-a-set-of-colum/1408592#1408592">here</a> or <a href="https://stackoverflow.com/questions/3349838/should-i-add-a-type-column-to-design-inheritance-in-postgresql/3349962#3349962">here</a>.</p>
|
<p>interesting problem. Of course the FK constraints are there for the subtables so there has to be a student for those. </p>
<p>The main problem is trying to check as it is inserted. The student has to be inserted first so that you don't violate a FK constraint in a subtable so a trigger that does a check wouldn't work.</p>
<p>You could write an app that checks now and then if you are really concerned about this. I think the biggest fear though would be deletions. Someone could delete a subtable entry but not the student. You could have triggers to check when items are deleted from the subtables since that is probably the biggest problem.</p>
<p>I have a db with a table per subclass hierarchy like this as well. I use Hibernate and its mapped properly so it deletes everything automatically. If doing this by 'hand' then I would make sure to always delete the parent with proper cascades hehe :)</p>
| 43,093
|
<p>The scenario</p>
<ul>
<li>You have developed a webapp using EJBs version 3.</li>
<li>The system is deployed, delivered and is used by the customer.</li>
</ul>
<p>If you would have to rewrite the system from scratch, would you use EJBs again?</p>
<p><strong>Yes</strong>: Don't answer this question, answer <a href="https://stackoverflow.com/questions/105544/most-important-problem-solved-by-ejb-3">this one</a> instead.</p>
<p><strong>No</strong>: Provide the top reason for not using EJBs again, based on your personal experience.</p>
<p>Let the answer contain just <strong>one</strong> reason. This will let other readers vote up the number one reason to stay away from EJB 3.</p>
|
<p>The project did not have any of the problems that EJBs are supposed to solve. Using EJBs just made it harder to code, to debug, to build, to deploy and to document and understand.</p>
|
<p>Having to do relationship-child management yourself: Hibernate's all-delete-orphan didn't make it into the 3.0 spec.</p>
| 19,500
|
<p>I have been a .net developer for the past three yrs. Just curious to know about the network security field. What kind of work does the developers working in these area do? I really have not much idea about network security but what my understanding is these people are involved in securing network, preventing attacks on network as obvious. Could any one please give me some details about this field and also what does it take to move to this field.</p>
|
<p>Basic questions include:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/479142/when-to-use-an-interface-instead-of-an-abstract-class-and-vice-versa">Whats the difference between an abstract class and interface? When would you want to use them?</a></li>
<li><a href="https://stackoverflow.com/questions/448023/what-is-the-difference-between-left-right-outer-and-inner-joins">What's the difference between a left join and an inner join?</a></li>
<li><a href="https://stackoverflow.com/questions/733482/what-is-the-difference-between-sessionstate-and-viewstate">What's the difference between viewstate and sessionstate?</a></li>
<li>What's the difference between overriding and overloading a method? Explain how both are done.</li>
<li>What's the difference between protected and internal? What about "protected internal"?</li>
<li>How do short-circuited operators work?</li>
<li>Explain what the StringBuilder class is and why you'd want to use it?</li>
<li>What's the difference between a static method and a non-static method?</li>
<li>What does the "volatile" keyword in C# mean?</li>
<li>Explain what happens when you pass a "ref" or "out" parameter into a method. <a href="https://stackoverflow.com/questions/135234/difference-between-ref-and-out-parameters-in-net">What's the difference between those two keywords</a>?</li>
<li>What's a weakreference? When would you want to use one?</li>
<li>What's the difference between a DataTable and a DataReader?</li>
<li>What's the difference between a value-type and a reference type?</li>
<li>What does the "readonly" keyword in C# mean?</li>
</ul>
<p>I think it usually helps to ask your applicants to complete a simple coding exercise such as:</p>
<ul>
<li>Write your own linked list class without using the built-in classes.</li>
<li>Write your own hashtable class without using the built-in classes.</li>
<li>Write a class that represents a binary tree. Write a method that traverses all nodes of the tree.</li>
<li>Write a method to perform a binary search on an array without using built-in methods.</li>
<li>Draw a database schema for a blog. Each user only has one blog, each blog has many categories, each category has many posts, and each post can belong to more than one category. Ask your applicant to write queries to pull specific information out.</li>
</ul>
<p>Next, look for specific technical know-how:</p>
<ul>
<li>(Event handlers) Create a class with a custom event handler, create another class which hooks onto the custom event handler.</li>
<li>(XML) Load an XML document and select all of the nodes with properties x, y, and z.</li>
<li>(Functional programming) Create a function that accepts another function as a parameter. A Map or Fold function works really good for this.</li>
<li>(Reflection) Write a function which determines if a class has a particular attribute.</li>
<li>(Regex) Write a regular expression which removes all tags from a block of HTML.</li>
</ul>
<p>None of these are particularly difficult questions for a proficient C# programmer to answer, and they should give you a good idea of your applicants particular strengths. You may also want to work in a few questions/code sample that make use of specific design patterns.</p>
<p><strong>[Edit for clarification]</strong>: </p>
<p>Seems that a lot of people don't understand why I'd ask these types of questions. Let me touch on a few peoples comments (I'm not quoting directly, but paraphrasing instead):</p>
<hr>
<p><strong>Q:</strong> When was the last time anyone used volatiles or weak references?</p>
<p><strong>A:</strong> When I give technical interviews, I look to see whether a person understands the high-level <em>and</em> low-level features of .NET. Volatiles and weak references are two low-level features provided by .NET -- even if these features aren't used often in practice, answers to these questions are extremely revealing:</p>
<ul>
<li><p>A good understanding of volatiles demonstrates that a person understands how compiler optimizations change the correctness of code, how threads keep local copies of shared state which may be out of sync at any given time, and is minimally aware of some of the complexities of multithreaded code.</p></li>
<li><p>A good understanding of weak references demonstrates that a person knows about the intimate details of the garbage collector and how it decides when to free memory. Sure, you could ask candidates "how does a garbage collector work", but asking about weak references gets a much better, more thoughtful reply.</p></li>
</ul>
<p>.NET is a fairly abstract language, but star developers almost always have a deep understanding of the CLR and the low-level details of .NET's runtime.</p>
<hr>
<p><strong>Q:</strong> Why would anyone need to implement their own hashtable or linked list?</p>
<p><strong>A:</strong> I'm not implying that the Dictionary class is inferior or that people should roll their own hashtable. This is a basic question which tests whether a person has a <em>minimal</em> understanding of datastructures. Thats what these questions test for: bare minimum understanding.</p>
<p>You learn about these hashtables and linked lists on the first day of Data Structures 101. If someone can't write a hashtable or a linked list from scratch, then they have a <em>huge</em> gap in their technical knowledge.</p>
<hr>
<p><strong>Q:</strong> Why are these questions so crud-oriented?</p>
<p><strong>A:</strong> Because the title of this thread is "questions every good .NET developer should know". Every .NET developer begins their career writing crud apps, and 90% of all application development people do for a living is concerned with line-of-business applications.</p>
<p>I think questions testing a persons knowledge of line-of-business apps are appropriate in most cases, unless you're looking for developers in very specific niches, such as compiler development, game-engine development, theorem-proving, image processing, etc.</p>
|
<p>I would prefer giving him a problem and asking him to solve it using the features of .net you know and why do you think it is best solution.</p>
<p>This will crack almost all the capabilities of a candidate in terms of technical, analytical and problem solving skills along with his approach for solving a problem.</p>
| 47,720
|
<p>Has anyone else had any problems using google's Domain Tracking API, I am specifically talking about the _link() method.</p>
<p><a href="http://code.google.com/apis/analytics/docs/gaJS/gaJSApiDomainDirectory.html#_gat.GA_Tracker_._link" rel="nofollow noreferrer">The documentation is here</a></p>
<p>The example provided shows that the _link() method should be used in the onclick event like this:</p>
<pre><code><a href="http://www.newsite.com" onclick="pageTracker._link('http://www.newsite.com');return false;">Go to our sister site</a>
</code></pre>
<p>However, this essentially just makes the link...do nothing (most probably because of the 'return false').</p>
<p>My understanding is that the pageTracker._link() method is 'supposed' to add additional parameters to the url and do it's own document.location style redirect.</p>
<p>Any ideas / catches / previous posts??</p>
|
<p>You should ensure that you are using the correct version of <code>svnadmin</code> for your repository version. It's possible to get errors like this by using the wrong version.</p>
<p>Having said that, version 1.3.x is pretty old now and you should consider upgrading to the latest 1.5.x.</p>
<p>I also found through google that <a href="http://www.nabble.com/Re:-svn:-Invalid-diff-stream:-insn-0-cannot-be-decoded-p17756765.html" rel="nofollow noreferrer">some versions of SVNKit</a> can cause this problem.</p>
|
<p>You should ensure that you are using the correct version of <code>svnadmin</code> for your repository version. It's possible to get errors like this by using the wrong version.</p>
<p>Having said that, version 1.3.x is pretty old now and you should consider upgrading to the latest 1.5.x.</p>
<p>I also found through google that <a href="http://www.nabble.com/Re:-svn:-Invalid-diff-stream:-insn-0-cannot-be-decoded-p17756765.html" rel="nofollow noreferrer">some versions of SVNKit</a> can cause this problem.</p>
| 30,428
|
<p>I have a list of images that i’ve loaded with the Loader class, but I’m having a tough time assigning them unique names.
I need unique names because I want to remove certain images after a while.
Is there a way to assign loaders a name or some unique tag so i can remove them later? thanks.</p>
<p>Here's part of my code</p>
<pre><code>for (var i = startnum; i < endnum; i++){
var thumb = panels[i].@THUMB;
var thumb_loader = new Loader();
thumb_loader.load(new URLRequest(thumb));
thumb_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbLoaded);
thumb_loader.name = i;
thumb_loader.x = (thumb_width + 20)*i;
}
</code></pre>
<p>I tried to use getChildByName in another function..</p>
<pre><code>var myLoader:Loader = getChildByName( "1" ) as Loader;
myLoader.unload();
</code></pre>
<p>But it's giving me
Error #1009: Cannot access a property or method of a null object reference.</p>
<p>I tried to put thumb_loader as global variable, and do this</p>
<pre><code>var myLoader:Loader = thumb_loader.getChildByName( "1" ) as Loader;
</code></pre>
<p>But it's still not working.
Thanks.</p>
|
<p>All display objects in ActionScript 3 have a name property. Whenever you create a Loader object you can assign a name to it like so:</p>
<pre><code>var myLoader:Loader = new Loader();
myLoader.name = "myUniqueName";
myLoader.load( .... );
addChild( myLoader );
</code></pre>
<p>If you'd like to refer to the loader by the name you gave it, use the getChildByName() method.</p>
<pre><code>var myLoader:Loader = getChildByName( "myUniqueName" ) as Loader;
myLoader.unload();
</code></pre>
<p>Please be mindful that getChildByName() will only work after you've added the Loader(s) to the display list using addChild(). Otherwise, you'll have to create something to store the references to the Loader objects in, such as an Array and refer to the loaders via that Array. For example, outside your loop you could create an Array named loadersArr. In your loop you would do: </p>
<pre><code>loadersArr["uniqueName"] = thumb_loader;
</code></pre>
<p>Then you can refer to your loaders with your unique name through the loadersArr Array.</p>
<pre><code>var loaderToUnload:Loader = loadersArr["uniqueName"];
loaderToUnload.unload();
</code></pre>
<p>Without seeing more of your code, its difficult to understand the scope in which this code resides and where any other code that may try to reference these Loaders resides.</p>
|
<p>Not sure I 100% understand your problem, but why not put them in an object map rather than a list and generate unique names for them if you don't have them...</p>
<pre><code>var img:Image;
var img_map:Object = new Object();
var last_added:int = 0;
for each (img in yourListOfImages)
{
img_map["img_"+last_added] = img;
last_added++;
}
</code></pre>
<p>Depending on your environment (Flex or Flash) you can use a UID generator instead of my simplistic unique names above.</p>
| 40,570
|
<p>What I want to do is patch an existing Python module that uses urllib2 to run on App Engine, but I don't want to break it so it can be used elsewhere. So I'm looking for a quick solution to test if the module is imported in the App Engine environment or not. Catching ImportError on urllib2 might not be the best solution.</p>
|
<p>You could simply use sys.modules to test if a module has been imported (I'm using unicodedata as an example):</p>
<pre><code>>>> import sys
>>> 'unicodedata' in sys.modules
False
>>> import unicodedata
>>> 'unicodedata' in sys.modules
True
</code></pre>
|
<p>You could do a simple check against key environment variables. No telling exactly how reliable this might be, though.</p>
<pre><code>import os, logging
try:
os.environ['APPENGINE_RUNTIME']
except KeyError:
logging.warn('We are not in App Engine environment')
else:
logging.info('We are in the App Engine environment')
</code></pre>
<p>You can also <a href="https://developers.google.com/appengine/docs/python/config/appconfig#Defining_Environment_Variables" rel="nofollow">define your own custom environment variable in your App Engine configuration file</a> and that will be viewable from <code>os.environ</code> within any module. So, type something like this in your app.yaml file:</p>
<pre><code>env_variables:
MY_APP_ENGINE_ENVIRONMENT: '982844ed9cbd6ce42318d2804386be29cbc7c35a'
</code></pre>
<p>... will give you an unambiguous ID to reference.</p>
<p>From the development server, here are the environment variables that I get:</p>
<pre><code>{'USER_EMAIL': '',
'DATACENTER': 'us1',
'wsgi.version': (1, 0),
'REQUEST_ID_HASH': 'E2C19D51',
'SERVER_NAME': 'mydesktop',
'QUERY_STRING': '',
'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'APPENGINE_RUNTIME': 'python27',
'wsgi.input': <cStringIO.StringI object at 0x2f145d0>,
'SERVER_PROTOCOL': 'HTTP/1.1',
'HTTPS': 'off',
'USER_IS_ADMIN': '0',
'TZ': 'UTC',
'REMOTE_ADDR': '192.168.0.2',
'HTTP_X_APPENGINE_COUNTRY': 'ZZ',
'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',
'SERVER_SOFTWARE': 'Development/2.0',
'HTTP_CACHE_CONTROL': 'max-age=0',
'DEFAULT_VERSION_HOSTNAME': 'mydesktop:8080',
'SERVER_PORT': '8080',
'wsgi.run_once': False,
'REQUEST_METHOD': 'GET',
'USER_ID': '',
'AUTH_DOMAIN': 'gmail.com',
'USER_NICKNAME': '',
'USER_ORGANIZATION': '',
'wsgi.multiprocess': True,
'INSTANCE_ID': '8a8e02e6efa8d195346ae0c90cfeafce8aa2',
'PATH_INFO': '/',
'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8',
'HTTP_HOST': 'mydesktop:8080',
'wsgi.errors': <google.appengine.api.logservice.logservice.LogsBuffer object at 0x2f09c30>,
'APPLICATION_ID': 'dev~myapp',
'wsgi.multithread': True,
'CURRENT_VERSION_ID': 'version-1',
'SCRIPT_NAME': '',
'REQUEST_LOG_ID': '4eafbc91ca4ebd5fee53f19eeab2eb26d243d9ddc92b6b9bc0a063eabdc84cfff',
'wsgi.url_scheme': 'http'}
</code></pre>
<p>Hope that helps.</p>
| 43,499
|
<p>The requirements for my document management system were:</p>
<ol>
<li>Must be secure from theft by simple copying of directories, files etc.</li>
<li>Must be secure against traditional virus infection (infection of physical file)</li>
<li>Must be fast to retrieve</li>
<li>The repository must not be visible to casual (directory) browsing users etc.</li>
</ol>
<p>I have decided to store all documents (and scanned images) as blobs in the database and so far my experience is wonderful and document retrieval is blindingly fast as well - it meets all the criteria from above and there are even a couple of additional advantages, such as autostoring documents together with the entity it relates to, easy and fast seaching of contents, removing of all sorts of user activities around opening and naming of documents etc. etc.</p>
<p>My question is - are there any serious risks or things that I overlooked with this design and implementation?</p>
<p>EDIT Note: DB is PostgreSQL, handles BLOBS very well and scales exceptionally well. The environment is Multi-user.</p>
|
<p>When your DB grows bigger and bigger it will become harder to backup.
Restoring a backup of a table with over 100 GB of data is not something that makes you happy.</p>
<p>Another thing that get is that all the table management functions get slower and slower as the dataset grows.<br>
But this can be overcome by making your data table just contain 2 fields:
ID and BLOB.</p>
<p>Retrieving data (by primary key) will likely only become a problem long after you hit a wall with backing up the dataset.</p>
|
<p>Sorry - the answer I offered was based on SQL Server, so the maintenance portion is not appropriate. But file I/O is accomplished at the hardware level and any database adds extra processing steps.</p>
<p>The database will impose extra overhead when retrieving the document. When the file is on disk you are only as slow or as fast as the I/O on the server. You certainly should manage your meta in a database, but in the end you want the UNC of the file and point the user to
the source and get out of the way.</p>
<p>From a maintenance and administration perspective you will limit yourself to a SAN when dealing with MS SQL Server. Solutions like Documentum take a different approach with simple storage on the disk and allows you to implement a storage solution as you see fit.</p>
<p><strong>EDIT</strong></p>
<p>Let me clarify my statement - with SQL Server you have limited options when you exceed the physical storage capacity of the box. This is in fact one of the big weaknesses of Sharepoint that you are not able to simply attach any type of network storage.</p>
| 26,046
|
<p>So I'm refactoring my code to implement more OOP. I set up a class to hold page attributes.</p>
<pre><code>class PageAtrributes
{
private $db_connection;
private $page_title;
public function __construct($db_connection)
{
$this->db_connection = $db_connection;
$this->page_title = '';
}
public function get_page_title()
{
return $this->page_title;
}
public function set_page_title($page_title)
{
$this->page_title = $page_title;
}
}
</code></pre>
<p>Later on I call the set_page_title() function like so</p>
<pre><code>function page_properties($objPortal) {
$objPage->set_page_title($myrow['title']);
}
</code></pre>
<p>When I do I receive the error message:</p>
<blockquote>
<p>Call to a member function set_page_title() on a non-object</p>
</blockquote>
<p>So what am I missing?</p>
|
<p>It means that <code>$objPage</code> is not an instance of an object. Can we see the code you used to initialize the variable?</p>
<p>As you expect a specific object type, you can also make use of <a href="http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration" rel="noreferrer">PHPs type-hinting feature<sup><em>Docs</em></sup></a> to get the error when your logic is violated:</p>
<pre><code>function page_properties(PageAtrributes $objPortal) {
...
$objPage->set_page_title($myrow['title']);
}
</code></pre>
<p>This function will only accept <code>PageAtrributes</code> for the first parameter.</p>
|
<p>I realized that I wasn't passing <strong>$objPage</strong> into <strong>page_properties()</strong>. It works fine now.</p>
| 7,817
|
<p>Like this: const void * test = sqlite3_column_blob(stat, 1);
Can I delete or delete[] test?</p>
|
<p>From the <a href="http://www.sqlite.org/c3ref/column_blob.html" rel="noreferrer">sqllite documentation</a>:</p>
<blockquote>
<p>The pointers returned are valid until a type conversion occurs or until sqlite3_step() or sqlite3_reset() or sqlite3_finalize() is called. The memory space used to hold strings and BLOBs is freed automatically. <strong>Do not pass the pointers returned by sqlite3_column_blob() into sqlite3_free().</strong></p>
</blockquote>
|
<p>Look at its API Manual. If it is a C API, you probably have to <code>free</code> it. If it doesn't provide its own function like sqlite3_free (pcre does this for example), you have to use that function.</p>
<p>What you can't do is delete it using C++'s delete operator, since you have got a void pointer. You cannot delete a void pointer, since the compiler has to know about its type. (and void is an incomplete type. you can't delete incomplete types either).</p>
| 42,098
|
<p>Is it possible to serialize and deserialize a class in C++?</p>
<p>I've been using Java for 3 years now, and serialization / deserialization is fairly trivial in that language. Does C++ have similar features? Are there native libraries that handle serialization?</p>
<p>An example would be helpful.</p>
|
<p>The <a href="http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/index.html" rel="noreferrer"><code>Boost::serialization</code></a> library handles this rather elegantly. I've used it in several projects. There's an example program, showing how to use it, <a href="http://www.boost.org/doc/libs/1_36_0/libs/serialization/example/demo.cpp" rel="noreferrer">here</a>.</p>
<p>The only native way to do it is to use streams. That's essentially all the <code>Boost::serialization</code> library does, it extends the stream method by setting up a framework to write objects to a text-like format and read them from the same format. </p>
<p>For built-in types, or your own types with <code>operator<<</code> and <code>operator>></code> properly defined, that's fairly simple; see <a href="https://isocpp.org/wiki/faq/serialization#serialize-simple-types" rel="noreferrer">the C++ FAQ</a> for more information.</p>
|
<p>Here is a simple serializer library I knocked up. It's header only, c11 and
has examples for serializing basic types. Here's one for a map to class.</p>
<p><a href="https://github.com/goblinhack/simple-c-plus-plus-serializer" rel="nofollow noreferrer">https://github.com/goblinhack/simple-c-plus-plus-serializer</a></p>
<pre><code>#include "c_plus_plus_serializer.h"
class Custom {
public:
int a;
std::string b;
std::vector c;
friend std::ostream& operator<<(std::ostream &out,
Bits my)
{
out << bits(my.t.a) << bits(my.t.b) << bits(my.t.c);
return (out);
}
friend std::istream& operator>>(std::istream &in,
Bits my)
{
in >> bits(my.t.a) >> bits(my.t.b) >> bits(my.t.c);
return (in);
}
friend std::ostream& operator<<(std::ostream &out,
class Custom &my)
{
out << "a:" << my.a << " b:" << my.b;
out << " c:[" << my.c.size() << " elems]:";
for (auto v : my.c) {
out << v << " ";
}
out << std::endl;
return (out);
}
};
static void save_map_key_string_value_custom (const std::string filename)
{
std::cout << "save to " << filename << std::endl;
std::ofstream out(filename, std::ios::binary );
std::map< std::string, class Custom > m;
auto c1 = Custom();
c1.a = 1;
c1.b = "hello";
std::initializer_list L1 = {"vec-elem1", "vec-elem2"};
std::vector l1(L1);
c1.c = l1;
auto c2 = Custom();
c2.a = 2;
c2.b = "there";
std::initializer_list L2 = {"vec-elem3", "vec-elem4"};
std::vector l2(L2);
c2.c = l2;
m.insert(std::make_pair(std::string("key1"), c1));
m.insert(std::make_pair(std::string("key2"), c2));
out << bits(m);
}
static void load_map_key_string_value_custom (const std::string filename)
{
std::cout << "read from " << filename << std::endl;
std::ifstream in(filename);
std::map< std::string, class Custom > m;
in >> bits(m);
std::cout << std::endl;
std::cout << "m = " << m.size() << " list-elems { " << std::endl;
for (auto i : m) {
std::cout << " [" << i.first << "] = " << i.second;
}
std::cout << "}" << std::endl;
}
void map_custom_class_example (void)
{
std::cout << "map key string, value class" << std::endl;
std::cout << "============================" << std::endl;
save_map_key_string_value_custom(std::string("map_of_custom_class.bin"));
load_map_key_string_value_custom(std::string("map_of_custom_class.bin"));
std::cout << std::endl;
}
</code></pre>
<p>Output:</p>
<pre><code>map key string, value class
============================
save to map_of_custom_class.bin
read from map_of_custom_class.bin
m = 2 list-elems {
[key1] = a:1 b:hello c:[2 elems]:vec-elem1 vec-elem2
[key2] = a:2 b:there c:[2 elems]:vec-elem3 vec-elem4
}
</code></pre>
| 29,053
|
<p>Suppose you have:</p>
<pre><code>A-B-C
</code></pre>
<p>Now your build/test fails. The fix should be merged in A.
My current work-flow is like this:</p>
<pre><code>$ git commit -m "fixA"
A-B-C-fixA
$ git rebase -i A~1
</code></pre>
<p>And squash fixA in A, result in: </p>
<pre><code>A'-B-C
</code></pre>
<p>Is there a command to do something like:</p>
<pre><code>A-B-C + (index with fix for A)
$ git commit -supperdupper A
</code></pre>
<p>Result:</p>
<pre><code>A'-B-C
</code></pre>
|
<p><em>If you're just looking for the easy solution for fixing up earlier commits, read the question! It explains it all. But since Elmarco was asking for a slick way, here we go:</em></p>
<p>As of Git 1.7.0, there is an <code>--autosquash</code> option for <a href="https://www.kernel.org/pub/software/scm/git/docs/git-rebase.html" rel="nofollow"><code>rebase</code></a>, which does what you want. There is also the <code>--fixup</code> and <code>--squash</code> options for <a href="https://www.kernel.org/pub/software/scm/git/docs/git-commit.html" rel="nofollow"><code>commit</code></a> to make things easier. With some aliasing you can probably even get the whole thing into a single command.</p>
<p>I'd suggest upgrading to the newest Git for maximum awesomeness:</p>
<pre><code>git/Documentation/RelNotes $ grep -i -A1 autosquash\\\|fixup *
1.7.0.txt: * "git rebase -i" learned new action "fixup" that squashes the change
1.7.0.txt- but does not affect existing log message.
--
1.7.0.txt: * "git rebase -i" also learned --autosquash option that is useful
1.7.0.txt: together with the new "fixup" action.
1.7.0.txt-
--
1.7.3.txt: * "git rebase -i" peeks into rebase.autosquash configuration and acts as
1.7.3.txt: if you gave --autosquash from the command line.
1.7.3.txt-
--
1.7.4.txt: * "git commit" learned --fixup and --squash options to help later invocation
1.7.4.txt- of the interactive rebase.
--
1.7.4.txt: * "git rebase --autosquash" can use SHA-1 object names to name which
1.7.4.txt: commit to fix up (e.g. "fixup! e83c5163").
1.7.4.txt-
</code></pre>
|
<p>I think the root of the problem is that git (and version control generally) forces you to think in terms of sequences of changes, but a changeset or feature-branch or whatever you call a cohesive group of related changes is in general not logically sequential. The order in which the code was written is incidental and not necessarily related to the order in which it should be read.</p>
<p>I don't have a solution to that, but I have written a <a href="https://gist.github.com/oktal3700/cafe086b49c89f814be4a7507a32a3f7" rel="nofollow">Perl script</a> to help automate the process of rewriting history. It's similar to the Python script of @MikaEloranta which I hadn't seen when I wrote it.</p>
<p><code>commit --fixup</code> and <code>rebase --autosquash</code> are great, but they don't do enough. When I have a sequence of commits <code>A-B-C</code> and I write some more changes in my working tree which belong in one or more of those existing commits, I have to manually look at the history, decide which changes belong in which commits, stage them and create the <code>fixup!</code> commits. But git already has access to enough information to be able to do all that for me.</p>
<p>For each hunk in <code>git diff</code> the script uses <code>git blame</code> to find the commit that last touched the relevant lines, and calls <code>git commit --fixup</code> to write the appropriate <code>fixup!</code> commits, essentially doing the same thing I was doing manually before.</p>
<p>If the script can't resolve a hunk to a single, unambiguous commit, it will report it as a failed hunk and you'll have to fall back to the manual approach for that one. If you changed a line twice in two separate commits, the script will resolve a change on that line to the most recent of those commits, which might not always be the correct resolution. IMHO in a "normal form" feature branch you shouldn't be changing a line twice in two different commits, each commit should be presenting the final version of the lines that it touches, to help the reviewer(s). However, it can happen in a bugfix branch, to contrive an example the line <code>foo(bar());</code> could be touched by commit A (rename <code>foo</code> to <code>fox</code>) and commit B (rename <code>bar</code> to <code>baz</code>).</p>
<p>If you find the script useful, please feel free to improve and iterate on it and maybe one day we'll get such a feature in <code>git</code> proper. I'd love to see a tool that can understand how a merge conflict should be resolved when it has been introduced by an interactive rebase.</p>
| 25,023
|
<p>We are making an automated patching application and would like to post files on production server through asp.net page (or maybe a web service), since we can only access production server via http. The page should accept files and store them to appropriate location. The path to files will be declared in external XML file.
So, is it possible posting a base64 encoded files within body tag and HOW? maybe even any better approach?</p>
|
<p>If unlocker comes with parameters -L and -U, I don't think L would be the one you want to unlock with. Probably U is for unlocking ;)</p>
<p>If you have any control of the application that is locking the file, it would be a better solution to have that program free the file rather than a third party app rip it away like this.</p>
|
<p>Look at the documentation for the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx" rel="nofollow noreferrer">System.Diagnostics.Process</a> class and the related ProcessStartInfo class.</p>
| 42,459
|
<p>I want to create a script that parses or makes sense of apache's error log to see what the most recent error was. I was wondering if anyone out there has something that does this or has any ideas where to start?</p>
|
<p>There are a few things to consider first:</p>
<ol>
<li>Firstly, your PHP user may not have access to Apache's log files.</li>
<li>Secondly, PHP and Apache aren't going to tell you where said log file is,</li>
<li>Lastly, Apache log files can get quite large.</li>
</ol>
<p>However, if none of these apply, you can use the normal file reading commands to do it.
The easiest way to get the last error is</p>
<pre><code>$contents = @file('/path/to/error.log', FILE_SKIP_EMPTY_LINES);
if (is_array($contents)) {
echo end($contents);
}
unset($contents);
</code></pre>
<p>There's probably a better way of doing this that doesn't oink up memory, but I'll leave that as an exercise for the reader.</p>
<p>One last comment: PHP also has an ini setting to redirect PHP errors to a log file: <code>error_log = /path/to/error.log</code></p>
<p>You can set this in httpd.conf or in an .htaccess file (if you have access to one) using the php_flag notation:</p>
<pre><code>php_flag error_log /web/mysite/logs/error.log
</code></pre>
|
<p>Have you tried biterScripting ? I am a system admin and I have been using to parse logs. It is univx style scripting. biterScripting.com -> Free download.</p>
| 19,281
|
<p>I am using a ResourceDictionary, but I would like to be able to look up the value or the key with the other item. Each is always unique, so that is not a problem. Is there a type that has this double sided lookup feature?</p>
|
<p>Not built in, but this is pretty easy to write. I would probably implement IDictionary for this though... You would then dump the ResourceDictionary into your custom type.</p>
<pre><code>public class DoubleLookup<TKey, TValue>
{
private IDictionary<TKey, TValue> keys;
private IDictionary<TValue, TKey> values;
//stuff...
public void Add(TKey key, TValue value)
{
this.keys.Add(key, value);
this.values.Add(value, key);
}
public TKey GetKeyFromValue(TValue value)
{
return this.values[value];
}
public TValue GetValueFromKey(TKey key)
{
return this.keys[key];
}
}
</code></pre>
|
<p>Be very careful when reversing the key/value relationship in a dictionary.</p>
<p>The contract of the dictionary guarantees that, for every value in the collection, there is exactly one key which maps to that value. The keys are unique. But the reverse is not true; for every distinct value, there can be many different keys mapping to that value.</p>
<p>In my own personal code library (written in Java, which is close enough), I have MultiMap class for just this kind of thing. Although the keys are unique, each key can be associated with multiple values. It's exactly identical to a Map>.</p>
<p>When I need to perform value-to-key lookups in a collection, I do something like this:</p>
<pre><code>Map<K, V> lookupTable = ...;
MultiMap<V, K> reverseLookupTable = MapUtil.invert(lookupTable);
V value = ...;
if (reverseLookupTable.containsKey(value)) {
Set<K> keys = reverseLookupTable.get(value);
}
</code></pre>
<p>If you use something other than a MultiMap (like a HashMap or Dictionary) as your reverse-lookup table, you run the risk of losing some of your V->K mappings, unless you can guarantee that all keys AND all values in your collection are unique.</p>
<hr>
<p>EDIT:</p>
<p>Oops. I just noticed that you said that all keys and values in your collection are unique. But I'll leave my answer here anyhow, as a warning for others reading this, who might not be able to provide the same guarantee.</p>
| 38,434
|
<p>I have a query on my database as such:</p>
<pre><code>SELECT * FROM expenses WHERE user_id = ? AND dated_on = ?
</code></pre>
<p>I have added an index to the table on both the <code>user_id</code> and <code>dated_on</code> columns. When I inspect the indexes using <code>SHOW INDEXES FROM expenses</code>, there are two lines -- one with a <code>seq_in_index</code> value of 1, the other with a <code>seq_in_index</code> value of 2.</p>
<p>My question is, if I then submit a query which uses only one of the two WHERE clauses, e.g.:</p>
<pre><code>SELECT * FROM expenses WHERE user_id = ?
</code></pre>
<p>Is there any benefit to creating another index which solely indexes the <code>user_id</code> column, or will the <code>user_id</code>/<code>dated_on</code> index described above be used just as efficiently?</p>
<p>Finally, how about if use the query:</p>
<pre><code>SELECT * FROM expenses WHERE dated_on = ?
</code></pre>
<p>How does the <code>seq_in_index</code> value of 2 affect index use and performance in this situation?</p>
|
<p>MySQL can use <a href="http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html" rel="noreferrer">any left portion of an index</a>.</p>
<p>In your example <code>SELECT * FROM expenses WHERE user_id = ?</code> will use the index but <code>SELECT * FROM expenses WHERE dated_on = ?</code> won't.</p>
<p>For a 3-column index A, B, C, <code>WHERE A = ? AND B = ?</code> will use an index over A and B, but <code>WHERE A = ? AND C = ?</code> will only use an index on A</p>
|
<p>If your index on user_id and dated_on is really in that order (user_id first), then it will be used for a user_id query also. You can check by using EXPLAIN to see the actual strategy for the query.</p>
| 32,735
|
<p>I have a 3 column grid in a window with a GridSplitter on the first column. I want to set the MaxWidth of the first column to a third of the parent Window or Page <code>Width</code> (or <code>ActualWidth</code>) and I would prefer to do this in XAML if possible.</p>
<p>This is some sample XAML to play with in XamlPad (or similar) which shows what I'm doing. </p>
<pre><code><Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="Column1" Width="200"/>
<ColumnDefinition x:Name="Column2" MinWidth="50" />
<ColumnDefinition x:Name="Column3" Width="{ Binding ElementName=Column1, Path=Width }"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Background="Green" />
<GridSplitter Grid.Column="0" Width="5" />
<Label Grid.Column="1" Background="Yellow" />
<Label Grid.Column="2" Background="Red" />
</Grid>
</Page>
</code></pre>
<p>As you can see, the right column width is bound to the width of the first column, so when you slide the left column using the splitter, the right column does the same :)
If you slide the left column to the right, eventually it will slide over half the page/window and over to the right side of the window, pushing away column 2 and 3. </p>
<p>I want to prevent this by setting the MaxWidth of column 1 to a third of the window width (or something like that). I can do this in code behind quite easily, but how to do it in "XAML Only"?</p>
<p><strong><em>EDIT:</strong> David Schmitt suggested to use SharedSizeGroup instead of binding, which is an excellent suggestion. My sample code would look like this then:</em></p>
<pre><code><Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<Grid IsSharedSizeScope="True">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="Column1" SharedSizeGroup="ColWidth" Width="40"/>
<ColumnDefinition x:Name="Column2" MinWidth="50" Width="*" />
<ColumnDefinition x:Name="Column3" SharedSizeGroup="ColWidth"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Background="Green" />
<GridSplitter Grid.Column="0" Width="5" />
<Label Grid.Column="1" Background="Yellow" />
<Label Grid.Column="2" Background="Red" />
</Grid>
</Page>
</code></pre>
|
<p>I think the XAML-only approach is somewhat circuitous, but here is a way to do it.</p>
<pre><code><Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<!-- This contains our real grid, and a reference grid for binding the layout-->
<Grid x:Name="Container">
<!-- hidden because it's behind the grid below -->
<Grid x:Name="LayoutReference">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!-- We need the border, because the column doesn't have an ActualWidth -->
<Border x:Name="ReferenceBorder"
Background="Black" />
<Border Background="White" Grid.Column="1" />
<Border Background="Black" Grid.Column="2" />
</Grid>
<!-- I made this transparent, so we can see the reference -->
<Grid Opacity="0.9">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="Column1"
MaxWidth="{Binding ElementName=ReferenceBorder,Path=ActualWidth}"/>
<ColumnDefinition x:Name="Column2"
MinWidth="50" />
<ColumnDefinition x:Name="Column3"
Width="{ Binding ElementName=Column1, Path=Width }"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Background="Green"/>
<GridSplitter Grid.Column="0" Width="5" />
<Label Grid.Column="1" Background="Yellow" />
<Label Grid.Column="2" Background="Red" />
</Grid>
</Grid>
</Page>
</code></pre>
|
<p>Too lazy to actually write it up myself, but you should be able to use a mathematical converter and bind to your parent windows width (either by name, or with a RelativeSource ancestor search). </p>
<pre><code>//I know I borrowed this from someone, sorry I forgot to add a comment from whom
public class ScaledValueConverter : IValueConverter
{
public Object Convert(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)
{
Double scalingFactor = 0;
if (parameter != null)
{
Double.TryParse((String)(parameter), out scalingFactor);
}
if (scalingFactor == 0.0d)
{
return Double.NaN;
}
return (Double)value * scalingFactor;
}
public Object ConvertBack(Object value, Type targetType, Object parameter, System.Globalization.CultureInfo culture)
{
throw new Exception("The method or operation is not implemented.");
}
}
</code></pre>
| 10,800
|
<p>Is it okay to directly connect together the grounds of the logic supply and the motor supply when using a Pololu style stepper driver?</p>
<p><a href="https://i.stack.imgur.com/yijCn.jpg" rel="nofollow noreferrer" title="A4988 connection schematic"><img src="https://i.stack.imgur.com/yijCn.jpg" alt="A4988 connection schematic" title="A4988 connection schematic"></a></p>
<p>If yes/no, why so?</p>
|
<p>That depends on how much noise you have on your motor power supply ground. You definitely want the 100 µF capacitor to have a good high frequency response. Motors turning on and off can be noisy, and that noise can cause false clock signals in your logic circuitry if you tie the grounds together. </p>
|
<p>That depends on how much noise you have on your motor power supply ground. You definitely want the 100 µF capacitor to have a good high frequency response. Motors turning on and off can be noisy, and that noise can cause false clock signals in your logic circuitry if you tie the grounds together. </p>
| 1,341
|
<p>For a new Java web project I thought about using:</p>
<ul>
<li>Eclipse as IDE</li>
<li>Mercurial for version control</li>
<li>Some kind of bug tracking software</li>
</ul>
<p>I have heard of bug tracking software where you can tie a change to an unresolved bug when you check it in. I haven't used any such solution myself, but it sounds good. Are there any good bug tracking applications which work well in combination with Eclipse and Mercurial and lets you tie a change to an unresolved bug? And if not, are there at least good plug ins for Eclipse to use Mercurial for version control? Would it support <code>hg rename</code> and <code>hg copy</code>?</p>
<p>If I can get something good working using a mix of the above three components I plan on throwing Hudson into the mix as well. To be able to track how changes in the code base affects our unit tests.</p>
<p>First of all I want feedback on the above question. But I would appreciate any thoughts regarding handling versioning, bug tracking and their integration into Eclipse.</p>
|
<p>In my experience the MercurialEclipse plug-in works quite well - as far as I understood, nobody commenting here has actually used it, so don't base your decisions solely on those opinions. You'd probably be better off to test it yourself. As I said before - it works for me.</p>
<p>Disclaimer: I've participated in developing the plug-in...</p>
|
<p>Trac can sometimes be a pain to set up. Take a look at <a href="http://www.redmine.org/" rel="nofollow noreferrer">Redmine</a>.
I'd recommend installing <a href="http://tortoisehg.sourceforge.net/" rel="nofollow noreferrer">TortoiseHg</a> too.</p>
| 23,000
|
<p>I'm pretty new in the 3D printing world, and there are some doubts that have come my way and I've not been able to find anywhere.</p>
<p>Usually, I'm going to try to print pieces bigger than the bed of my Elegoo Mars Pro (which is 115 x 65 x 150 mm, so it's pretty small). Everywhere I try to look at this they are talking about Fused Filament Fabrication (FFF) printers, and I guess that material will make the answer to these questions to be different, that's why I'm asking here. <strong>All of these questions are focused on SLA printers.</strong></p>
<h2>Is there any kind of technique / slicer software to be able to print those pieces by parts?</h2>
<p>I've read about slicers, but there seem to be a bunch of them, and some of them work best with some printers than others, and have different features but I haven't seen any that helps in this matter.</p>
<p>Also, I've seen the typical plane cut, but this doesn't make it easy later on to "fit" pieces. I would need some kind of female - male joint. Is there any (free) slicer that helps in that, and makes those joints to be accurate and solid?</p>
<p>Thank you!</p>
<hr />
<p>I removed the "shrink size" part in the question and published it <a href="https://3dprinting.stackexchange.com/questions/14283/curated-resin-size-shrink-and-methods-to-reduce-it">as a separate question</a>. Also moved <a href="https://3dprinting.stackexchange.com/questions/14284/sla-resin-post-processing-gluing-parts-together">to a different question</a> "gluing separate pieces" part.*</p>
|
<p>I don't think it is the thermistor degrading. To answer your question directly, all my thermistors have failed because the tiny wire has broken off, and generally the fail is “hard” not soft.</p>
<p>It is more likely you’re experiencing absorbed humidity in the filament from it being out on the spool too long. this makes you have to increase the temperature.</p>
<p>I’m sure if you dehydrated the spool in the oven for a bit you’d get better prints and a slightly lower print temp.</p>
<p>Additionally, keep in mind that a lot of PLA on the market nowadays runs at higher temps because it’s laced with something (“PLA+”?). Check the item description for indicators of a new or improved formula.</p>
<p>You could try ordering a thermistor of the same make and testing the temperature of it. You can get a half dozen for about \$10. The Marlin firmware your printer probably uses should have a section for thermistors and what kind you’re using. It’s probably type “1” which is the cheap kind.</p>
<p>You can try using one of those distant head thermometers to measure the temperature wirelessly at the hot end. These are probably over \$100 right now because of COVID. I think that is how a well-resourced person would handle this (i'm not one personally).</p>
<p>Maybe start with the oven and while it’s cooking, research the thermistors and what goes in to replacing one. It’s a good learning experience because one day your hotend may be irreparably clogged and you’ll want to know some of the steps to disassemble it.</p>
|
<p>It is indeed possible that the thermistor is broken (yet not sure). I am aware of two types of issues with thermistors:</p>
<ol>
<li><p>The contact (soldering) is broken, usually due to the temperature extreme variations. The thermistor will indicate the maximum temperature in case of PTC or minimum temperature in case of NTC. In some cases, due to vibrations or other factor, the contact will eventually touch, showing improbable jumps of temperature.</p>
</li>
<li><p>The thermistor is broken internally. In that case it will just indicate a wrong temperature. I can't say if constant temperature or constant delta.</p>
</li>
</ol>
<p>For how to troubleshot the component, however, EE.SE seems more convenient.</p>
| 1,728
|
<p>Normally I use <code>imagecreatefromjpeg()</code> and then <code>getimagesize()</code>, but with Firefox 3 I need to go round this different. So now im using <code>imagecreatefromstring()</code>, but how do I retreive the image dimensions now?</p>
|
<p><code>imagesx()</code> and <code>imagesy()</code> functions seem to work with images made with <code>imagecreatefromstring()</code>, too.</p>
|
<p>ah yes! i just found the answer on the internet a second ago :)</p>
<p>for those who still interested :</p>
<pre><code>$image = imagecreatefromstring($img_str);
$w = imagesx($image);
$h = imagesy($image);
</code></pre>
| 13,448
|
<p>What is the troubleshooting process for the "Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80080005" errors in .Net? To clarify: I am getting this at runtime, on my XP machine, with client being .net code running under admin account. {XXXX} refers to one of our in-house COM components. </p>
<p>From what I understand, 0x80080005 refers to "permission denied", but where do I go to check/change the permissions? Or am I completely wrong here, and the error is coming from the component itself, and not out of Windows COM subsystem?</p>
|
<p>Seems to be a rather generic error relating to starting up the COM server. Possible issues include <a href="http://blogs.msdn.com/adioltean/archive/2005/06/24/432519.aspx" rel="noreferrer">timeouts</a>, <a href="http://alt.pluralsight.com/wiki/default.aspx/Keith/ComSecurityFaqEx2.html" rel="noreferrer">logon failures</a> (check the Q about <code>CO_E_SERVER_EXEC_FAILURE</code>), or <a href="http://www.devguy.com/fp/Tips/COM/" rel="noreferrer">security permissions</a>, or (evidently) a <a href="http://blogs.msdn.com/jigarme/archive/2008/05/08/cocreateinstance-returns-0x80080005-for-visual-studio-2008-based-atl-service.aspx" rel="noreferrer">VS2008 ATL bug</a>. Hitting an error in CreateInstance would do the trick as well, I think.</p>
<p>I'd start by checking Event Log for anything interesting.</p>
|
<p>One thing that you can look at is the DCOM security configuration. It is controlled by the dcomcnfg utility. There are <a href="http://www.opcactivex.com/Support/Tutorials/DCOM_Tutorial_-_Configuring_th/DCOM_Videos/dcom_videos.html" rel="nofollow noreferrer">helpful tutorial videos</a> on the web to explain how to use it. There is also a <a href="http://forums.asp.net/t/1093228.aspx" rel="nofollow noreferrer">thread on the ASP.NET</a> forum that discusses how to use dcomcnfg.</p>
| 35,250
|
<p>I have a file I need to move that's already under perforce. Once moved it needs some editing - update the package, etc - appropriate to its new location. Should I submit the move changespec and then reopen it for edit, or can I do this in one go? If so, what is the appropriate sequence of events?</p>
|
<p>I have done this before in one go, but depending on your build process, I recommend against it. What I generally do is this:</p>
<ol>
<li>Move the file.</li>
<li>If the move needs a change in order to compile, open it for edit and make those changes.</li>
<li>Submit the changes, telling perforce to reopen the files for editing.</li>
<li>Make the changes for path, etc., that don't cause compile errors but should be updated.</li>
<li>Submit those changes with an appropriate description.</li>
</ol>
<p>If you want to, however, you could just do all your changes in step (2) above. Perforce might change the flag for the new file from integrate to add, but it still remembers the source path for the file.</p>
<p><strong>Edit: Better method</strong></p>
<p>I realized that I often use a different method, but the idea of "moving" the file distracted me. So, I would recommend these steps instead:</p>
<ol>
<li>Integrate the file into the new path/name, leaving the previous file there. I am assuming that this won't break your build process.</li>
<li>Submit the new file, checking it out again for edit after submission.</li>
<li>Make the required changes to the new file, and to the project so that you are using the new file.</li>
<li>Submit the edits for the new file.</li>
<li>[Optional] You might need to check through branch specs to see if you need to map the old file into the new one in any branches.</li>
<li>Create a changelist for deleting the old file, and submit it sometime later.</li>
</ol>
<p>This method allows the edits to be cleanly separated from the rename/move, while never leaving the project in a state that won't compile.</p>
<p>Also, why wait for step 6? Sometimes, especially on bigger projects, you might want to move a file that another person is editing. Perforce will helpfully tell you this. By waiting to delete the file, you allow your coworker(s) to finish the edits and submit without needing to move their work manually. After the edits are submitted, they can be integrated into the new file, and then the old one can be safely deleted.</p>
|
<p>"Safely" is probably an important point here. Once you rename or move the file it'll get a revision number of "1" which looks like a new file to your Perforce client. Of course, admins will be able to get its prior history, but if the editing/version history of the file is important to you it's a little harder to get the older revision.</p>
<p>Update: Thanks to Commodore Jaeger and Greg Whitfield for enlightening comments.</p>
<p>This wasn't easy to track down regarding what the One True Answer is, even from Perforce support, so I figured I'd update everyone on what we found:</p>
<ul>
<li>Perforce stores all versions of every document in its database.</li>
<li>If it's saving your file as type <code><text></code> or <code><ktext></code> then it stores the diffs of one file version to another and not the entire file.</li>
<li>If you check out a file, make no changes to it, and then re-submit, it will save as a new version with 0 diffs. This is configurable and P4 can be set up to ignore changelist items without any actual diffs. You can force this behavior by selecting "Revert unchanged files..." before you submit a changelist.</li>
<li>Use "Rename/Move..." to move files in P4 so it can track them. Don't copy them using Windows Explorer and then re-add them in P4.</li>
<li>If you use the "Rename/Move..." function from the context menu, the "new" file will show a revision number of "1" as though it were a new file.</li>
<li>However, since P4 saves every function performed on a file, you can actually get to any previous revision (and even recover "deleted" files) with the CLI command <code>p4 filelog -i</code></li>
<li>If you want to get to the revision history of a moved or renamed file and you're not an admin, you can right-click and select its "Revision Graph" which shows every version of a file even when moved between branches.</li>
</ul>
<p>According to Perforce support, easier tracking of revision history through branch or folder moves is an oft-requested feature and is in their current roadmap.</p>
<p>Perforce's answer: At the moment, there isn't a way to move/rename/integrate files and still maintain the exact file history.</p>
<p>However, if you were to choose "Integrate..." by right-clicking on the folder that you want to share, the versions of the files of the newly branched folder and underlying files will start from revision #1, but the integration history between the branched folder and underlying files and the original folder and underlying files will remain through which you can trace the revision history of the files.</p>
| 14,052
|
<p>Why use a GlobalClass? What are they for? I have inherited some code (shown below) and as far as I can see there is no reason why strUserName needs this. What is all for?</p>
<pre><code>public static string strUserName
{
get { return m_globalVar; }
set { m_globalVar = value; }
}
</code></pre>
<p>Used later as:</p>
<pre><code>GlobalClass.strUserName
</code></pre>
<p>Thanks</p>
|
<p>You get all the bugs of global state and none of the yucky direct variable access. </p>
<p>If you're going to do it, then your coder implemented it pretty well. He/She probably thought (correctly) that they would be free to swap out an implementation later.</p>
<p>Generally it's viewed as a bad idea since it makes it difficult to test the system as a whole the more globals you have in it.</p>
<p>My 2 cents.</p>
|
<p>When you want to use a <b>static</b> member of a type, you use it like <code>ClassName.MemberName</code>. If your code snippet is in the same class as the member you're referring (in this example, you're coding in a GlobalClass member, and using strUserName) you <b>can</b> omit the class name. Otherwise, it's required as the compiler wouldn't have any knowledge of what class you're referring to.</p>
| 40,564
|
<p>Is there a succinct way to retrieve a random record from a sql server table? </p>
<p>I would like to randomize my unit test data, so am looking for a simple way to select a random id from a table. In English, the select would be "Select one id from the table where the id is a random number between the lowest id in the table and the highest id in the table." </p>
<p>I can't figure out a way to do it without have to run the query, test for a null value, then re-run if null.</p>
<p>Ideas?</p>
|
<blockquote>
<p>Is there a succinct way to retrieve a random record from a sql server table?</p>
</blockquote>
<p>Yes</p>
<pre><code>SELECT TOP 1 * FROM table ORDER BY NEWID()
</code></pre>
<h2>Explanation</h2>
<p>A <code>NEWID()</code> is generated for each row and the table is then sorted by it. The first record is returned (i.e. the record with the "lowest" GUID).</p>
<h3>Notes</h3>
<ol>
<li><p>GUIDs are generated as pseudo-random numbers since version four:</p>
<blockquote>
<p>The version 4 UUID is meant for generating UUIDs from truly-random or
pseudo-random numbers.</p>
<p>The algorithm is as follows:</p>
<ul>
<li>Set the two most significant bits (bits 6 and 7) of the
clock_seq_hi_and_reserved to zero and one, respectively.</li>
<li>Set the four most significant bits (bits 12 through 15) of the
time_hi_and_version field to the 4-bit version number from
Section 4.1.3.</li>
<li>Set all the other bits to randomly (or pseudo-randomly) chosen
values.</li>
</ul>
</blockquote>
<p>—<a href="http://www.ietf.org/rfc/rfc4122.txt" rel="noreferrer">A Universally Unique IDentifier (UUID) URN Namespace - RFC 4122</a></p></li>
<li><p>The alternative <code>SELECT TOP 1 * FROM table ORDER BY RAND()</code> will not work as one would think. <code>RAND()</code> returns one single value per query, thus all rows will share the same value.</p></li>
<li><p>While GUID values are pseudo-random, you will need a better PRNG for the more demanding applications.</p></li>
<li><p>Typical performance is less than 10 seconds for around 1,000,000 rows — of course depending on the system. Note that it's impossible to hit an index, thus performance will be relatively limited.</p></li>
</ol>
|
<p>I was looking to improve on the methods I had tried and came across this post. I realize it's old but this method is not listed. I am creating and applying test data; this shows the method for "address" in a SP called with @st (two char state)</p>
<pre><code>Create Table ##TmpAddress (id Int Identity(1,1), street VarChar(50), city VarChar(50), st VarChar(2), zip VarChar(5))
Insert Into ##TmpAddress(street, city, st, zip)
Select street, city, st, zip
From tbl_Address (NOLOCK)
Where st = @st
-- unseeded RAND() will return the same number when called in rapid succession so
-- here, I seed it with a guaranteed different number each time. @@ROWCOUNT is the count from the most recent table operation.
Set @csr = Ceiling(RAND(convert(varbinary, newid())) * @@ROWCOUNT)
Select street, city, st, Right(('00000' + ltrim(zip)),5) As zip
From ##tmpAddress (NOLOCK)
Where id = @csr
</code></pre>
| 23,234
|
<p>The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says:</p>
<p><strong>The node to be removed is not a child of this node.</strong></p>
<p>Does anyone know the proper way to do this?</p>
<pre><code>public void DeleteProject (string projectName)
{
string ccConfigPath = ConfigurationManager.AppSettings["ConfigPath"];
XmlDocument configDoc = new XmlDocument();
configDoc.Load(ccConfigPath);
XmlNodeList projectNodes = configDoc.GetElementsByTagName("project");
for (int i = 0; i < projectNodes.Count; i++)
{
if (projectNodes[i].Attributes["name"] != null)
{
if (projectName == projectNodes[i].Attributes["name"].InnerText)
{
configDoc.RemoveChild(projectNodes[i]);
configDoc.Save(ccConfigPath);
}
}
}
}
</code></pre>
<p><strong>UPDATE</strong></p>
<p>Fixed. I did two things:</p>
<pre><code>XmlNode project = configDoc.SelectSingleNode("//project[@name='" + projectName + "']");
</code></pre>
<p>Replaced the For loop with an XPath query, which wasn't for fixing it, just because it was a better approach.</p>
<p>The actual fix was:</p>
<pre><code>project.ParentNode.RemoveChild(project);
</code></pre>
<p>Thanks Pat and Chuck for this suggestion.</p>
|
<p>Instead of </p>
<pre><code>configDoc.RemoveChild(projectNodes[i]);
</code></pre>
<p>try </p>
<pre><code>projectNodes[i].parentNode.RemoveChild(projectNodes[i]);
</code></pre>
|
<p>It would be handy to see a sample of the XML file you're processing but my guess would be that you have something like this</p>
<pre><code><Root>
<Blah>
<project>...</project>
</Blah>
</Root>
</code></pre>
<p>The error message seems to be because you're trying to remove <code><project></code> from the grandparent rather than the direct parent of the project node</p>
| 4,095
|
<p>I want to include a batch file rename functionality in my application. A user can type a destination filename pattern and (after replacing some wildcards in the pattern) I need to check if it's going to be a legal filename under Windows. I've tried to use regular expression like <code>[a-zA-Z0-9_]+</code> but it doesn't include many national-specific characters from various languages (e.g. umlauts and so on). What is the best way to do such a check?</p>
|
<p>You can get a list of invalid characters from <a href="http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars.aspx" rel="noreferrer"><code>Path.GetInvalidPathChars</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx" rel="noreferrer"><code>GetInvalidFileNameChars</code></a>.</p>
<p><strong>UPD:</strong> See <a href="https://stackoverflow.com/questions/62771/how-check-if-given-string-is-legal-allowed-file-name-under-windows#62855">Steve Cooper's suggestion</a> on how to use these in a regular expression.</p>
<p><strong>UPD2:</strong> Note that according to the Remarks section in MSDN "The array returned from this method is not guaranteed to contain the complete set of characters that are invalid in file and directory names." <a href="https://stackoverflow.com/questions/62771/how-check-if-given-string-is-legal-allowed-file-name-under-windows/62888#62888">The answer provided by sixlettervaliables</a> goes into more details.</p>
|
<p>One liner for verifying illigal chars in the string:</p>
<pre><code>public static bool IsValidFilename(string testName) => !Regex.IsMatch(testName, "[" + Regex.Escape(new string(System.IO.Path.InvalidPathChars)) + "]");
</code></pre>
| 8,825
|
<p>My guess is that class variables ("class var") are truly global in storage (that is, one instance for the entire application).</p>
<p>But I am wondering whether this is the case, or whether they are thread in storage (eg similar to a "threadvar") - once instance per thread.</p>
<p>Anyone know?</p>
<p><em>Edit: changed "scope" to "storage" as this is in fact the correct terminology, and what I am after (thanks Barry)</em></p>
|
<p>Yes, class variables are globally scoped. Have a look in the RTL source for details of how threadvars are implemented. Under Win32 each thread can have a block of memory allocated automatically to it on thread creation. This extra data area is what is used to contain your threadvars.</p>
|
<p>Class variables are just like classes: global and unique for the application.</p>
| 10,781
|
<p>From time to time I read that Fortran is or can be faster then C for heavy calculations. Is that really true? I must admit that I hardly know Fortran, but the Fortran code I have seen so far did not show that the language has features that C doesn't have.</p>
<p>If it is true, please tell me why. Please don't tell me what languages or libs are good for number crunching, I don't intend to write an app or lib to do that, I'm just curious.</p>
|
<p>The languages have similar feature-sets. The performance difference comes from the fact that Fortran says aliasing is not allowed, unless an EQUIVALENCE statement is used. Any code that has aliasing is not valid Fortran, but it is up to the programmer and not the compiler to detect these errors. Thus Fortran compilers ignore possible aliasing of memory pointers and allow them to generate more efficient code. Take a look at this little example in C:</p>
<pre><code>void transform (float *output, float const * input, float const * matrix, int *n)
{
int i;
for (i=0; i<*n; i++)
{
float x = input[i*2+0];
float y = input[i*2+1];
output[i*2+0] = matrix[0] * x + matrix[1] * y;
output[i*2+1] = matrix[2] * x + matrix[3] * y;
}
}
</code></pre>
<p>This function would run slower than the Fortran counterpart after optimization. Why so? If you write values into the output array, you may change the values of matrix. After all, the pointers could overlap and point to the same chunk of memory (including the <code>int</code> pointer!). The C compiler is forced to reload the four matrix values from memory for all computations.</p>
<p>In Fortran the compiler can load the matrix values once and store them in registers. It can do so because the Fortran compiler assumes pointers/arrays do not overlap in memory.</p>
<p>Fortunately, the <a href="https://en.wikipedia.org/wiki/Restrict" rel="noreferrer"><code>restrict</code></a> keyword and strict-aliasing have been introduced to the C99 standard to address this problem. It's well supported in most C++ compilers these days as well. The keyword allows you to give the compiler a hint that the programmer promises that a pointer does not alias with any other pointer. The strict-aliasing means that the programmer promises that pointers of different type will never overlap, for example a <code>double*</code> will not overlap with an <code>int*</code> (with the specific exception that <code>char*</code> and <code>void*</code> can overlap with anything).</p>
<p>If you use them you will get the same speed from C and Fortran. However, the ability to use the <code>restrict</code> keyword only with performance critical functions means that C (and C++) programs are much safer and easier to write. For example, consider the invalid Fortran code: <code>CALL TRANSFORM(A(1, 30), A(2, 31), A(3, 32), 30)</code>, which most Fortran compilers will happily compile without any warning but introduces a bug that only shows up on some compilers, on some hardware and with some optimization options.</p>
|
<p>Most of the posts already present compelling arguments, so I will just add the proverbial 2 cents to a different aspect.</p>
<p>Being fortran faster or slower in terms of processing power in the end can have its importance, but if it takes 5 times more time to develop something in Fortran because:</p>
<ul>
<li>it lacks any good library for tasks different from pure number crunching</li>
<li>it lack any decent tool for documentation and unit testing</li>
<li>it's a language with very low expressivity, skyrocketing the number of lines of code.</li>
<li>it has a very poor handling of strings</li>
<li>it has an inane amount of issues among different compilers and architectures driving you crazy.</li>
<li>it has a very poor IO strategy (READ/WRITE of sequential files. Yes, random access files exist but did you ever see them used?)</li>
<li>it does not encourage good development practices, modularization.</li>
<li>effective lack of a fully standard, fully compliant opensource compiler (both gfortran and g95 do not support everything)</li>
<li>very poor interoperability with C (mangling: one underscore, two underscores, no underscore, in general one underscore but two if there's another underscore. and just let not delve into COMMON blocks...)</li>
</ul>
<p>Then the issue is irrelevant. If something is slow, most of the time you cannot improve it beyond a given limit. If you want something faster, change the algorithm. In the end, computer time is cheap. Human time is not. Value the choice that reduces human time. If it increases computer time, it's cost effective anyway.</p>
| 17,607
|
<p>Does anyone know of a system for automatic error reporting in java? We have a server product that is installed on client servers. The idea is that our server would phone home with the details of an error to one of our servers, which then enters a bug in our bug tracker. Preferable, this would happen over http. It wouldn't happen for all exceptions, just the more serious and any that are not otherwise handled.</p>
<p>I'm trying to avoid rolling my own. We'll catch the exceptions ourselves, but I'm hoping this system would handle as much as possible between exception handler and the bug tracker back home.</p>
|
<p>Not conventional, but maybe you could use <a href="http://logging.apache.org/log4j/1.2/index.html" rel="nofollow noreferrer">Log4J</a> appenders to do it.</p>
<p>The <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/net/SocketAppender.html" rel="nofollow noreferrer">SocketAppender</a> allows you to send an event to a remote a log server. You can also communicate via mail using SMTPAppender (a little tricky but easy to implement). I don't know if there is any other appender to communicate with the server via HTTP (you could even implement it if needed, I suppose it is pretty easy).</p>
<p>Lets see if other users at stackoverflow have a better idea.</p>
|
<p>Have a look at <a href="http://www.snmp4j.org/" rel="nofollow noreferrer">SNMP4J</a>. There are quite a lot of system administration tools to aggregate SNMP infomation (ask your systems administrator), and the <a href="http://en.wikipedia.org/wiki/Simple_Network_Management_Protocol" rel="nofollow noreferrer">Simple Network Management Protocol</a> is designed for monitoring.</p>
<p>If you only need errors to be mailed to you you can also build your own framework with JavaMail; it is not that complicated and the boiler plate code can be put outside your business logic.</p>
<p>Maybe your bug tracking systems allows Soap/XML messages; then Axis would be a good fit, although it comes with quite a few dependencies.</p>
| 24,740
|
<p>Has anyone ever had the issue where trying to "View Designer" on a windows form in Visual Studio .NET causes the error: <strong>"Could not load file or assembly…"</strong> ?</p>
<p>In this case, the assembly in question was <code>XYZ.dll</code>. I managed to fix this by adding <code>XYZ.dll</code> and all its references to my project's references (even though my project doesn't directly depend on them) and rebuilding the whole solution. However, after that, I removed all those references from my project, rebuilt, and it still worked. </p>
<p>One other piece of information is that I use <strong>Resharper 2.5</strong>. Someone else pointed out that it might be Resharper doing some shadow copying. I'll look into this next time this happens.
Does anyone have a understanding of why this error happens in the first place, and possibly the 'correct' way to fix it?</p>
|
<p>We have same problem. Some Form/UserControl classes can not be viewed in designer and Visual Studio causes various exceptions.</p>
<p>There are one typical cause:
One of designed component thrown unhandled exception during initialization ( in constructor or in Load event or before ).</p>
<p>Not only for this case, you can run another instance of visual studio, open/create some independent project, go to menu -> Debug -> Attach to process ... -> select instance of devenv.exe process with problematic designer. Then press <strong>Ctrl+Alt+E</strong>, the "Exceptions" windows should be shown. There check "Thrown" in categories of exception.</p>
<p>Now active the visual studio with designer and try view designer. If the exception will be thrown, you will see callstack ( and maybe source code, if the exception was thrown from your code ) and other typical information about thrown exception. This information may be very helpful.</p>
<hr />
<p>If you have something like <code>TypeLoadException</code> from Winforms designer, when debugging Visual Studio (<code>devenv.exe</code> process) with another instance of Visual Studio, have a look at the <strong>Debug > Modules</strong> panel to see exactly which version of your DLL is loaded. Turned out that it was an unexpected version for us, hence the issue.</p>
|
<p>I concur with the Resharper comment. I'm running 4.1. I disabled it, restart VS2008, and tried the "Convert to Web Application" again, and it worked.</p>
| 20,146
|
<p>I have a little dilemma on how to set up my visual studio builds for multi-targeting.</p>
<p>Background: c# .NET v2.0 with p/invoking into 3rd party 32 bit DLL's, SQL compact v3.5 SP1, with a Setup project.
Right now, the platform target is set to x86 so it can be run on Windows x64.</p>
<p>The 3rd party company has just released 64 bit versions of their DLL's and I want to build a dedicated 64bit program.</p>
<p>This raises some questions which I haven't got the answers to yet.
I want to have the exact same code base.
I must build with references to either the 32bit set of DLL's or 64bit DLL's.
(Both 3rd party and SQL Server Compact)</p>
<p>Can this be solved with 2 new sets of configurations (Debug64 and Release64) ?</p>
<p>Must I create 2 separate setup projects(std. visual studio projects, no Wix or any other utility), or can this be solved within the same .msi?</p>
<p>Any ideas and/or recommendations would be welcomed.</p>
|
<p>Yes, you can target both x86 and x64 with the same code base in the same project. In general, things will Just Work if you create the right solution configurations in VS.NET (although P/Invoke to entirely unmanaged DLLs will most likely require some conditional code): the items that I found to require special attention are:</p>
<ul>
<li>References to outside managed assemblies with the same name but their own specific bitness (this also applies to COM interop assemblies)</li>
<li>The MSI package (which, as has already been noted, will need to target either x86 or x64)</li>
<li>Any custom .NET Installer Class-based actions in your MSI package</li>
</ul>
<p>The assembly reference issue can't be solved entirely within VS.NET, as it will only allow you to add a reference with a given name to a project once. To work around this, edit your project file manually (in VS, right-click your project file in the Solution Explorer, select Unload Project, then right-click again and select Edit). After adding a reference to, say, the x86 version of an assembly, your project file will contain something like:</p>
<pre><code><Reference Include="Filename, ..., processorArchitecture=x86">
<HintPath>C:\path\to\x86\DLL</HintPath>
</Reference>
</code></pre>
<p>Wrap that Reference tag inside an ItemGroup tag indicating the solution configuration it applies to, e.g:</p>
<pre><code><ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<Reference ...>....</Reference>
</ItemGroup>
</code></pre>
<p>Then, copy and paste the entire ItemGroup tag, and edit it to contain the details of your 64-bit DLL, e.g.:</p>
<pre><code><ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
<Reference Include="Filename, ..., processorArchitecture=AMD64">
<HintPath>C:\path\to\x64\DLL</HintPath>
</Reference>
</ItemGroup>
</code></pre>
<p>After reloading your project in VS.NET, the Assembly Reference dialog will be a bit confused by these changes, and you may encounter some warnings about assemblies with the wrong target processor, but all your builds will work just fine.</p>
<p>Solving the MSI issue is up next, and unfortunately this <i>will</i> require a non-VS.NET tool: I prefer Caphyon's <a href="http://www.advancedinstaller.com/" rel="noreferrer">Advanced Installer</a> for that purpose, as it pulls off the basic trick involved (create a common MSI, as well as 32-bit and 64-bit specific MSIs, and use an .EXE setup launcher to extract the right version and do the required fixups at runtime) very, very well. </p>
<p>You can probably achieve the same results using other tools or the <a href="http://wix.sourceforge.net/" rel="noreferrer">Windows Installer XML (WiX) toolset</a>, but Advanced Installer makes things so easy (and is quite affordable at that) that I've never really looked at alternatives.</p>
<p>One thing you <i>may</i> still require WiX for though, even when using Advanced Installer, is for your .NET Installer Class custom actions. Although it's trivial to specify certain actions that should only run on certain platforms (using the VersionNT64 and NOT VersionNT64 execution conditions, respectively), the built-in AI custom actions will be executed using the 32-bit Framework, even on 64-bit machines.</p>
<p>This may be fixed in a future release, but for now (or when using a different tool to create your MSIs that has the same issue), you can use WiX 3.0's managed custom action support to create action DLLs with the proper bitness that will be executed using the corresponding Framework.</p>
<hr>
<p>Edit: as of version 8.1.2, Advanced Installer correctly supports 64-bit custom actions. Since my original answer, its price has increased quite a bit, unfortunately, even though it's still extremely good value when compared to InstallShield and its ilk...</p>
<hr>
<p>Edit: If your DLLs are registered in the GAC, you can also use the standard reference tags this way (SQLite as an example):</p>
<pre><code><ItemGroup Condition="'$(Platform)' == 'x86'">
<Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86" />
</ItemGroup>
<ItemGroup Condition="'$(Platform)' == 'x64'">
<Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=AMD64" />
</ItemGroup>
</code></pre>
<p>The condition is also reduced down to all build types, release or debug, and just specifies the processor architecture.</p>
|
<p>Regarding your last question. Most likely you cant solve this inside a single MSI.
If you are using registry/system folders or anything related, the MSI itself must be aware of this and you must prepare a 64bit MSI to properly install on 32 bit machine.</p>
<p>There is a possibility that you can make you product installed as a 32 it application and still be able to make it run as 64 bit one, but i think that may be somewhat hard to achieve.</p>
<p>that being said i think you should be able to keep a single code base for everything. In my current work place we have managed to do so. (but it did took some juggling to make everything play together)</p>
<p>Hope this helps.
Heres a link to some info related to 32/64 bit issues:
<a href="http://blog.typemock.com/2008/07/registry-on-windows-64-bit-double-your.html" rel="nofollow noreferrer">http://blog.typemock.com/2008/07/registry-on-windows-64-bit-double-your.html</a></p>
| 17,577
|
<p>For a given class I would like to have tracing functionality i.e. I would like to log every method call (method signature and actual parameter values) and every method exit (just the method signature). </p>
<p>How do I accomplish this assuming that: </p>
<ul>
<li>I don't want to use any 3rd party
AOP libraries for C#,</li>
<li>I don't want to add duplicate code to all the methods that I want to trace, </li>
<li>I don't want to change the public API of the class - users of the class should be able to call all the methods in exactly the same way. </li>
</ul>
<p>To make the question more concrete let's assume there are 3 classes: </p>
<pre><code> public class Caller
{
public static void Call()
{
Traced traced = new Traced();
traced.Method1();
traced.Method2();
}
}
public class Traced
{
public void Method1(String name, Int32 value) { }
public void Method2(Object object) { }
}
public class Logger
{
public static void LogStart(MethodInfo method, Object[] parameterValues);
public static void LogEnd(MethodInfo method);
}
</code></pre>
<p>How do I invoke <em>Logger.LogStart</em> and <em>Logger.LogEnd</em> for every call to <em>Method1</em> and <em>Method2</em> without modifying the <em>Caller.Call</em> method and without adding the calls explicitly to <em>Traced.Method1</em> and <em>Traced.Method2</em>?</p>
<p>Edit: What would be the solution if I'm allowed to slightly change the Call method?</p>
|
<p>C# is not an AOP oriented language. It has some AOP features and you can emulate some others but making AOP with C# is painful.</p>
<p>I looked up for ways to do exactly what you wanted to do and I found no easy way to do it.</p>
<p>As I understand it, this is what you want to do:</p>
<pre><code>[Log()]
public void Method1(String name, Int32 value);
</code></pre>
<p>and in order to do that you have two main options</p>
<ol>
<li><p>Inherit your class from MarshalByRefObject or ContextBoundObject and define an attribute which inherits from IMessageSink. <a href="http://www.developerfusion.co.uk/show/5307/3/" rel="noreferrer">This article</a> has a good example. You have to consider nontheless that using a MarshalByRefObject the performance will go down like hell, and I mean it, I'm talking about a 10x performance lost so think carefully before trying that.</p></li>
<li><p>The other option is to inject code directly. In runtime, meaning you'll have to use reflection to "read" every class, get its attributes and inject the appropiate call (and for that matter I think you couldn't use the Reflection.Emit method as I think Reflection.Emit wouldn't allow you to insert new code inside an already existing method). At design time this will mean creating an extension to the CLR compiler which I have honestly no idea on how it's done.</p></li>
</ol>
<p>The final option is using an <a href="http://en.wikipedia.org/wiki/Inversion_of_control" rel="noreferrer">IoC framework</a>. Maybe it's not the perfect solution as most IoC frameworks works by defining entry points which allow methods to be hooked but, depending on what you want to achive, that might be a fair aproximation.</p>
|
<ol>
<li>Write your own AOP library.</li>
<li>Use reflection to generate a logging proxy over your instances (not sure if you can do it without changing some part of your existing code).</li>
<li>Rewrite the assembly and inject your logging code (basically the same as 1).</li>
<li>Host the CLR and add logging at this level (i think this is the hardest solution to implement, not sure if you have the required hooks in the CLR though).</li>
</ol>
| 4,540
|
<p>This is an issue that I've spent hours researching in the past. It seems to me to be something that should have been addressed by modern <a href="http://en.wikipedia.org/wiki/Relational_database_management_system" rel="noreferrer">RDBMS</a> solutions but as yet I have not found anything that really addresses what I see to be an incredibly common need in any Web or Windows application with a database back-end.</p>
<p>I speak of dynamic sorting. In my fantasy world, it should be as simple as something like:</p>
<pre><code>ORDER BY @sortCol1, @sortCol2
</code></pre>
<p>This is the canonical example given by newbie SQL and <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="noreferrer">Stored Procedure</a> developers all over forums across the Internet. "Why isn't this possible?" they ask. Invariably, somebody eventually comes along to lecture them about the compiled nature of stored procedures, of execution plans in general, and all sorts of other reasons why it isn't possible to put a parameter directly into an <code>ORDER BY</code> clause.</p>
<hr>
<p>I know what some of you are already thinking: "Let the client do the sorting, then." Naturally, this offloads the work from your database. In our case though, our database servers aren't even breaking a sweat 99% of the time and they aren't even multi-core yet or any of the other myriad improvements to system architecture that happen every 6 months. For this reason alone, having our databases handle sorting wouldn't be a problem. Additionally, databases are <em>very</em> good at sorting. They are optimized for it and have had years to get it right, the language for doing it is incredibly flexible, intuitive, and simple and above all any beginner SQL writer knows how to do it and even more importantly they know how to edit it, make changes, do maintenance, etc. When your databases are far from being taxed and you just want to simplify (and shorten!) development time this seems like an obvious choice.</p>
<p>Then there's the web issue. I've played around with JavaScript that will do client-side sorting of HTML tables, but they inevitably aren't flexible enough for my needs and, again, since my databases aren't overly taxed and can do sorting really <em>really</em> easily, I have a hard time justifying the time it would take to re-write or roll-my-own JavaScript sorter. The same generally goes for server-side sorting, though it is already probably much preferred over JavaScript. I'm not one that particularly likes the overhead of DataSets, so sue me.</p>
<p>But this brings back the point that it isn't possible — or rather, not easily. I've done, with prior systems, an incredibly hack way of getting dynamic sorting. It wasn't pretty, nor intuitive, simple, or flexible and a beginner SQL writer would be lost within seconds. Already this is looking to be not so much a "solution" but a "complication."</p>
<hr>
<p>The following examples are not meant to expose any sort of best practices or good coding style or anything, nor are they indicative of my abilities as a T-SQL programmer. They are what they are and I fully admit they are confusing, bad form, and just plain hack.</p>
<p>We pass an integer value as a parameter to a stored procedure (let's call the parameter just "sort") and from that we determine a bunch of other variables. For example... let's say sort is 1 (or the default):</p>
<pre><code>DECLARE @sortCol1 AS varchar(20)
DECLARE @sortCol2 AS varchar(20)
DECLARE @dir1 AS varchar(20)
DECLARE @dir2 AS varchar(20)
DECLARE @col1 AS varchar(20)
DECLARE @col2 AS varchar(20)
SET @col1 = 'storagedatetime';
SET @col2 = 'vehicleid';
IF @sort = 1 -- Default sort.
BEGIN
SET @sortCol1 = @col1;
SET @dir1 = 'asc';
SET @sortCol2 = @col2;
SET @dir2 = 'asc';
END
ELSE IF @sort = 2 -- Reversed order default sort.
BEGIN
SET @sortCol1 = @col1;
SET @dir1 = 'desc';
SET @sortCol2 = @col2;
SET @dir2 = 'desc';
END
</code></pre>
<p>You can already see how if I declared more @colX variables to define other columns I could really get creative with the columns to sort on based on the value of "sort"... to use it, it usually ends up looking like the following incredibly messy clause:</p>
<pre><code>ORDER BY
CASE @dir1
WHEN 'desc' THEN
CASE @sortCol1
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END DESC,
CASE @dir1
WHEN 'asc' THEN
CASE @sortCol1
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END,
CASE @dir2
WHEN 'desc' THEN
CASE @sortCol2
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END DESC,
CASE @dir2
WHEN 'asc' THEN
CASE @sortCol2
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END
</code></pre>
<p>Obviously this is a very stripped down example. The real stuff, since we usually have four or five columns to support sorting on, each with possible secondary or even a third column to sort on in addition to that (for example date descending then sorted secondarily by name ascending) and each supporting bi-directional sorting which effectively doubles the number of cases. Yeah... it gets hairy really quick.</p>
<p>The idea is that one could "easily" change the sort cases such that vehicleid gets sorted before the storagedatetime... but the pseudo-flexibility, at least in this simple example, really ends there. Essentially, each case that fails a test (because our sort method doesn't apply to it this time around) renders a NULL value. And thus you end up with a clause that functions like the following:</p>
<pre><code>ORDER BY NULL DESC, NULL, [storagedatetime] DESC, blah blah
</code></pre>
<p>You get the idea. It works because SQL Server effectively ignores null values in order by clauses. This is incredibly hard to maintain, as anyone with any basic working knowledge of SQL can probably see. If I've lost any of you, don't feel bad. It took us a long time to get it working and we still get confused trying to edit it or create new ones like it. Thankfully it doesn't need changing often, otherwise it would quickly become "not worth the trouble."</p>
<p>Yet it <em>did</em> work.</p>
<hr>
<p>My question is then: <strong>is there a better way?</strong></p>
<p>I'm okay with solutions other than Stored Procedure ones, as I realize it may just not be the way to go. Preferably, I'd like to know if anyone can do it better within the Stored Procedure, but if not, how do you all handle letting the user dynamically sort tables of data (bi-directionally, too) with ASP.NET?</p>
<p>And thank you for reading (or at least skimming) such a long question!</p>
<p>PS: Be glad I didn't show my example of a stored procedure that supports dynamic sorting, dynamic filtering/text-searching of columns, pagination via ROWNUMBER() OVER, <em>AND</em> try...catch with transaction rollbacking on errors... "behemoth-sized" doesn't even begin to describe them.</p>
<hr>
<p><strong>Update:</strong></p>
<ul>
<li>I would like to <strong>avoid dynamic SQL</strong>. Parsing a string together and running an EXEC on it defeats a lot of the purpose of having a stored procedure in the first place. Sometimes I wonder though if the cons of doing such a thing wouldn't be worth it, at least in these special dynamic sorting cases. Still, I always feel dirty whenever I do dynamic SQL strings like that — like I'm still living in the Classic ASP world.</li>
<li>A lot of the reason we want stored procedures in the first place is for <strong>security</strong>. I don't get to make the call on security concerns, only suggest solutions. With SQL Server 2005 we can set permissions (on a per-user basis if need be) at the schema level on individual stored procedures and then deny any queries against the tables directly. Critiquing the pros and cons of this approach is perhaps for another question, but again it's not my decision. I'm just the lead code monkey. :)</li>
</ul>
|
<p>Yeah, it's a pain, and the way you're doing it looks similar to what I do:</p>
<pre><code>order by
case when @SortExpr = 'CustomerName' and @SortDir = 'ASC'
then CustomerName end asc,
case when @SortExpr = 'CustomerName' and @SortDir = 'DESC'
then CustomerName end desc,
...
</code></pre>
<p>This, to me, is still much better than building dynamic SQL from code, which turns into a scalability and maintenance nightmare for DBAs.</p>
<p>What I do from code is refactor the paging and sorting so I at least don't have a lot of repetition there with populating values for <code>@SortExpr</code> and <code>@SortDir</code>.</p>
<p>As far as the SQL is concerned, keep the design and formatting the same between different stored procedures, so it's at least neat and recognizable when you go in to make changes.</p>
|
<p>This solution might only work in .NET, I don't know. </p>
<p>I fetch the data into the C# with the initial sort order in the SQL order by clause, put that data in a DataView, cache it in a Session variable, and use it to build a page.</p>
<p>When the user clicks on a column heading to sort (or page, or filter), I don't go back to the database. Instead, I go back to my cached DataView and set its "Sort" property to an expression I build dynamically, just like I would dynamic SQL. ( I do the filtering the same way, using the "RowFilter" property).</p>
<p>You can see/feel it working in a demo of my app, BugTracker.NET, at <a href="http://ifdefined.com/btnet/bugs.aspx" rel="nofollow noreferrer">http://ifdefined.com/btnet/bugs.aspx</a></p>
| 18,002
|
<p>I'm considering altering some tables to use nvarchar(50) as primary key instead of an int primary key. Using an int ID for a key really is irrelevant data, it's the string I'm interested in. What sort of performance hit will occur, or where do you research this? Other than cut and try that is.</p>
|
<p>You have hit upon one of the major "holy wars" of database design. The debate you're referring to is the "surrogate vs. natural key" argument that's been raging for as long as there have been RDBMSs (as nearly as I can tell).</p>
<p>The debate essentially boils down to whether a representative key (surrogate, for example an IDENTITY column) should be used versus using the actual data that uniquely describes a record (natural key).</p>
<p>I will say that there is no "right" answer. Performance measures are an artifact of the platform, and should be assessed by experimentation, but performance is not likely to be the major concern.</p>
<p>What I consider to be the primary argument for surrogate keys is the immutability of primary keys. If you choose to use a natural key, you give up the option of altering that key after it is established. You also give up the possibility that it may become non-unique at some point in the future. For those reasons, I typically (not always) use surrogate keys for most of my tables.</p>
<p>However, as I mentioned, there is a very long-standing debate filled with discussions of indexing strategies and normal-form adherance to be read if you are so inclined.</p>
<p>I would Google "surrogate vs. natural keys". Here are a few links to get you started:</p>
<p><a href="http://decipherinfosys.wordpress.com/2007/02/01/surrogate-keys-vs-natural-keys-for-primary-key/" rel="nofollow noreferrer">Systems Engineering and RDBMS</a></p>
<p><a href="https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1045050.html" rel="nofollow noreferrer">Techrepublic</a></p>
<p><a href="http://sqlblogcasts.com/blogs/tonyrogerson/archive/2006/05/11/427.aspx" rel="nofollow noreferrer">Tony Rogerson's blog</a></p>
<p>Hope this helps.</p>
|
<p>Why UNICODE? e.g. if I translated an English word into Chinese Han characters, would they be considered to be duplicates?</p>
<p>Why variable? Fixed width is a good physical characteristic of a key.</p>
<p>Why 50 characters? That's a lot of keying for users (I agree "an int ID for a key really is irrelevant data" and think such so-called 'surrogate keys' should never be exposed to end users, BTW).</p>
<p>Also, for me <code>NVARCHAR(50)</code> is a bit of a 'smell': a Microsoft default, a straight port from MS Access, perhaps? This doesn't mean you haven't given due thought and consideration to your key, of course, just one of those things to maybe review.</p>
<p>Oh hang on: you meant specifically PRIMARY KEY, right? Assuming you explicitly use your one (per table) clustered index, AFAIK PRIMARY KEY designation has no physical implications in SQL Server land. Of course, all your candidate keys should be covered by NOT NULL UNIQUE constraints; the one you choose to promote to PRIMARY key is arbitrary.</p>
| 27,751
|
<p>Not for the first time, I've accidentally done "svn switch" from somewhere below the root of my project. This switches that subdirectory only, but how do I undo this?</p>
<p>If I try switching the subdirectory back to the original branch I get:</p>
<pre><code>"svn: Directory 'subdir\_svn' containing working copy admin area is missing"
</code></pre>
<p><strong>Update</strong>: I've got changes in the subdir, so I don't want to do a delete. </p>
<p>In the short term I've fixed it by reapplying the changes, but I was after a way to get Subversion to re-switch back to where I came from... or is this a missing feature?</p>
|
<p>Quick hack: Delete the directory, go one level up, and run svn update.</p>
|
<pre><code>svn revert <dir>
</code></pre>
<p>Or, yes, delete it and grab another copy.</p>
| 12,610
|
<p>How can I do Exp and Imp by using PL/SQL?</p>
|
<p>This could be done in a few ways.</p>
<p>First, if you're using 10g or later, you can consider using data pump (expdp and impdp) as opposed to imp and exp. These are the newer and more capable versions of those tools.</p>
<p>As for how to call them from PL/SQL, you can do so by: </p>
<ul>
<li>You can make an external procedure call to a DLL (or shared library if you're on UNIX)</li>
<li>you could write a simple Java class (to run in the Oracle JVM) that would call out using Java</li>
<li>you could use Advanced Queues or DBMS_PIPE to communicate with external applications </li>
<li>You could use UTL_TCP to interact over the network (e.g. SOAP) </li>
<li>In 10g, you could use the DBMS_SCHEDULER package to call OS commands</li>
</ul>
<p>The first and last options should be well documented in the Oracle online docs - the other two options would require a little more coordination and coding.</p>
|
<p>You can see an example about exactly you are requesting in the <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14215/dp_api.htm#sthref460" rel="nofollow noreferrer">Examples of Using the Data Pump API</a> inside the <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14215/toc.htm" rel="nofollow noreferrer">Oracle Database Utilities</a> book.</p>
| 47,739
|
<p>I've several web user controls on my asp.net page and I wanna pass values between them. For example :</p>
<p>There is a dropDownList in one of them and when user selects any item from dropDownList, it can pass the selected value to the other user control which includes GridView to show related data of selected item value from the user control which contains the dropdownlist. (woow pretty awkward sentence tho) </p>
<p>Thanks and Regards..</p>
<p>P.s : Can we use User controls as class in the way to return values ?</p>
|
<p>On the DropDownList onChange event you could then assign the selected item value to the property of the other user control. </p>
<p>Ok, your UserControls should have properties that allow data to be set. For example in Control2 you would have:</p>
<pre><code>public string needData {
get { return MyData; }
set {
MyData = value;
//do whatever you need to do with that data here
}
</code></pre>
<p>Now in your page you would capture the DropDownList OnChange event and inside that you would something like this:</p>
<pre><code>myControl2.needData = myDropDownList.SelectedValue;
</code></pre>
<p>Does that make more sense?</p>
|
<p>Use delegates, example <a href="http://www.dotnetfunda.com/articles/article201.aspx" rel="nofollow noreferrer">here</a></p>
<p>Hope this helps</p>
| 47,506
|
<p>I recently broke the cooling fan on my Voxelab Aquila while doing some maintenance, and I'm in the middle of a multi piece print that I would like to finish soon. I found the fan replacement I need, but it's not going to arrive for over a week. I was wondering if it would be ok to print a few things with the broken fan, or if that would be bad for the motor or anything else.
<a href="https://i.stack.imgur.com/8wC69.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8wC69.jpg" alt="enter image description here" /></a><a href="https://i.stack.imgur.com/C8Kvm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C8Kvm.jpg" alt="enter image description here" /></a></p>
|
<p>As long as your ambient temperature is not excessive and you're not using a very high bed temperature, you should be fine.</p>
<p>With insufficient cooling, there is a risk of heat creep - that is, of the heat from the melt zone working its way up to the area where the filament is supposed to be solid, potentially causing jams if it deforms and catches in crevices there. However, the hotend is made to operate in temperatures far above normal room temperature, e.g. in non-air-conditioned spaces, in enclosed chambers for printing ABS, etc.</p>
<p>Just keep the space you're printing in cool and go on printing while you wait for a new fan to arrive. Maybe reduce your bed temperature a bit if you usually use temperatures on the high end (over 50°C).</p>
|
<p>If the fan is the part cooling fan, you'll have reduced cooling on the part as it is printed. This isn't necessarily going to be a problem, although you may have irregularities in the print surface.</p>
<p>If the fan is the heat sink cooling fan, reduced cooling will be problematic. This could result in heat creep and clogging of the hot end.</p>
| 2,142
|
<p>Are hints really necessary for every sql statement? We have a dba who is anal about it and asks us to put hints on every select and update statements in our stored procs. Is this really necessary?</p>
|
<p>Not usually. Putting them on everything sounds like overkill.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/ms187713.aspx" rel="nofollow noreferrer">documentation</a> says</p>
<p><em>Because the SQL Server query optimizer typically selects the best execution plan for a query, we recommend that join_hint, query_hint, and table_hint be used only as a last resort by experienced developers and database administrators</em></p>
|
<p>Hints are merely hints. They help the optimizer to do the best job possible. But like any optimization, you should focus on the statements that are actually problems.</p>
| 33,281
|
<p>I want to move various parts of my app into simple scripts, to allow people that do not have a strong knowledge of c++ to be able to edit and implement various features.</p>
<p>Because it's a real time app, I need to have some kind of multitasking for these scripts. Ideally I want it so that the c++ app calls a script function which then continues running (under the c++ thread) until either a pause point (Wait(x)), or it returns. In the case of it waiting the state needs to be saved ready for the script to be restarted the next time the app loops after the duration has expired.</p>
<p>The scripts also need to be able to call c++ class methods, ideally using the c++ classes rather than plain wrapper functions around c++ classes.</p>
<p>I don't want to spend a massive amount of time implementing this, so using an existing scripting language is preferred to writing my own. I heard that Python and Lua can be integrated into a c++ app, but I do not know how to do this to achieve my goals.</p>
<ul>
<li>The scripts must be able to call c++ functions</li>
<li>The scripts must be able to "pause" when certain functions are called (eg. Wait), and be restarted again by the c++ thread</li>
<li>Needs to be fast -- this is for a real time app and there could potentially be a lot of scripts running.</li>
</ul>
<p>I can probably roll the multitasking code fairly easily, provided the scripts can be saved and restarted (possibly by a different thread to the original).</p>
|
<p>You can use either Lua or Python. Lua is more "lightweight" than python. It's got a smaller memory footprint than python does and in our experience was easier to integrate (people's mileage on this point might vary). It can support a bunch of scripts running simultaneously. Lua, at least, supports stopping/starting threads in the manner you desire.</p>
<p>Boost.python is nice, but in my (limited) experience, it was difficult for us to get compiling for our different environments and was pretty heavyweight. It has (in my opinion) the disadvantage of requiring Boost. For some, that might not be a problem, but if you don't need Boost (or are not using it), you are introducing a ton of code to get Boost.python working. YMMV.</p>
<p>We have built Lua into apps on multiple platforms (win32, Xbox360 and PS3). I believe that it will work on x64. The suggestion to use Luabind is good. We wound up writing our own interface between the two and while not too complicated, having that glue code will save you a lot of time and perhaps aggravation.</p>
<p>With either solution though, debugging can be a pain. We currently have no good solution for debugging Lua scripts that are embedded into our app. Since we haven't used python in our apps I can't speak to what tools might be available there, but a couple of years ago the landscape was roughly the same -- poor debugging. Having scripting to extend functionality is nice, but bugs in the scripts can cause problems and might be difficult to locate.</p>
<p>The Lua code itself is kind of messy to work with if you need to make changes there. We have seen bugs in the Lua codebase itself that were hard to track down. I suspect that Boost::Python might have similar problems.</p>
<p>And with any scripting language, it's not necessarily a solution for "non-programmers" to extend functionality. It might seem like it, but you will likely wind up spending a fair amount of time either debugging scripts or even perhaps Lua.</p>
<p>That all said, we've been very happy with Lua and have shipped it in two games. We currently have no plans to move away from the language. All in all, we've found it better than other alternatives that were available a couple of years ago. Python (and IronPython) are other choices, but based on experience, they seem more heavy handed than Lua. I'd love to hear about other experiences there though.</p>
|
<p>You can also embed C/C++ scripts using <a href="http://softintegration.com/" rel="nofollow noreferrer">Ch</a>. I've been using it for a game project I'm working on, and it does well. Nice blend of power and adaptability.</p>
| 8,923
|
<p>As far as i know it is not possible to do the following in C# 2.0</p>
<pre><code>public class Father
{
public virtual Father SomePropertyName
{
get
{
return this;
}
}
}
public class Child : Father
{
public override Child SomePropertyName
{
get
{
return this;
}
}
}
</code></pre>
<p>I workaround the problem by creating the property in the derived class as "new", but of course that is not polymorphic.</p>
<pre><code>public new Child SomePropertyName
</code></pre>
<p>Is there any solution in 2.0?
What about any features in 3.5 that address this matter? </p>
|
<p>This is not possible in any .NET language because of type-safety concerns. In type-safe languages, you must provide covariance for return values, and contravariance for parameters. Take this code:</p>
<pre><code>class B {
S Get();
Set(S);
}
class D : B {
T Get();
Set(T);
}
</code></pre>
<p>For the <code>Get</code> methods, covariance means that <code>T</code> must either be <code>S</code> or a type derived from <code>S</code>. Otherwise, if you had a reference to an object of type <code>D</code> stored in a variable typed <code>B</code>, when you called <code>B.Get()</code> you wouldn't get an object representable as an <code>S</code> back -- breaking the type system.</p>
<p>For the <code>Set</code> methods, contravariance means that <code>T</code> must either be <code>S</code> or a type that <code>S</code> derives from. Otherwise, if you had a reference to an object of type <code>D</code> stored in a variable typed <code>B</code>, when you called <code>B.Set(X)</code>, where <code>X</code> was of type <code>S</code> but not of type <code>T</code>, <code>D::Set(T)</code> would get an object of a type it did not expect.</p>
<p>In C#, there was a conscious decision to disallow changing the type when overloading properties, even when they have only one of the getter/setter pair, because it would otherwise have very inconsistent behavior (<em>"You mean, I can change the type on the one with a getter, but not one with both a getter and setter? Why not?!?"</em> -- Anonymous Alternate Universe Newbie).</p>
|
<p>No. C# does not support this idea (it's called "return type covariance").
You can however do this:</p>
<pre><code>public class FatherProp
{
}
public class ChildProp: FatherProp
{
}
public class Father
{
public virtual FatherProp SomePropertyName
{
get
{
return new FatherProp();
}
}
}
public class Child : Father
{
public override FatherProp SomePropertyName
{
get
{
// override to return a derived type instead
return new ChildProp();
}
}
}
</code></pre>
<p>i.e. use the contract defined by the base class, but return a derived type. I have made a more detailed sample to make this point clearer - returning "this" again wouldn't change anything.</p>
<p>It is possible (but messy) to test the returned object for it's actual type (i.e. "if someObject is ChildProp"), but it is better to call a virtual method on it that does the right thing for its type.</p>
<p>The base class virtual method (in this case, virtual property) not only has an implementation, but also defines a contract: that a child class can supply a different implementation of SomePropertyName if it meets this contract (i.e. SomePropertyName returns an object of type "FatherProp"). Returning an object of type "ChildProp" derived from "FatherProp" meets this contract. But you can't change the contract in "Child" - this contract applies to all classes descended from "Father".</p>
<p>If you take a step back and look at your broader design, there are other language constructs in the C# toolkit that you may also want to think about instead - Generics, or interfaces.</p>
| 19,013
|
<p>I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?</p>
|
<pre><code>>>> import struct
>>> struct.pack('f', 3.141592654)
b'\xdb\x0fI@'
>>> struct.unpack('f', b'\xdb\x0fI@')
(3.1415927410125732,)
>>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0)
'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'
</code></pre>
|
<p>I would add a comment but I don't have enough reputation.</p>
<p>Just to add some info. If you have a byte buffer containing X amount of floats, the syntax for unpacking would be:</p>
<pre><code>struct.unpack('Xf', ...)
</code></pre>
<p>If the values are doubles the unpacking would be:</p>
<pre><code>struct.unpack('Xd', ...)
</code></pre>
| 2,731
|
<p>The Eclipse <a href="http://www.eclipse.org/projects/project_summary.php?projectid=tools.ve" rel="noreferrer">Visual Editor</a> project seems to be dead, no commits, no updates. Any one know what is happening?</p>
|
<p><strong>Update 2:</strong> The project <a href="http://www.eclipse.org/archived/" rel="nofollow noreferrer">has been archived</a> (i.e. dead) since June 2011 again.</p>
<p><strong>Update:</strong> The project <a href="http://dev.eclipse.org/mhonarc/lists/ve-dev/msg01818.html" rel="nofollow noreferrer">has been revived</a> and is now under active development again.</p>
<p>Its pretty much dead due to a lack of developer support. Here are <a href="http://dev.eclipse.org/mhonarc/lists/ve-dev/msg01748.html" rel="nofollow noreferrer">some</a> <a href="http://dev.eclipse.org/mhonarc/lists/ve-dev/msg01742.html" rel="nofollow noreferrer">recent</a> posts from their mailing list talking about a lack of movement on the project.</p>
|
<p>WindowBuilder can be a good alternative. I had several problems with VE and I end up with WindowBuilder who worked for me perfectly.</p>
<p><a href="http://www.eclipse.org/windowbuilder/" rel="nofollow">http://www.eclipse.org/windowbuilder/</a></p>
| 41,272
|
<p>I'm using a QTableWidget to display several rows. Some of these rows should reflect an error and their text color is changed :</p>
<p>Rows reflecting that there is no error are displayed with a default color (black text on white background on my computer).<br>
Rows reflecting that there is an error are displayed with a red text color (which is red text on white background on my computer).</p>
<p>This is all fine as long as there is no selection. As soon as a row is selected, no matter of the unselected text color, the text color becomes always white (on my computer) over a blue background.</p>
<p>This is something I would like to change to get the following :<br>
When a row is selected, if the row is reflecting there is no error, I would like it to be displayed with white text on blue background (default behavior).<br>
If the row is reflecting an error and is selected, I would like it to be displayed with red text on blue background.</p>
<p>So far I have only been able to change the selection color for the whole QTableWidget, which is not what I want !</p>
|
<p>Answering myself, here is what I ended up doing : a delegate.</p>
<p>This delegate will check the foreground color role of the item. If this foreground color is not the default WindowText color of the palette, that means a specific color is set and this specific color is used for the highlighted text color.</p>
<p>I'm not sure if this is very robust, but at least it is working fine on Windows.</p>
<pre><code>class MyItemDelegate: public QItemDelegate
{
public:
MyItemDelegate(QObject* pParent = 0) : QItemDelegate(pParent)
{
}
void paint(QPainter* pPainter, const QStyleOptionViewItem& rOption, const QModelIndex& rIndex) const
{
QStyleOptionViewItem ViewOption(rOption);
QColor ItemForegroundColor = rIndex.data(Qt::ForegroundRole).value<QColor>();
if (ItemForegroundColor.isValid())
{
if (ItemForegroundColor != rOption.palette.color(QPalette::WindowText))
{
ViewOption.palette.setColor(QPalette::HighlightedText, ItemForegroundColor);
}
}
QItemDelegate::paint(pPainter, ViewOption, rIndex);
}
};
</code></pre>
<p>Here is how to use it :</p>
<pre><code>QTableWidget* pTable = new QTableWidget(...);
pTable->setItemDelegate(new MyItemDelegate(this));
</code></pre>
|
<p>You could, of course, inherit from the table widget and override the paint event, but I don't think that is what you want to do.</p>
<p>Instead, should use the <code>QAbstractItemDelegate</code> functionality. You could either create one to always be used for error rows, and set the error rows to use that delegate, or make a general one that knows how to draw both types of rows. The second method is what I would recommend. Then, your delegate draws the rows appropriately, even for the selected row.</p>
| 36,419
|
<p>I run all my integers through a <code>(int)Integer</code> to make them safe to use in my query strings.</p>
<p>I also run my strings through this function code:-</p>
<pre><code>if(!get_magic_quotes_gpc()) {
$string = mysql_real_escape_string($string);
}
$pattern = array("\\'", "\\\"", "\\\\", "\\0");
$replace = array("", "", "", "");
if(preg_match("/[\\\\'\"\\0]/", str_replace($pattern, $replace, $string))) $string = addslashes($string);
$cleanedString = str_replace('%','',$string);
</code></pre>
<p>I obviously return the $cleanedString variable. Now I replace the % character because it is a wildcard to mySQL and it could potentially slow down my queries (or make them return incorrect data) if the user inserted them. Are there any other special characters for mySQL I should be concerned about? </p>
<p>On a second note, is there anything wrong or redundant about my search and replace after the <code>mysql_real_escape_string</code>? I got it from a website when I was first starting out and (if I remember correctly) it said you had to use this search/replace in addition to the escape string. It looks like it's trying to remove any previously escaped injection characters?</p>
|
<p>yeah I think you've got things going a bit strangely there.</p>
<p>First of all, I'd check for magic quotes and <em>remove</em> the slashes if it's turned on. That way you've got a string which actually represents the information you want (and not one that has been treated with slashes).</p>
<p>If you particularly want to remove the % wildcard then you could just escape that or remove it altogether. Before you insert the string into an SQL query, finally run it through mysql_real_escape_string, and everything will be fine.</p>
<pre><code>$string = $_POST['searchTerm'];
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
$string = str_replace("%", "", $string);
$safeString = mysql_real_escape_string($string);
</code></pre>
|
<p>On your second point:<br />
It is completely redundant, all the characters have been properly escaped if you run it through mysql_real_escape_string()</p>
| 44,044
|
<p>I've been writing C / C++ code for almost twenty years, and I know Perl, Python, PHP, and some Java as well, and I'm teaching myself JavaScript. But I've never done any .NET, VB, or C# stuff. What exactly does <strong>managed</strong> code mean?</p>
<p>Wikipedia <a href="http://en.wikipedia.org/wiki/Managed_code" rel="noreferrer">describes it</a> simply as</p>
<blockquote>
<p>Code that executes under the management of a virtual machine</p>
</blockquote>
<p>and it specifically says that Java is (usually) managed code, so</p>
<ul>
<li><strong>why does the term only seem to apply to C# / .NET?</strong></li>
<li><strong>Can you compile C# into a .exe that contains the VM as well, or do you have to package it up and give it to another .exe (a la java)?</strong></li>
</ul>
<p>In a similar vein,</p>
<ul>
<li><strong>is .NET a <em>language</em> or a <em>framework</em>, and what exactly does "framework" mean here?</strong></li>
</ul>
<p>OK, so that's more than one question, but for someone who's been in the industry as long as I have, I'm feeling rather N00B-ish right now...</p>
|
<p>When you compile C# code to a .exe, it is compiled to Common Intermediate Language(CIL) bytecode. Whenever you run a CIL executable it is executed on Microsofts Common Language Runtime(CLR) virtual machine. So no, it is not possible to include the VM withing your .NET executable file. You must have the .NET runtime installed on any client machines where your program will be running.</p>
<p>To answer your second question, .NET is a framework, in that it is a set of libraries, compilers and VM that is not language specific. So you can code on the .NET framework in C#, VB, C++ and any other languages which have a .NET compiler. </p>
<p><a href="https://bitbucket.org/brianritchie/wiki/wiki/.NET%20Languages" rel="noreferrer">https://bitbucket.org/brianritchie/wiki/wiki/.NET%20Languages</a></p>
<p>The above page has a listing of languages which have .NET versions, as well as links to their pages.</p>
|
<p>Managed Code--MSIL and IL and Managed Code are same.When we build our application the .dll or .exe files are generated in the Bin folder.These files are called as Managed code.Later these files are given to CLR to generate Native code which would be understood by OS.</p>
| 8,238
|
<p>In previous releases there were 3 ways to pass data from controller to view AFAIK (shown below). </p>
<p>I want to use method (2) with MVC Beta 1, but I can't find the renderView method. So what's the new syntax (if it's still possible)? Thanks in advance.</p>
<p>Ben.</p>
<p>Syntax #1: Old-school dictionary</p>
<pre><code>ViewData["Name"] = "Moo-moo";
ViewData["Age"] = 6;
ViewData["HasFunnyFace"] = true;
RenderView("ShowCat");
</code></pre>
<p>Syntax #2: Explicitly-typed ViewData object</p>
<pre><code>RenderView("ShowCat", new ShowCatViewData {
Name = "Moo-moo",
Age = 6,
HasFunnyFace = true
});
</code></pre>
<p>Syntax #3: Anonymously-typed object</p>
<pre><code>RenderView("ShowCat", new {
Name = "Moo-moo",
Age = 6,
HasFunnyFace = true
});
</code></pre>
|
<p>In beta 1, use the View method:</p>
<pre><code>return View ("ShowCat", <TYPED_DATA_SET_OR_OTHER_MODEL>);
</code></pre>
<p>The View method has replaced the RenderView method.</p>
|
<p>Following from Kieron's comment, in Visual Studio 2008 (maybe 2005/VSE?), when you right click on your controller action, you can choose 'Add View' at the top of the context menu.</p>
<p>This brings up a little dialog box, which will allow you to create a strongly typed view by specifying it.</p>
| 38,191
|
<p>Last Friday where I work, an oracle client was upgarded and our IIS server from version 9 to version 10. Now that its on version 10, we are seeing a lot of connections being open up to the database. It is opening up so many connections that we cannot log onto the database using tools like PlSQL developer or Toad. We never had an issue like this when the oracle client was at version 9. Because of the number of clients that exists on this particular box, i dont think it will be possible to revert back to the Oracle 9 client.
Is anyone aware of this problem or know of any possible work arounds?</p>
<p>Any help is greatly appreciated</p>
|
<p>lex/flex and yacc/bison provide easy-to-use, well-understood lexer- and parser-generators, and I'd really recommend doing something like that as opposed to doing it procedurally in e.g. Perl. Regular expressions are powerful stuff for ripping apart strings with relatively-, but not totally-fixed structure. With any real programming language, the size of your state machine gets to be simply unmanageable with anything short of a Real Lexer/Parser (tm). Imagine dealing with all possible interleavings of keywords, identifiers, operators, extraneous parentheses, extraneous semicolons, and comments that are allowed in something like Verilog AMS, with regular expressions and procedural code alone.</p>
<p>There's no denying that there's a substantial learning curve there, but writing a grammar that you can use for flex and bison, and doing something useful on the syntax tree that comes out of bison, will be a much better use of your time than writing a ton of special-case string-processing code that's more naturally dealt with using a syntax-tree in the first place. Also, what you learn writing it this way will truly broaden your skillset in ways that writing a bunch of hacky Perl code just won't, so if you have the means, I highly recommend it ;-)</p>
<p>Also, if you're lazy, check out the Eclipse plugins that do syntax highlighting and basic refactoring for Verilog and VHDL. They're in an incredibly primitive state, last I checked, but they may have some of the code you're looking for, or at least a baseline piece of code to look at to better inform your approach in rolling your own.</p>
|
<p>In trying to find my answer, I found this on <a href="http://www.ibm.com/developerworks/edu/au-dw-au-parsingwithantlr-i.html" rel="nofollow noreferrer">ANTLR</a> - might be of use</p>
| 9,615
|
<p>I'm scanning through a file looking for lines that match a certain regex pattern, and then I want to print out the lines that match but in alphabetical order. I'm sure this is trivial but vbscript isn't my background</p>
<p>my array is defined as</p>
<pre><code>Dim lines(10000)
</code></pre>
<p>if that makes any difference, and I'm trying to execute my script from a normal cmd prompt</p>
|
<p>From <a href="http://www.microsoft.com/technet/scriptcenter/funzone/games/tips08/gtip1130.mspx#E4C" rel="noreferrer">microsoft</a></p>
<p>Sorting arrays in VBScript has never been easy; that’s because VBScript doesn’t have a sort command of any kind. In turn, that always meant that VBScript scripters were forced to write their own sort routines, be that a bubble sort routine, a heap sort, a quicksort, or some other type of sorting algorithm.</p>
<p>So (using .Net as it is installed on my pc):</p>
<pre><code>Set outputLines = CreateObject("System.Collections.ArrayList")
'add lines
outputLines.Add output
outputLines.Add output
outputLines.Sort()
For Each outputLine in outputLines
stdout.WriteLine outputLine
Next
</code></pre>
|
<p>I actually just had to do something similar but with a 2D array yesterday. I am not that up to speed on vbscript and this process really bogged me down. I found that the articles <a href="https://web.archive.org/web/20180927040044/http://www.4guysfromrolla.com:80/webtech/011001-1.shtml" rel="nofollow noreferrer">here</a> were very well written and got me on the road to sorting in vbscript.</p>
| 33,719
|
<p>Following Jonathan Holland's suggestion in his comment for my previous question: <a href="https://stackoverflow.com/questions/137360/is-there-any-way-in-net-to-programmatically-listen-to-http-traffic">Is there any way in .NET to programmatically listen to HTTP traffic?</a> I've made a separate (but not exactly a duplicate) question for what I <em>really</em> want to know:</p>
<p><strong>How do I automate a web proxy in .NET for unit tests</strong> (including set up and tear down) for spying on HTTP traffic that comes from the browser (particularly images, scripts, and XmlHttpRequests on the requested page)?</p>
<p>I prefer to have zero set-up (so no Fiddler installed on Windows) where everything can be unpacked from an assembly, deployed, and then removed without a trace, so to speak.</p>
|
<p>WebAii 2.0 has a built-in HTTP proxy:</p>
<p><a href="http://www.artoftest.com/community/blogs/09-03-25/WebAii_2_0_Beta_Released.aspx" rel="nofollow noreferrer">http://www.artoftest.com/community/blogs/09-03-25/WebAii_2_0_Beta_Released.aspx</a></p>
|
<p>I'm not sure if it's what you're looking for, but here is an example of ASP.NET unit testing using selenium.
<a href="http://www.stevetrefethen.com/blog/AutomatedTestingOfASPNETWebApplicationsUsingSelenium.aspx" rel="nofollow noreferrer">http://www.stevetrefethen.com/blog/AutomatedTestingOfASPNETWebApplicationsUsingSelenium.aspx</a></p>
| 16,624
|
<p>I need to come up with a solution for users to be able to paste an image on to a website, then upload that image on to the web server. I'm not sure what the right solution for this - I am pretty sure javascript is out of the question because I don't think it can handle binary clipboard data (or any clipboard data?)</p>
<p>So, I'm not sure which way to go with this. Is this something possible with a Java applet? Or maybe a Flash SWF? Any other alternatives?</p>
|
<p>Or this <a href="http://lassebunk.dk/2009/08/04/clipboard-java-applet/" rel="nofollow noreferrer">free one</a> (via another StackOverflow question)</p>
|
<p><a href="http://www.radinks.com/upload/applet.php" rel="nofollow noreferrer">Rad Upload</a> (java applet). It's not free, but it is relatively cheap.</p>
| 47,153
|
<p>I am trying to get some <code>JavaScript</code> to programmatically adjust a HTML <code>img</code> tag's width to display various sized images correctly.</p>
<p>I have a fixed width <code>img</code> tag at <code>800px</code> to display an image, this is the max width.</p>
<p>If the image is wider then <code>800px</code> I want to display it at <code>800px</code> wide;</p>
<p>If the image is less than <code>800px</code> wide I want to preserve its width to avoid stretching it.</p>
<p>I use this html/javacript code to get a partial solution:</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>function resize_image(id) {
var img = document.getElementById(id);
var normal_width = img.width;
img.removeAttribute("width");
var real_width = img.width;
if (real_width < normal_width) {
img.width = real_width;
} else {
img.width = normal_width;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="myimage" onload="resize_image(self.id);" src="https://via.placeholder.com/350x150" width="800" /></code></pre>
</div>
</div>
</p>
<p>The above code seems to work on all browsers I have tested except <code>Safari</code> (images don't display unless you refresh the page).</p>
<p>I know I can use CSS <code>max-width</code> but that wont work on <code>IE</code> < 7 which is a show stopper.</p>
<p>How can I get this working for all browsers? Many thanks in advance.</p>
|
<p>I have never seen a safari in work, but you can try changing your onload event to this:</p>
<pre><code>onload="resize_image(self.id);return true"
</code></pre>
<p>It could be that without a return value, safari thinks that this object should not be loaded.</p>
|
<p>Have you tried monkey with <code>img.style.width</code>? You could also try having 2 CSS classes for each of the 2 conditions and programmaticly change them. </p>
| 48,548
|
<p>I need an equivalent to c++'s <code>std::multimap<K, V, Comp, Alloc></code> in C-sharp. Does it exist in the standard library?</p>
|
<p>Because it's almost christmas :)</p>
<pre><code>//////////////////////////////////////////////////////////////////////
// Algorithmia is (c) 2008 Solutions Design. All rights reserved.
// http://www.sd.nl
//////////////////////////////////////////////////////////////////////
// COPYRIGHTS:
// Copyright (c) 2008 Solutions Design. All rights reserved.
//
// The Algorithmia library sourcecode and its accompanying tools, tests and support code
// are released under the following license: (BSD2)
// ----------------------------------------------------------------------
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1) Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2) Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY SOLUTIONS DESIGN ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SOLUTIONS DESIGN OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the authors
// and should not be interpreted as representing official policies, either expressed or implied,
// of Solutions Design.
//
//////////////////////////////////////////////////////////////////////
// Contributers to the code:
// - Frans Bouma [FB]
//////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SD.Tools.Algorithmia.UtilityClasses;
namespace SD.Tools.Algorithmia.GeneralDataStructures
{
/// <summary>
/// Extension to the normal Dictionary. This class can store more than one value for every key. It keeps a HashSet for every Key value.
/// Calling Add with the same Key and multiple values will store each value under the same Key in the Dictionary. Obtaining the values
/// for a Key will return the HashSet with the Values of the Key.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
public class MultiValueDictionary<TKey, TValue> : Dictionary<TKey, HashSet<TValue>>
{
/// <summary>
/// Initializes a new instance of the <see cref="MultiValueDictionary&lt;TKey, TValue&gt;"/> class.
/// </summary>
public MultiValueDictionary()
: base()
{
}
/// <summary>
/// Adds the specified value under the specified key
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public void Add(TKey key, TValue value)
{
ArgumentVerifier.CantBeNull(key, "key");
HashSet<TValue> container = null;
if(!this.TryGetValue(key, out container))
{
container = new HashSet<TValue>();
base.Add(key, container);
}
container.Add(value);
}
/// <summary>
/// Determines whether this dictionary contains the specified value for the specified key
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>true if the value is stored for the specified key in this dictionary, false otherwise</returns>
public bool ContainsValue(TKey key, TValue value)
{
ArgumentVerifier.CantBeNull(key, "key");
bool toReturn = false;
HashSet<TValue> values = null;
if(this.TryGetValue(key, out values))
{
toReturn = values.Contains(value);
}
return toReturn;
}
/// <summary>
/// Removes the specified value for the specified key. It will leave the key in the dictionary.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public void Remove(TKey key, TValue value)
{
ArgumentVerifier.CantBeNull(key, "key");
HashSet<TValue> container = null;
if(this.TryGetValue(key, out container))
{
container.Remove(value);
if(container.Count <= 0)
{
this.Remove(key);
}
}
}
/// <summary>
/// Merges the specified multivaluedictionary into this instance.
/// </summary>
/// <param name="toMergeWith">To merge with.</param>
public void Merge(MultiValueDictionary<TKey, TValue> toMergeWith)
{
if(toMergeWith==null)
{
return;
}
foreach(KeyValuePair<TKey, HashSet<TValue>> pair in toMergeWith)
{
foreach(TValue value in pair.Value)
{
this.Add(pair.Key, value);
}
}
}
/// <summary>
/// Gets the values for the key specified. This method is useful if you want to avoid an exception for key value retrieval and you can't use TryGetValue
/// (e.g. in lambdas)
/// </summary>
/// <param name="key">The key.</param>
/// <param name="returnEmptySet">if set to true and the key isn't found, an empty hashset is returned, otherwise, if the key isn't found, null is returned</param>
/// <returns>
/// This method will return null (or an empty set if returnEmptySet is true) if the key wasn't found, or
/// the values if key was found.
/// </returns>
public HashSet<TValue> GetValues(TKey key, bool returnEmptySet)
{
HashSet<TValue> toReturn = null;
if(!base.TryGetValue(key, out toReturn) && returnEmptySet)
{
toReturn = new HashSet<TValue>();
}
return toReturn;
}
}
}
</code></pre>
|
<p>Consider using <a href="http://www.codeproject.com/Articles/612301/The-List-Trifecta-Part-2" rel="nofollow"><code>BMultiMap<K,V></code></a> if your collection as a whole is large. It saves a lot of memory compared to <code>Dictionary<K,List<V>></code>, especially if the number of values associated with each key is often small.</p>
| 49,873
|
<p>I'm not really sure where to ask this question as I think it is a design question, but also a printing question. So if there is a better place to post, I'd be happy to harass someone else.<br>
I'm (re)designing a sprinkler manifold for a dripper system because the stupid pegs for this <a href="https://rads.stackoverflow.com/amzn/click/com/B00M0UG9SK" rel="nofollow noreferrer" rel="nofollow noreferrer">stupid manifold</a> are on top of the manifold, which is a prime spot for any old postal person/dog/raindrop to break off. Of course the pegs aren't sold separately so you have to buy a whole new manifold. Seems like a great use for a 3D printer. </p>
<p><a href="https://i.stack.imgur.com/t5VuH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t5VuH.jpg" alt="sprinkler pegs"></a></p>
<p>I designed a new manifold and decided the pegs were useful in case they broke off. I was thinking having them screw in would be a better design, but for the life of me I can't get them to actually screw in after I print.
<a href="https://www.dropbox.com/s/9cy2vbtc8r8j47g/MushroomManifold%20FO%20real-%20i2%20v4.f3d?dl=0" rel="nofollow noreferrer">Here</a> is the fusion 360 file.
This is generally what it looks like:
<a href="https://i.stack.imgur.com/gam5D.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gam5D.jpg" alt="MushroomManifold"></a>
And <a href="https://www.dropbox.com/s/e1edw8pbpw64j20/MushroomManifold.stl?dl=0" rel="nofollow noreferrer">here</a> is the resulting stl file. </p>
<p>After several prints, the pegs won't screw into the manifold base. I push and I turn and turn but the threads just won't bite. The 3/4" pipe threads fit just fine, so I know threads can be printed, but these pegs are stubborn. </p>
<p>I guess my question is, what's a good design for a peg thingy that needs to attach into a manifold, but also pass water? Should I try to replicate the cantilever thing they have going on, or is a screw better? Any ideas why my pegs won't screw into the base of my mushroom? This is my first attempt at 3d modeling so I'm not totally familiar with all the terminology, so any pointers there would be helpful.
Thanks!</p>
|
<p>I examined and sliced your STL file, and the profile of your threads looks very strange.</p>
<p>It's definitely possible to do very strong, perfectly-fitting threads down to small sizes (at least down to M4 or slightly smaller) using modern inexpensive 3D printers, and contrary to widespread belief (there's a well-known YouTube comparison with a major test fallacy claiming otherwise) they should usually be stronger than threaded inserts against being pulled out. But you need to get the thread profile exactly right.</p>
<p>Most real thread profiles are trapezoidal, but yours peak at points and have round bases. This is unlikely to match the external thread on the part you're trying to fit to it, and it's going to have major dimensional accuracy issues because of the sharp point which can't necessarily be represented in the layer resolution.</p>
<p>I'm not familiar with Fusion 360 so I don't know how to tell you exactly, but most CAD software has libraries for generating threads conforming to standard thread profiles. If you want to do 3D printed threads, you should look at those and figure out which one you're trying to match. Or, if you want to replace the pegs with your own design anyway, just pick a reasonable one for both.</p>
<p>Generally, most modern threads use the basic <a href="https://en.wikipedia.org/wiki/ISO_metric_screw_thread" rel="nofollow noreferrer">ISO metric thread profile</a>, even if they're not standard metric diameter or pitch:</p>
<p><a href="https://i.stack.imgur.com/5TTOQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5TTOQ.png" alt="ISO Metric Thread Profile diagram"></a></p>
<p>Your cross-sections should look roughly like the "internal thread" side of that.</p>
|
<p>If I may suggest a slight alternative: don't try to make the threads part of the 3Dprint. Instead, thicken the walls where the threads would have been, increasing the ID (inner diameter) of the hole, maybe even "thread" to match the outside of : metal <a href="https://www.homedepot.com/p/Everbilt-1-4-in-20-tpi-x-20-mm-Zinc-Plated-Screw-in-Type-E-Insert-Nut-4-Pack-817798/204804833" rel="nofollow noreferrer">threaded inserts</a>. Those can be screwed in, .<br>
Perhaps a small "<a href="https://www.homedepot.com/p/Everbilt-6-32-Coarse-Zinc-Plated-Steel-Tee-Nut-4-per-Pack-802261/204274190" rel="nofollow noreferrer">T-nut</a>" (pick the size you need) would be sufficient, and you could create holes in your printed part for the penetration tips. </p>
| 1,327
|
<p>I have a copy of emacs that I use on a couple of different (windows) computers from a thumb drive, and I am wondering if it is possible to create something that is sort of the equivalent of a bash alias or symlink within emacs? Something that I could use within find-file is the main thing that i'm looking for, so for example: <code>C-f <some link></code> would take me somewhere. Currently I have to add a new defun every time i get to a new computer, which is just kind of a pain and I would <em>swear</em> i've seen this somewhere, but months of googling have turned up nothing.</p>
<p>What i've got right now is something like:</p>
<pre><code>(defun go-awesome ()
"Find my way to my work home"
(interactive)
(find-file "c:/cygwin/home/awesome"))
</code></pre>
<p>But that feels increadibly overdone and hacky for just visiting a fairly hacky for just visiting a file that i visit semi-regularly. And it requires a lot of effort to set up a new file.</p>
<p>The biggest problem with it though, in my opinion is that it doesn't fit in my workflow. When i want to visit a file i always do <code>C-x C-f</code>, and if i realize that "hey i'm at work" i then have to <code>C-g M-x go-awesome</code>. Perhaps it would be more clear if i said that i wanted to be able to do something that is the equivalent of an <code>ln -s /some/awesome/dir</code> but internal to emacs, instead of built into the OS, so that <code>C-x C-f ~/awesome/some/sub/dir</code> would work on windows or anywhere else.</p>
|
<p>I'm not really clear on what you're asking for. I store my commonly-used files in registers in my .emacs:</p>
<pre><code>(set-register ?c '(file . "c:/data/common.txt"))
(set-register ?f '(file . "c:/data/frequent.txt"))
</code></pre>
<p>Then I can jump to a file with <code>jump-to-register</code> (<code>C-x r j</code>):</p>
<p>For example, "<code>C-x r j c</code>" takes me to <code>c:/data/common.txt</code> (loading it if necessary).</p>
<p>Is that what you're looking for?</p>
|
<p><strong><em>I Moved this into the original question, but i'm leaving it here because people responded to it already</em></strong></p>
<p>That's way better than what i've got, but what i feel like probably exists is something that would replace, for example:</p>
<pre><code>(defun nuke ()
"alias delete-trailing-whitespace"
(interactive)
(delete-trailing-whitespace))
</code></pre>
<p>and feel less hacky, and like it was actually doing what it was supposed to be doing, instead of doing something really heavy for what feels like something that should be really light.</p>
<p>Does that make sense?</p>
<p>Your assign to registers might actually be better than what i'm looking for, though.</p>
| 21,199
|
<p>Right up front: I do <em>not</em> want to start a religious war.</p>
<p>I've used <em>vi</em> for as long as I can remember, and the few times I've tried to pick up <em>Emacs</em> I've been so lost that I've quickly given up. Lots of people find Emacs very powerful, however. Its programmability is somewhat legendary. I'm primarily doing Solaris+Java development, and I'd like to ask a simple question: will my productivity increase if I invest time in getting my head around Emacs? Is the functionality that it offers over <em>Vim</em> going to be paid back in productivity increases in a reasonable timeframe?</p>
<p><em>Repeat: I don't want a "my editor is better than yours" answer. I just want a yes or no answer as to whether it's worth investing the time or not. Will my productivity really increase?</em></p>
|
<p>I prefer emacs to vi, but I'm comfortable in both. </p>
<p>There are some things that you can do in emacs that make it more powerful than vi, but not all of them are even programming-related. (Can you send email or read news from within vi? No, but who cares?) If you're comfortable with lisp (I'm not), you might be able to write add-ons and modes and stuff to make your life easier, but that's just likely to be syntax colouring and brace matching and eye candy like that.</p>
<p>I will stop rambling now. Will your <strong>productivity</strong> increase using emacs? No.</p>
<p><strong>Update</strong>: See my comment below. Since I posted this, I <em>have</em> come across ways that using emacs has made me more productive than using vi.</p>
|
<p>I really see no reason to switch. I've used vi for a long time and am quite comfortable with it; about every six months I would install emacs to give it a go, then quickly just switch back. Yes there were things I much preferred about vi, but the main reason I never stuck with it is because the time investment to fully learn another editor when I already know an extremely capable one isn't worth it.<br>
I'm reminded of this <a href="http://www.users.qwest.net/~eballen1/knottenbelt.txt" rel="nofollow noreferrer">rather dated study.</a></p>
<p>In my opinion, SLIME is about the only reason to switch to emacs if you're already proficient with vi.</p>
| 7,036
|
<p>At home, I use CTRL+SHIFT+B or F7 or whatever key sequence initiates the build for my build tool. At work, this doesn't quite cut it.</p>
<p>At my first job (an internship) we used a product called Visual Build, which I have come to like very much. It's the best build tool I've ever worked with. The down side here is that it's not free.</p>
<p>At my latest job, I came in knowing literally nothing about Ant. Now, unfortunately, I've become deeply involved in our build processes, and cannot extricate myself. It works, yes, but after coming from Visual build, it seems like it's fighting me every step of the way. Yes, it's free, but we're not trying to be a free-software-only development company or anything.</p>
<p>I've never looked in to <code>make</code> or any other build tools, so I don't really know what else is out there.</p>
<p>Has anybody ever seen or had experience with Visual Build? Mostly I'm fond of a few key things:</p>
<ol>
<li>it has a GUI</li>
<li>it runs arbitrary VBScript without the need of a compiled class</li>
<li>you can step through the build process, or start from anywhere in the middle.</li>
</ol>
<p>Are there any free build tools that have this? Is there any way to convince people that it's worth it to move on? It's 2008. We use IDEs to develop, why not (IBEs) to build?</p>
<p><b>Edit: </b> I'm mostly looking for an answer to my last questions; Is there a solution with a built-in GUI that I can use for free?</p>
|
<p>We use FinalBuilder - I think it's very similar to VisualBuild, though I've not used the latter. </p>
<p>It does run from the command line, and you can integrate it with CC.Net if you want.</p>
|
<p>Going back to the keystrokes thing for a sec, I found <a href="http://www.bcheck.net/apps/#hoekey" rel="nofollow noreferrer">Hoekey</a> which the CTO loves. I don't use it myself, but as a way of assign keystrokes to things, it's pretty good.</p>
| 41,520
|
<p>Here's the scenario. I'm using myopenid for, among other things, StackOverflow. When I initially set up my openid account with myopenid, I decided to try out Cardspace because they had support.</p>
<p>I later wanted to access Stackoverflow from another machine so I chose to back up my card. I gave it a password and a filename and successfully created a backup file. I was also to able successfully import it to my laptop.</p>
<p>Here is where the problem comes in - I am unable to use the card that I backed up from my laptop. The original card still works great on my desktop. Additional information is that my desktop is running Windows XP SP3 (x86) while my laptop is running Windows Vista (x64).</p>
<p>Any ideas? Am I doing something wrong? I'm seriously considering dropping Cardspace on myopenid and moving to a password solution with them instead.</p>
<p>Thanks!</p>
|
<p>It <em>should</em> work; however if you have 3.5SP1 on one machine and 3.5 or less on another there was an (unannounced) breaking change with the code to generate the unique ID from the card; which may explain why it doesn't work.</p>
<p>I would try sending a test transaction to <a href="https://sharpsts.com/demos/informationCardToken.aspx" rel="nofollow noreferrer">the SharpSTS test page</a> with only the PPID as the claim, and examine the token sent back; if the PPIDs differ then that's your problem.</p>
|
<p>In Cardspace, the card is locked to the computer. You can move it around by exporting/importing. The next version "Geneva" will allow you to store your cards in a directory service which is useful for those running Active Directory.</p>
| 8,136
|
<p>I'm reading the book "The Software Architect's Profession" by Marc and Laura Sewell (<a href="https://rads.stackoverflow.com/amzn/click/com/0130607967" rel="noreferrer" rel="nofollow noreferrer">Amazon link</a>) and it got me wondering whether a software architect is a part of the old non-agile BDUF approach.</p>
<p>Is there a place for software architects in an agile approach? I'm especially interested in Scrum.</p>
<p>BTW I currently am the Unix Application Architect for a major company.</p>
<p>cheers,</p>
<p>Rob</p>
|
<p>My role as architect in Scrum includes the following.</p>
<ol>
<li><p>Technical spikes -- proofs of concept -- how will we do that. ("It would be simpler if you'd simply using the SMTP library directly, it already wraps the existing SMTP libraries; writing your own wrapper around our wrapper doesn't help much. We can add the method you want.")</p></li>
<li><p>Coordination among the developers to fit the intended architecture. ("Ummm... why are you using your own properties file?"</p></li>
<li><p>Working with users to prioritize the backlog appropriately. ("These three are related, if we do one, we get the other two at almost zero extra cost.")</p></li>
<li><p>Working with managers to cost the backlog. (No, a project manager can't do this; they don't have the technical depth. No, the programmers can't do this, they don't have the overview.)</p></li>
<li><p>Articulating why the package names are that way, and why the data model has those features.</p></li>
<li><p>Finding the things we're missing and reprioritizing the backlog on technical grounds ("We're going to need this additional sprint to integrate [X], upgrade [Y] and replace [Z] or we'll never get those sprints done.")</p></li>
</ol>
|
<p>I dont think there is the need as the SCRUM guide written by the original formants of SCRUM Dr Jeff Sutherland and Ken Schwaber doesnt mention the need for one. </p>
| 21,423
|
<p>Can anyone explaine me, what is MVC, why we use it and how we can use it. Benefits of using this? and can we use ASP.NET MVC in ASP.NET 2.0 (VS 2005)</p>
|
<p>You'll use MVC when you need total control over the HTML output from ASP.NET. It also allows for better/easier unit-testing. It is based on a Model View Controller architecture.</p>
<p>Scott Gutherie introduces it well here:
<a href="http://weblogs.asp.net/scottgu/archive/2007/10/14/asp-net-mvc-framework.aspx" rel="nofollow noreferrer">Scott Gu's Blog</a></p>
|
<p><strong>Asp.net MVC</strong> is based on MVC design pattern. Now Question is raised that what is <strong>MVC design pattern</strong>. MVC design pattern allows you to develop the application with loosely coupled components. It separates the application into different layers like <strong>Data</strong>, <strong>business logic</strong> and <strong>presentation logic</strong>.
To learn more about Asp.net MVC. Please go to the below link.</p>
<p><a href="https://youtu.be/m_9FnAc5k8c" rel="nofollow noreferrer">https://youtu.be/m_9FnAc5k8c</a></p>
| 48,715
|
<p>What causes the publish error:
"fl.getDocumentDOM() has no properties" ?</p>
<p>The error occurs only when using the "Test Project" button in the project pane. It doesn't cause the publish to fail, it's just annoying.</p>
|
<p><a href="http://www.w3.org/TR/css3-background/#the-border-radius" rel="nofollow noreferrer">CSS3 has <code>border-radius</code></a>.</p>
<p>For now, Mozilla- and WebKit-based browsers have experimental support, <code>-moz-border-radius</code> and <code>-webkit-border-radius</code>. It's not bad to use them now, as long as you understand they are temporary measures until they are properly implemented. I would expect it's not too long before you see full support for <code>border-radius</code> in Mozilla, Firefox and IE. (Well, hopefully IE.)</p>
<p><strong>Update:</strong> as of August 2016, with <a href="http://caniuse.com/#search=border-radius" rel="nofollow noreferrer">border-radius being natively available</a> in all native desktop browsers (and most mobile browsers, not to mention), the stringency of using <code>-moz-border-radius</code>, <code>-webkit-border-radius</code> and similar is being slowly relaxed.</p>
|
<p>Any CSS property that starts with a dash (e.g. <code>-moz</code>, <code>-webkit</code>) is a browser-specific property.</p>
<p>This allows browser vendors to experiment with new CSS properties. Doing so is a common part of the process for writing new CSS specs, to allow web developers to see how the properties work and raise issues.</p>
<p>Hence you’ll find a lot of CSS 3 properties, like <code>border-radius</code> currently implemented in some browsers with vendor-specific extensions.</p>
<p>There’s nothing particularly wrong with using these on production sites, as long as you’re aware they’ll only work in the one browser.</p>
<p>CSS 3 should be out any decade now :)</p>
| 42,751
|
<p>I have a set of applications that all rely on a cross-platform library (in-house development), and everything is stored in subversion. Now, this library is part of every app and as such a copy of it has to be in each app's working directory. </p>
<p>In order to be able to go back to any version of an app and have the correct version of the lib, one option would be to keep a copy of the lib in the project, however this is a nightmare to maintain. </p>
<p>More elegant seems to be to use subversion's <a href="http://svnbook.red-bean.com/en/1.5/svn.advanced.externals.html" rel="nofollow noreferrer">externals definitions</a> feature. However it seems to be necessary to use explicit revision numbers to make 100% sure that the correct revision is assigned (for example, if the trunk or a tag or a branch were specified without revision number, it seems you can't be 100% sure whether you will get EXACTLY the same revision as e.g. a year ago, as people can always commit on top of the trunk/branch/tag).</p>
<p>Now, this library is in constant development, as it is basically the heart of our multi-platform application. So maintaining the revisions in the svn:external prop will need constant updating. It is also common that devs will make changes to their local copy (bugfixes, new features) and then commit it. I am afraid now that if I set it up using revisions it will be harder to track down where exactly this commit is going (e.g. devs may lose track that the dep is on a branch; also when committing, it will be committed to the top of the trunk/branch, possibly skipping other commits by other devs).</p>
<p>Basically, it seems even with external definitions the devs working with that will still need to maintain a certain amount of constraint and control handling this (see e.g. this <a href="https://stackoverflow.com/questions/245337/how-can-i-branch-in-svn-and-have-it-branch-my-svnexternal-folders-as-well">example on SO</a>). Ideally they should be clever enough to do so, but (judging by myself) forgetting these small details is quite common and may cause a lot of headache later on.</p>
<p>So, what I am looking for is a really fool-proof solution (if there is one) to this problem of keeping this lib in sync with several projects in a way that I can go back in time and always get the correct versions together without having to constantly be on the watch.</p>
|
<p>The problem with your problem is that your library is not a library, at least not in a strict sense of the expression.</p>
<p>Your "library" is better described as a project that happens to be shared by the teams working on the different applications that rely on that core.</p>
<p>In this context, the biggest issue is not the subversion technique you may choose to use, but the way you organize your team in order to achieve a useful collaboration on that core component.</p>
<p>And the kind of problems that may arise are at least two. First, as the different applications may need different behaviors from your core, if they do not coordinate well, a perfectly valid commit from one team will break the other ones (continuous integration should help here).</p>
<p>But the second problem is harder to solve even with good inter-team communication, and it's related to the release management.</p>
<p>If the applications depending on this core are released at different points in time, you will have a hard time getting a stable core that is good enough for the release of one the apps while not halting the development of the rest.</p>
<p>My suggestion, have somebody dedicated to look after the core library. Use a branch of it in every project and let the applications developers to commit there while ensuring that they discuss the changes with everybody, specially the overseer of the lib.</p>
<p>And finally, make this library supervisor be in charge of coordinating the merges of the changes made by the different teams into the trunk of the library, thus generating stable, tested releases that will be used by the stable releases of your applications. And after every release of the core, spawn the next generation of branches into the rest of the projects.</p>
<p>It sounds like a lot of work compared with just defining an external and let everybody commit there. But actually, there is no point in hiding the fact that you must put some effort in keeping your core library coherent. If you don't do it upfront it will hunt you later.</p>
|
<p>You can use <a href="http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.advanced.vendorbr" rel="nofollow noreferrer">Vendor Branches</a>.</p>
| 32,660
|
<p>I am looking to print an enclosure, which will have a PCB inside with some LED indicators. I was wondering if it is possible to 3D print the enclosure such that the following look can be achieved? What material and technique?</p>
<p>When LEDs are off, it looks something like this:</p>
<p><a href="https://i.stack.imgur.com/eUN2v.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/eUN2v.jpg" alt="enter image description here"></a></p>
<p>WHen the LED turns on, it looks like this (illuminated symbols):</p>
<p><a href="https://i.stack.imgur.com/X9GuC.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/X9GuC.jpg" alt="enter image description here"></a></p>
|
<p>Achieving this with 3D printing would be quite difficult, and you might be better served by creating this effect some other way (I would personally recommend getting some inkjet transparencies and stacking a few layers together: an entirely black layer, and a few layers with the symbols in negative space).</p>
<p>One way that you <em>might</em> be able to achieve this using just a common FDM printer is to print the part face down, and printing just a single layer or two that covers the entire face, and then printing more layers that cover everything but the symbols. However, those symbols look small and detailed and you might not be able to reproduce such detail.</p>
|
<p>You can print the "lid" in translucent (gray) and stick a piece of laser printed transparency film under it with the symbols (print it "negative" so the symbols are transparent and the rest is black). Depending on the quality of the printed black you might want to stack two printouts to minimize light sipping through the black areas. A divider separating the leds underneath ensures that only one symbol lights up.</p>
<p>This will work better the better surface quality the "lid" has.</p>
| 358
|
<p>In this asp.net I'm cleaning up it's possible for deadlocks to occur. I want to make sure that the code deals with them properly, so I'm trying to write NUnit tests which trigger a deadlock.....</p>
<p>The DAO is split by entity. Each entity has a set of tests which are surrounded by Startup() and Teardown() methods which create a transactionscope and then roll it back after the tests are complete. This works great for everything else, but is completely useless for deadlocks.</p>
<p>How can I setup and run a "deadlock" test using TransactionScope and SQL2000 (ie MSDTC is involved) that can be reliably reproduced?
More detail: I know there is a situation whereby if two users call two functions with different, specific, data values then a deadlock <em>can</em> result. How can I simulate this within NUNIT - and make the deadlock <em>always</em> happen?</p>
<p>And yes, I did start with the "Why don't you stop the deadlocks happening in the first place" plan of action, but I have no control over the code where the deadlocks can occur - I just call the functions and they can deadlock.</p>
|
<p>If your deadlock results in an exception being thrown, you want to use a Mock Object to emulate the exception being thrown.</p>
<p>The basic idea is that you tell your Mock Object framework (I like <a href="http://www.typemock.com/" rel="nofollow noreferrer">TypeMock</a>) to throw an exception instead, something like this:</p>
<pre><code>MockObject mo = MockManager.MockObject(typeof(MyDeadlockException));
mock.ExpectAndThrow("MyMethod", (MyDeadlockException)mo.Object);
</code></pre>
<p>The idea is basically the same for other mocking frameworks.</p>
|
<p>What if one of your tests in the middle of your transaction just does a "wait" for like 5 minutes? Or, you simply write a test that starts a transaction, creates a new record, and then updates that record without committing. Then, start a new transaction in and try to read that record that was created and is currently being updated. You'll get a deadlock there.</p>
| 21,564
|
<p>I just purchased this Ender 3 Pro about 1 week ago and since then I've been having nightmares with leveling/tramming the printer bed. From having to tram it again after every print to not being able to level it at all.
Since then I've been reading and watching a lot of problem-related content to try and find a solution.</p>
<p>The two most recommended upgrades were a glass bed and stiffer springs for the bed so that's what I bought. I purchased the original Creality glass bed and the yellow springs and for a day or so I got it to work in an acceptable way but I still had to tram the bed every couple of prints.
Today for some unknown reason, I woke up and I can't seem to get my bed leveled in the middle. I've tried every possible solution that crossed my mind but the middle of the bed is still too far from the nozzle and the filament won't stick.</p>
|
<p>This is an old hotend type, it is called a <a href="https://www.google.com/search?q=j+head+nozzle" rel="noreferrer">J-Head</a> (see e.g. the <a href="https://reprap.org/wiki/J_Head_Nozzle#Mk_V" rel="noreferrer">J-Head Nozzle Mk V</a>, I'm unsure which exact version you have). The hotend is serviceable, you can buy separate "nozzles" (with integrated heater block) for it in <a href="https://www.123-3d.nl/3D-printer-onderdelen/Extruder/J-Head-p388.html" rel="noreferrer">some e-shops</a>. You should be able to unscrew the "nozzle" from the PEEK nozzle holder. The milled flat surfaces indicate that you can use a 13 mm or 1/2" open-end wrench to disassemble the PEEK nozzle holder.</p>
<p>The "nozzle":</p>
<p><a href="https://i.stack.imgur.com/a3MXz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/a3MXz.png" alt="enter image description here" /></a></p>
<p>The instruction to assemble such a hotend are:</p>
<blockquote>
<p><strong>Mk V</strong></p>
<ol>
<li>Secure the brass nozzle in a vise by the heater section.</li>
<li>Wrap a couple of turns of PTFE tape (plumbing tape) around the brass threads.</li>
<li>Screw the nozzle holder down onto the nozzle. If no flats are milled, use a pair of pliers to tighten the nozzle. The nozzle holder can be protected from the pliers by first wrapping it with a rag or paper towel. If there are flats milled, a 13 mm (1/2") open-end wrench can be used to tighten the nozzle.</li>
<li>Remove the brass nozzle from the vise.</li>
<li>Slide the PTFE liner down into the nozzle holder. The PTFE liner needs to be inserted such that the flat end is making contact with the brass and the internally tapered end is towards the top.
Install the washer.</li>
<li>Screw in the hollow-lock socket set screw. Ensure that the washer stays centered while tightening this set screw. Use a piece of filament to ensure that the set screw is not too tight as the liner can become compressed and obstruct the passage. If this happens, slightly loosen the set screw.</li>
</ol>
</blockquote>
<p>To disassemble you need to reverse the order.</p>
<p>You need to ask yourself it you want to change to a newer type of hotend, but generally, these are higher, e.g. compared to a V6:</p>
<p><a href="https://i.stack.imgur.com/2XnBm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2XnBm.png" alt="enter image description here" /></a></p>
|
<p>Not exactly the type of answer you probably want, but this hotend does not look servicable. The nozzle is usually considered a consumable part unless it's made of something like tungsten carbide, or at least steel. The nozzle is almost surely long past its useful life unless the printer was barely used, and the entire hotend has lots of design flaws like very small thermal mass and heat sink butting up against the heater block, which defeats the purpose of having a heat sink.</p>
<p>The right solution here is to figure out what kind of attachment it's supposed to use (dimensions of that groove mount) and buy or put together a replacement hotend.</p>
| 2,210
|
<p>I am a new to the prefuse visualization toolkit and have a couple of general questions. For my purpose, I would like to perform an initial visualization using prefuse (graphview / graphml). Once rendered, upon a user click of a node, I would like to completely reload a new xml file for a new visualization. I want to do this in order to allow me to "pre-package" graphs for display. </p>
<p>For example. If I search for Ted. I would like to have an xml file relating to Ted load and render a display. Now in the display I see that Ted has nodes associated called Bill and Joe. When I click Joe, I would like to clear the display and load an xml file associated with Joe. And so on. </p>
<p>I have looked into loading one very large xml file containing all node and node relationship info and allowing prefuse to handle this using the hops from one level to another. However, eventually I am sure that system performance issues will arise due to the size of data.</p>
<p>Thanks in advance for any help,
John </p>
|
<p>Of course as you said, one option is loading all nodes and then set the nodes you don't need to be invisible. Prefuse scales fairly well, but of course it has its limits. The second option is to just create a brand new panel and replace the old panel. I've used the option 2 and it works quite well.</p>
|
<p>I'm far from an expert on Prefuse's performance issues, but I think it is definitely more resource intensive to have a huge xml file loaded at once than to do the processing to only re-load the necessary nodes. </p>
<p>I don't know what kind of graph you are using, but I would place a 'refreshGraph' that removes the graph from the Visualization object, cancels Activity, cancels Layout, refreshes the ActionList and re-starts over. It would probably turn out something like this:</p>
<pre><code>public void refresh(clickedNode){
visualization.removeGroup(GRAPH);
visualization.removeGroup(AGGR);
activity.cancel();
actionList.cancel();
visualization.reset();
// process the XML and reload your graph here
}
</code></pre>
| 21,316
|
<p>Is there any way to reboot the JVM? As in don't actually exit, but close and reload all classes, and run main from the top?</p>
|
<p>Your best bet is probably to run the java interpreter within a loop, and just exit. For example:</p>
<pre><code>#!/bin/sh
while true
do
java MainClass
done
</code></pre>
<p>If you want the ability to reboot or shutdown entirely, you could test the exit status:</p>
<pre><code>#!/bin/sh
STATUS=0
while [ $STATUS -eq 0 ]
do
java MainClass
STATUS=$?
done
</code></pre>
<p>Within the java program, you can use System.exit(0) to indicate that you want to "reboot," and System.exit(1) to indicate that you want to stop and stay stopped.</p>
|
<p>AFAIK there is no such way. </p>
<p>Notice that if there were a way to do that, it would highly depend on the current loaded code to properly release all held resources in order to provide a graceful restart (think about files, socket/tcp/http/database connections, threads, etc).</p>
<p>Some applications, like Jboss AS, capture Ctrl+C on the console and provide a graceful shutdown, closing all resources, but this is application-specific code and not a JVM feature.</p>
| 32,396
|
<p>Having this route:</p>
<pre><code>map.foo 'foo/*path', :controller => 'foo', :action => 'index'
</code></pre>
<p>I have the following results for the <code>link_to</code> call</p>
<pre><code>link_to "Foo", :controller => 'foo', :path => 'bar/baz'
# <a href="/foo/bar%2Fbaz">Foo</a>
</code></pre>
<p>Calling <code>url_for</code> or <code>foo_url</code> directly, even with <code>:escape => false</code>, give me the same url:</p>
<pre><code>foo_url(:path => 'bar/baz', :escape => false, :only_path => true)
# /foo/bar%2Fbaz
</code></pre>
<p>I want the resulting url to be: <code>/foo/bar/baz</code></p>
<p>Is there a way around this without patching rails?</p>
|
<p>Instead of passing path a string, give it an array.</p>
<pre><code>link_to "Foo", :controller => 'foo', :path => %w(bar baz)
# <a href="/foo/bar/baz">Foo</a>
</code></pre>
<p>If you didn't have the route in your routes file, this same link_to would instead create this:</p>
<pre><code># <a href="/foo?path[]=bar&path[]=baz">Foo</a>
</code></pre>
<p>The only place I could find this documented is in <a href="http://dev.rubyonrails.org/ticket/7047" rel="nofollow noreferrer">this ticket</a>.</p>
|
<p>Any reason why you're needing to generate the URL with that path though?</p>
<p>It would be cleaner to just define an extra route to cover that URL.</p>
| 18,216
|
<p>How do I write a program that tells when my other program ends?</p>
|
<p>The only way to do a waitpid() or waitid() on a program that isn't spawned by yourself is to become its parent by ptrace'ing it.</p>
<p>Here is an example of how to use ptrace on a posix operating system to temporarily become another processes parent, and then wait until that program exits. As a side effect you can also get the exit code, and the signal that caused that program to exit.:</p>
<pre><code>#include <sys/ptrace.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char** argv) {
int pid = atoi(argv[1]);
int status;
siginfo_t si;
switch (ptrace(PTRACE_ATTACH, pid, NULL)) {
case 0:
break;
case -ESRCH:
case -EPERM:
return 0;
default:
fprintf(stderr, "Failed to attach child\n");
return 1;
}
if (pid != wait(&status)) {
fprintf(stderr, "wrong wait signal\n");
return 1;
}
if (!WIFSTOPPED(status) || (WSTOPSIG(status) != SIGSTOP)) {
/* The pid might not be running */
if (!kill(pid, 0)) {
fprintf(stderr, "SIGSTOP didn't stop child\n");
return 1;
} else {
return 0;
}
}
if (ptrace(PTRACE_CONT, pid, 0, 0)) {
fprintf(stderr, "Failed to restart child\n");
return 1;
}
while (1) {
if (waitid(P_PID, pid, &si, WSTOPPED | WEXITED)) {
// an error occurred.
if (errno == ECHILD)
return 0;
return 1;
}
errno = 0;
if (si.si_code & (CLD_STOPPED | CLD_TRAPPED)) {
/* If the child gets stopped, we have to PTRACE_CONT it
* this will happen when the child has a child that exits.
**/
if (ptrace(PTRACE_CONT, pid, 1, si.si_status)) {
if (errno == ENOSYS) {
/* Wow, we're stuffed. Stop and return */
return 0;
}
}
continue;
}
if (si.si_code & (CLD_EXITED | CLD_KILLED | CLD_DUMPED)) {
return si.si_status;
}
// Fall through to exiting.
return 1;
}
}
</code></pre>
|
<p>This is called the "halting problem" and is not solvable.
See <a href="http://en.wikipedia.org/wiki/Halting_problem" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Halting_problem</a></p>
| 15,280
|
<p>I'm sure you have all been there, you take on a project where there is a creaky old code base which is barely fit for purpose and you have to make the decision to either re-write it from scratch or repair what already exists. </p>
<p>Conventional wisdom tends to suggest that you should never attempt a re-write from scratch as the risk of failure is very high. So what did you do when faced with this problem, how did you make the decision and how did it turn out?</p>
|
<p>It really depends on how bad it is.</p>
<p>If it's a small system, and you fully understand it, then a rewrite is not crazy.</p>
<p>On the other hand, if it's a giant legacy monster with ten million lines of undocumented mystery code, then you're really going to have a hard time with a full rewrite.</p>
<p>Points to consider:</p>
<ul>
<li>If it looks good to the user, they
won't care what kind of spaghetti
mess it is for you. On the other
hand, if it's bad for them too, then
it's easier to get agreement (and
patience).</li>
<li>If you do rewrite, try to do it one
part at a time. A messy,
disorganized codebase may make this
difficult (i.e, replacing just one
part requires a rewrite of large
icebergs of dependency code), but if
possible, this makes it a lot easier
to gradually do the rewrite and get
feedback from users along the way.</li>
</ul>
<p>I would really hesitate to take on a giant rewrite project for a large system without being able to release the new edition one part at a time.</p>
|
<p>It's not so black and white... it really depends on a lot of factors (the more important being "what does the person paying you want you to do")</p>
<p>Where I work we re-wrote a development framework, and on the other hand, we keep modifying some old systems that cannot be migrated (because of the client's technology and time restrictions). In this case, we try to mantain the coding style and sometimes you have to implement a lot of workarounds because of the way it was built</p>
| 5,568
|
<p>When I type <code>git diff</code>, I want to view the output with my visual diff tool of choice (SourceGear "diffmerge" on Windows). How do I configure git to do this?</p>
|
<p>Since Git1.6.3, you can use the <strong>git difftool script</strong>: see <a href="https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/949242#949242">my answer below</a>.</p>
<hr>
<p>May be this <a href="https://web.archive.org/web/20170508180316/http://git.net:80/ml/version-control.msysgit/2008-06/msg00200.html" rel="noreferrer">article</a> will help you. Here are the best parts:</p>
<p>There are two different ways to specify an external diff tool. </p>
<p>The first is the method you used, by setting the GIT_EXTERNAL_DIFF variable. However, the variable is supposed to point to the full path of the executable. Moreover, the executable specified by GIT_EXTERNAL_DIFF will be called with a fixed set of 7 arguments:</p>
<pre><code>path old-file old-hex old-mode new-file new-hex new-mode
</code></pre>
<p>As most diff tools will require a different order (and only some) of the arguments, you will most likely have to specify a wrapper script instead, which in turn calls the real diff tool.</p>
<p>The second method, which I prefer, is to <strong>configure the external diff tool via "git
config"</strong>. Here is what I did:</p>
<p>1) Create a wrapper script "git-diff-wrapper.sh" which contains something like</p>
<pre><code>-->8-(snip)--
#!/bin/sh
# diff is called by git with 7 parameters:
# path old-file old-hex old-mode new-file new-hex new-mode
"<path_to_diff_executable>" "$2" "$5" | cat
--8<-(snap)--
</code></pre>
<p>As you can see, only the second ("old-file") and fifth ("new-file") arguments will be
passed to the diff tool.</p>
<p>2) Type</p>
<pre><code>$ git config --global diff.external <path_to_wrapper_script>
</code></pre>
<p>at the command prompt, replacing with the path to "git-diff-wrapper.sh", so your ~/.gitconfig contains</p>
<pre><code>-->8-(snip)--
[diff]
external = <path_to_wrapper_script>
--8<-(snap)--
</code></pre>
<p>Be sure to use the correct syntax to specify the paths to the wrapper script and diff
tool, i.e. use forward slashed instead of backslashes. In my case, I have</p>
<pre><code>[diff]
external = \"c:/Documents and Settings/sschuber/git-diff-wrapper.sh\"
</code></pre>
<p>in .gitconfig and</p>
<pre><code>"d:/Program Files/Beyond Compare 3/BCompare.exe" "$2" "$5" | cat
</code></pre>
<p>in the wrapper script. Mind the trailing "cat"!</p>
<p>(I suppose the '<code>| cat</code>' is needed only for some programs which may not return a proper or consistent return status. You might want to try without the trailing cat if your diff tool has explicit return status)</p>
<p>(<a href="https://stackoverflow.com/users/20520/diomidis-spinellis">Diomidis Spinellis</a> adds <a href="https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-my-preferred-diff-tool-viewer/255212#comment96247087_255212">in the comments</a>: </p>
<blockquote>
<p>The <code>cat</code> command is required, because <a href="http://man7.org/linux/man-pages/man1/diff.1.html" rel="noreferrer"><code>diff(1)</code></a>, by default exits with an error code if the files differ.<br>
Git expects the external diff program to exit with an error code only if an actual error occurred, e.g. if it run out of memory.<br>
By piping the output of <code>git</code> to <code>cat</code> the non-zero error code is masked.<br>
More efficiently, the program could just run <code>exit</code> with and argument of 0.)</p>
</blockquote>
<hr>
<p>That (the article quoted above) is the theory for external tool <strong>defined through config file</strong> (not through environment variable).<br>
In practice (still for config file definition of external tool), you can refer to:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/780425/how-do-i-setup-diffmerge-with-msysgit-gitk/783667#783667">How do I setup DiffMerge with msysgit / gitk?</a> which illustrates the concrete settings of DiffMerge and WinMerge for MsysGit and gitk</li>
<li><a href="https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/773973#773973">How can I set up an editor to work with Git on Windows?</a> for the definition of Notepad++ as an external editor.</li>
</ul>
|
<p>You may want to try out <a href="http://github.com/jiqingtang/xd" rel="nofollow noreferrer">xd</a>, which is a GUI wrapper for Git/SVN diff. It is <em>not</em> a diff tool itself.</p>
<p>You run <code>xd</code> when you want to run <code>git diff</code> or <code>svn diff</code> and it will show you a list of files, a preview window and you can launch any diff tool you like, including tkdiff, xxdiff, gvimdiff, Emacs (ediff), <a href="https://en.wikipedia.org/wiki/XEmacs" rel="nofollow noreferrer">XEmacs</a> (ediff), <a href="http://meldmerge.org/" rel="nofollow noreferrer">Meld</a>, <a href="http://diffuse.sourceforge.net/index.html" rel="nofollow noreferrer">Diffuse</a>, <a href="https://en.wikipedia.org/wiki/Kompare" rel="nofollow noreferrer">Kompare</a> and <a href="http://kdiff3.sourceforge.net/" rel="nofollow noreferrer">KDiff3</a>. You can also run any custom tool.</p>
<p>Unfortunately the tool doesn't support Windows.</p>
<p><strong>Disclosure</strong>: I am the author of this tool.</p>
| 31,843
|
<p>By default each row of a Gridview maps to each row in a datatable or dataset attached to its datasource. But what if I want to display these rows in multiple columns. For example if it has 10 rows, 5 rows each should be displayed in 2 columns side by side. Also can I do this with the Infragistics grid. Is this possible?</p>
|
<p>You can use a <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.aspx" rel="noreferrer"><code>DataList</code></a> control instead. It has a <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.repeatcolumns.aspx" rel="noreferrer"><code>RepeatColumns</code></a> property that you can define the number of columns you want to display.</p>
<p>In .NET Framework 3.5, there is an even better solution, the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview" rel="noreferrer"><code>ListView</code></a> control. You can find further information about how to use the ListView control <a href="http://msdn.microsoft.com/en-us/library/bb398790.aspx" rel="noreferrer">here</a>.</p>
|
<p>Can't you just put two identical bound columns one after the other?</p>
| 4,019
|
<p>I have a webservice @ <a href="http://recpushdata.cyndigo.com/Jobs.asmx" rel="nofollow noreferrer">http://recpushdata.cyndigo.com/Jobs.asmx</a> but I'm not able to access it though I am adding it as a WebReference properly.</p>
<p>Any Help would be great.</p>
|
<p>My guess is that this is a bug of some sorts. In SQL 2005 I was able to create such an indexed view without a problem (code is below). When I tried to run it on SQL 2000 though I got the same error as you are getting.</p>
<p>The following seems to work on SQL 2000, but I get a warning that the index will be ignored AND you would have to convert every time that you selected from the view.</p>
<pre><code>CONVERT(CHAR(8), datetime_column, 112)
</code></pre>
<p>Works in SQL 2005:</p>
<pre><code>CREATE TABLE dbo.Test_Determinism (
datetime_column DATETIME NOT NULL DEFAULT GETDATE())
GO
CREATE VIEW dbo.Test_Determinism_View
WITH SCHEMABINDING
AS
SELECT
DATEADD(dd, DATEDIFF(dd, 0, [datetime_column]), 0) AS EffectiveDate
FROM
dbo.Test_Determinism
GO
CREATE UNIQUE CLUSTERED INDEX IDX_Test_Determinism_View ON dbo.Test_Determinism_View (EffectiveDate)
GO
</code></pre>
|
<p>Look at <a href="https://stackoverflow.com/questions/309492/user-defined-functions-sql-server-2005-flagged-incorrectly-as-non-deterministic">that question asked and answered by Cade Roux</a>. Perhaps the solution would be to create a function using WITH SCHEMABINDING and then use it in the computed column</p>
<p><strong>EDIT</strong></p>
<p>I understand that you goal is to be able to have an index on that column. </p>
<p>If that cannot be done with a computed column then perhaps the only option would be to create an ordinary column and modify the data in that column each time you update the one it is based on. (say in trigger)</p>
| 39,877
|
<p>I have started using Linq to SQL in a (bit DDD like) system which looks (overly simplified) like this:</p>
<pre><code>public class SomeEntity // Imagine this is a fully mapped linq2sql class.
{
public Guid SomeEntityId { get; set; }
public AnotherEntity Relation { get; set; }
}
public class AnotherEntity // Imagine this is a fully mapped linq2sql class.
{
public Guid AnotherEntityId { get; set; }
}
public interface IRepository<TId, TEntity>
{
Entity Get(TId id);
}
public class SomeEntityRepository : IRepository<Guid, SomeEntity>
{
public SomeEntity Get(Guid id)
{
SomeEntity someEntity = null;
using (DataContext context = new DataContext())
{
someEntity = (
from e in context.SomeEntity
where e.SomeEntityId == id
select e).SingleOrDefault<SomeEntity>();
}
return someEntity;
}
}
</code></pre>
<p>Now, I got a problem. When I try to use SomeEntityRepository like this</p>
<pre><code>public static class Program
{
public static void Main(string[] args)
{
IRepository<Guid, SomeEntity> someEntityRepository = new SomeEntityRepository();
SomeEntity someEntity = someEntityRepository.Get(new Guid("98011F24-6A3D-4f42-8567-4BEF07117F59"));
Console.WriteLine(someEntity.SomeEntityId);
Console.WriteLine(someEntity.Relation.AnotherEntityId);
}
}
</code></pre>
<p>everything works nicely until the program gets to the last WriteLine, because it throws an <code>ObjectDisposedException</code>, because the DataContext does not exist any more.</p>
<p>I do see the actual problem, but how do I solve this? I guess there are several solutions, but none of those I have thought of to date would be good in my situation.</p>
<ul>
<li>Get away from the repository pattern and using a new DataContext for each atomic part of work.
<ul>
<li>I really would not want to do this. A reason is that I do not want to be the applications to be aware of the repository. Another one is that I do not think making linq2sql stuff COM visible would be good.</li>
<li>Also, I think that doing <code>context.SubmitChanges()</code> would probably commit much more than I intended to.</li>
</ul></li>
<li>Specifying DataLoadOptions to fetch related elements.
<ul>
<li>As I want my Business Logic Layer to just reply with some entities in some cases, I do not know which sub-properties they need to use.</li>
</ul></li>
<li>Disabling lazy loading/delayed loading for all properties.
<ul>
<li>Not an option, because there are quite a few tables and they are heavily linked. This could cause a lot of unnecessary traffic and database load.</li>
</ul></li>
<li>Some post on the internet said that using .Single() should help.
<ul>
<li>Apparently it does not ...</li>
</ul></li>
</ul>
<p>Is there any way to solve this misery?</p>
<p>BTW: We decided to use Linq t0 SQL because it is a relatively lightweight ORM solution and included with the .NET framework and Visual Studio. If the .NET Entity Framework would fit better in this pattern, it may be an option to switch to it. (We are not that far in the implementation, yet.)</p>
|
<p>Rick Strahl has a nice article about DataContext lifecycle management here: <a href="http://www.west-wind.com/weblog/posts/246222.aspx" rel="nofollow noreferrer">http://www.west-wind.com/weblog/posts/246222.aspx</a>.</p>
<p>Basically, the atomic action approach is nice in theory but you're going to need to keep your DataContext around to be able to track changes (and fetch children) in your data objects.</p>
<p>See also: <a href="https://stackoverflow.com/questions/226127/multiplesingle-instance-of-linq-to-sql-datacontext">Multiple/single instance of Linq to SQL DataContext</a> and <a href="https://stackoverflow.com/questions/196253/linq-to-sql-where-does-your-datacontext-live">LINQ to SQL - where does your DataContext live?</a>.</p>
|
<blockquote>
<p>Specifying DataLoadOptions to fetch related elements. As I want my Business Logic Layer to just reply with some entities in some cases, I do not know which sub-properties they need to use. </p>
</blockquote>
<p>If the caller is granted the coupling necessary to use the .Relation property, then the caller might as well specify the DataLoadOptions.</p>
<pre><code>DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.LoadWith<Entity>(e => e.Relation);
SomeEntity someEntity = someEntityRepository
.Get(new Guid("98011F24-6A3D-4f42-8567-4BEF07117F59"),
loadOptions);
</code></pre>
<p>//</p>
<pre><code>using (DataContext context = new DataContext())
{
context.LoadOptions = loadOptions;
</code></pre>
| 32,425
|
<p>How to add offline access functionality to <a href="http://moinmo.in" rel="noreferrer">MoinMoin wiki</a>?</p>
<p>As a minimum, I would love to have browsing access to all pages on a server-based wiki (while being offline). Search and other things, which do not modify the content, are secondary. An added bonus would be if this solution allowed to update wiki content while offline and push it back to the wiki when online.</p>
<p>Google Gears looks like a good candidate for trying to solve this, but other solutions are also welcome.</p>
<p>An interesting property of MoinMoin is that it keeps content in regular files instead of the database. This can make it easier to port wiki content from one location to another, but I don't know if that can play any role in answering this question.</p>
<p>Note: if you see a good reply please rate it up. i'd love to do that, but the site does not let me do ratings yet.</p>
|
<p><em>By using Gears with the Firefox Greasemonkey plugin, you can inject Gears code into any website that you want. Don't wait for your favorite website to enable offline support -- do it yourself.</em> <a href="http://code.google.com/apis/gears/articles/gearsmonkey.html" rel="nofollow noreferrer">http://code.google.com/apis/gears/articles/gearsmonkey.html</a></p>
|
<p>Have a look at <a href="http://moinmo.in/DesktopEdition" rel="nofollow noreferrer">MoinMoin Desktop Edition</a>.</p>
| 21,313
|
<p>If possible I want to catch pressure sensitive input from a Wacom tablet in Python. Are there any Python libraries available that can do this?</p>
|
<p>You could perhaps take a look at the <a href="http://www.alexmac.cc/tablet-apps/tablet-apps-0.3.1.tar.bz2" rel="nofollow noreferrer">software</a> described <a href="http://www.alexmac.cc/tablet-apps/" rel="nofollow noreferrer">here</a>. It is a gnome applet, written in Python.</p>
<p>From the web site:</p>
<p>"The gnome wacom applet is a small gnome panel applet that shows how much pressure is being applied to your wacom tablet by the current device. Clicking on the panel icon brings up a dialog allowing you to select a different device and check what pressure and tilt information is being recieved from it. This dialog also contains a small drawing test area to give your pen a quick test."</p>
<p><a href="http://www.google.com/search?q=wacom+tablet+python" rel="nofollow noreferrer">Google is your friend</a></p>
|
<p>Pressure data is available in <a href="http://python-gtk-3-tutorial.readthedocs.org/en/latest/" rel="nofollow">PyGObject to access Gtk+ 3</a> on multiple platforms, though "Windows users may still want to keep using PyGTK until more convenient installers are published." [<a href="https://wiki.python.org/moin/PyGtk" rel="nofollow">citation</a>] Motion event objects generated by pressure sensitive devices will carry pressure data.</p>
| 6,739
|
<p>The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object instance. Although I know how to code the singleton pattern in C++ and Java, I was wondering if anyone know how to implement it in Ruby?</p>
|
<p>Actually, the above answer was not completely correct.</p>
<pre><code>require 'singleton'
class Example
include Singleton
end
</code></pre>
<p>You also need to include the require 'singleton' statement.</p>
|
<p>You could use modules to the same effect I believe, although its not "the singleton pattern" you can have global state that way (which is what a singleton is ! Naughty global state !).</p>
| 2,670
|
<p>How do I revert a modified file to its previous revision at a specific commit hash (which I determined via <a href="https://git-scm.com/docs/git-log" rel="noreferrer"><code>git log</code></a> and <a href="https://git-scm.com/docs/git-diff" rel="noreferrer"><code>git diff</code></a>)?</p>
|
<p>Assuming the hash of the commit you want is <code>c5f567</code>:</p>
<pre><code>git checkout c5f567 -- file1/to/restore file2/to/restore
</code></pre>
<p>The <a href="https://git-scm.com/docs/git-checkout" rel="noreferrer">git checkout</a> man page gives more information.</p>
<p>If you want to revert to the commit before <code>c5f567</code>, append <code>~1</code> (where 1 is the number of commits you want to go back, it can be anything):</p>
<pre><code>git checkout c5f567~1 -- file1/to/restore file2/to/restore
</code></pre>
<p>As a side note, I've always been uncomfortable with this command because it's used for both ordinary things (changing between branches) and unusual, destructive things (discarding changes in the working directory).</p>
<hr />
<p>There is also a new <a href="https://git-scm.com/docs/git-restore" rel="noreferrer"><code>git restore</code></a> command that is specifically designed for restoring working copy files that have been modified. If your git is new enough you can use this command, but the documentation comes with a warning:</p>
<blockquote>
<p>THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.</p>
</blockquote>
|
<ul>
<li><strong>Run the following command that does a soft reset and the changes comes to your local.</strong></li>
</ul>
<pre><code>git reset --soft HEAD^1
</code></pre>
<ul>
<li><strong>See the status of files that you previously committed that comes to
your local and then make the change.</strong></li>
</ul>
<pre><code> git status
</code></pre>
<ul>
<li><p><strong>Commit and push the file after making the changes</strong>.</p>
</li>
<li><p><strong>Previous commit history for the wrong committed files will not be
shown</strong></p>
</li>
</ul>
<p>Before pulling from origin always have pruning (Optional Step)</p>
<pre class="lang-cs prettyprint-override"><code> git remote prune origin
</code></pre>
| 26,513
|
<p>Comparing string in C# is pretty simple. In fact there are several ways to do it. I have listed some in the block below. What I am curious about are the differences between them and when one should be used over the others? Should one be avoided at all costs? Are there more I haven't listed? </p>
<pre><code>string testString = "Test";
string anotherString = "Another";
if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}
</code></pre>
<p>(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)</p>
|
<p>Here are the rules for how these functions work:</p>
<p><strong><code>stringValue.CompareTo(otherStringValue)</code></strong></p>
<ol>
<li><code>null</code> comes before a string</li>
<li>it uses <code>CultureInfo.CurrentCulture.CompareInfo.Compare</code>, which means it will use a culture-dependent comparison. This might mean that <code>ß</code> will compare equal to <code>SS</code> in Germany, or similar</li>
</ol>
<p><strong><code>stringValue.Equals(otherStringValue)</code></strong></p>
<ol>
<li><code>null</code> is not considered equal to anything</li>
<li>unless you specify a <code>StringComparison</code> option, it will use what looks like a direct ordinal equality check, i.e. <code>ß</code> is not the same as <code>SS</code>, in any language or culture</li>
</ol>
<p><strong><code>stringValue == otherStringValue</code></strong></p>
<ol>
<li>Is not the same as <code>stringValue.Equals()</code>.</li>
<li>The <code>==</code> operator calls the static <code>Equals(string a, string b)</code> method (which in turn goes to an internal <code>EqualsHelper</code> to do the comparison.</li>
<li>Calling <code>.Equals()</code> on a <code>null</code> string gets <code>null</code> reference exception, while on <code>==</code> does not.</li>
</ol>
<p><strong><code>Object.ReferenceEquals(stringValue, otherStringValue)</code></strong></p>
<p>Just checks that references are the same, i.e. it isn't just two strings with the same contents, you're comparing a string object with itself.</p>
<hr>
<p>Note that with the options above that use method calls, there are overloads with more options to specify how to compare.</p>
<p>My advice if you just want to check for equality is to make up your mind whether you want to use a culture-dependent comparison or not, and then use <code>.CompareTo</code> or <code>.Equals</code>, depending on the choice.</p>
|
<p>Using .Equals is also a lot easier to <em>read</em>.</p>
| 6,603
|
<p>You get a compilation error if you define the string parameter to have a size greater than 8000</p>
<p>e.g. </p>
<pre><code>The size (9000) given to the type 'varchar' exceeds the maximum allowed for any data type (8000).
</code></pre>
<p>Any ideas?</p>
|
<p>you need to store it as TEXT instead of varchar for string larger than 8000 in sql 2000</p>
|
<p>You can't use text as a parameter value for a stored proc in SQL 2000, so usually the technique is to break up the information into chunks of 8000 characters or less and reassemble in the proc.</p>
| 36,113
|
<p>What is the best way to password protect folder using php without a database or user name but using. Basically I have a page that will list contacts for organization and need to password protect that folder without having account for every user . Just one password that gets changes every so often and distributed to the group. I understand that it is not very secure but never the less I would like to know how to do this. In the best way.</p>
<p>It would be nice if the password is remembered for a while once user entered it correctly.</p>
<hr>
<p>I am doing approximately what David Heggie suggested, except without cookies. It does seem insecure as hell, but it is probably better having a bad password protection then none at all. </p>
<p>This is for internal site where people would have hell of a time remembering their login and password and would never go through <em>sign up</em> process... unless it is really easy they would not use the system at all. </p>
<p>I wanted to see other solutions to this problem. </p>
<p>With user base consisting of not very tech savvy people what are other ways to do this. </p>
|
<p><strong>Edit: SHA1 is no longer considered secure. Stored password hashes should also be <a href="https://en.wikipedia.org/wiki/Salt_(cryptography)" rel="nofollow noreferrer">salted</a>. There are now much better solutions to this problem.</strong></p>
<hr />
<p>You could use something like this:</p>
<pre><code>//access.php
<?php
//put sha1() encrypted password here - example is 'hello'
$password = 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d';
session_start();
if (!isset($_SESSION['loggedIn'])) {
$_SESSION['loggedIn'] = false;
}
if (isset($_POST['password'])) {
if (sha1($_POST['password']) == $password) {
$_SESSION['loggedIn'] = true;
} else {
die ('Incorrect password');
}
}
if (!$_SESSION['loggedIn']): ?>
<html><head><title>Login</title></head>
<body>
<p>You need to login</p>
<form method="post">
Password: <input type="password" name="password"> <br />
<input type="submit" name="submit" value="Login">
</form>
</body>
</html>
<?php
exit();
endif;
?>
</code></pre>
<p>Then on each file you want to protect, put at the top:</p>
<pre><code><?php
require('access.php');
?>
secret text
</code></pre>
<p>It isn't a very nice solution, but it might do what you want</p>
<p><strong>Edit</strong></p>
<p>You could add a logout.php page like:</p>
<pre><code><?php
session_start();
$_SESSION['loggedIn'] = false;
?>
You have logged out
</code></pre>
|
<p>Well since you <em>know</em> it's insecure to begin with, you could store a password in a text file somewhere on your web server. When someone accesses the page you could show a form that asks for a password. If the password matches what is in the text file, then you reload the page and display the information. Using the text file will allow you to change the password without having to modify the page they are accessing when you want to change it. You're still going to be sending plaintext everywhere unless you're using SSL. Let me know if you need some code.</p>
| 36,492
|
<p>What are the tensions between multithreading and exception-safety in C++? Are there good guidelines to follow? Does a thread terminate because of an uncaught exception?</p>
|
<p>I believe the C++ standard does not make any mention of multithreading - multithreading is a platform-specific feature.</p>
<p>I'm not exactly sure what the C++ standard says about uncaught exceptions in general, but according to <a href="http://www.devx.com/tips/Tip/14240" rel="noreferrer">this page</a>, what happens is platform-defined, and you should find out in your compiler's documentation.</p>
<p>In a quick-and-dirty test I did with g++ 4.0.1 (i686-apple-darwin8-g++-4.0.1 to be specific), the result is that <code>terminate()</code> is called, which kills the entire program. The code I used follows:</p>
<pre><code>#include <stdio.h>
#include <pthread.h>
void *threadproc(void *x)
{
throw 0;
return NULL;
}
int main(int argc, char **argv)
{
pthread_t t;
pthread_create(&t, NULL, threadproc, NULL);
void *ret;
pthread_join(t, &ret);
printf("ret = 0x%08x\n", ret);
return 0;
}
</code></pre>
<p>Compiled with <code>g++ threadtest.cc -lpthread -o threadtest</code>. Output was:</p>
<pre><code>terminate called after throwing an instance of 'int'
</code></pre>
|
<p>I don't recommend letting any exception remain uncaught. Wrap your top-level thread functions in catch-all handlers that can more gracefully (or at least verbosely) shut down the program.</p>
| 42,642
|
<p>I'm developing an application for Windows Mobile Devices using Visual Studio .NET 2008 whose UI requires the use of a ComboBox control. Unfortunately, for devices with neither a hardware fullsize keyboard nor a touchscreen interface, there is no way to move (tab) from the ComboBox control to another control on the same form (say, specifying a product in the ComboBox and then moving to a text field to add a quantity).</p>
<p>I've tried creating an event handler for the ComboBox's KeyPress event and setting the focus to the next control manually whenever the user presses the Right or Left directional key but unfortunately the event handler does not capture those key presses.</p>
<p>Any ideas? I have a strong suspicion that this is being over-engineered and that there exists a better control more suited to what I need to do; I find it a bit inconceivable that tabbing out of a Combo Box control could be that difficult.</p>
<p>Thanks!</p>
<p>EDIT: Apparently I can capture the KeyDown and KeyUp events on the ComboBox, which allows me to set the focus or tab to the next control. Still over-engineered - still looking for ideas!</p>
|
<p>I believe directionals are only captured on <code>KeyDown</code> and <code>KeyUp</code>, not on <code>KeyPress</code>.</p>
<p>Alternatively to using a ComboBox, you could use several RadioButtons if the numer of ListItems is static and relatively small.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/bb985500.aspx#GeneralRules" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb985500.aspx#GeneralRules</a> provides UI navigation rules. </p>
| 7,534
|
<p>Is it better to initialize class member variables on declaration</p>
<pre><code>private List<Thing> _things = new List<Thing>();
private int _arb = 99;
</code></pre>
<p>or in the default constructor?</p>
<pre><code>private List<Thing> _things;
private int _arb;
public TheClass()
{
_things = new List<Thing>();
_arb = 99;
}
</code></pre>
<p>Is it simply a matter of style or are there performance trade-offs, one way or the other?</p>
|
<p>In terms of performance, there is no real difference; field initializers are implemented as constructor logic. The only difference is that field initializers happen before any "base"/"this" constructor.</p>
<p>The constructor approach can be used with auto-implemented properties (field initializers cannot) - i.e.</p>
<pre><code>[DefaultValue("")]
public string Foo {get;set;}
public Bar() { // ctor
Foo = "";
}
</code></pre>
<p>Other than that, I tend to prefer the field initializer syntax; I find it keeps things localized - i.e.</p>
<pre><code>private readonly List<SomeClass> items = new List<SomeClass>();
public List<SomeClass> Items {get {return items;}}
</code></pre>
<p>I don't have to go hunting up and down to find where it is assigned...</p>
<p>The obvious exception is where you need to perform complex logic or deal with constructor parameters - in which case constructor-based initialization is the way to go. Likewise, if you have multiple constructors, it would be preferable for the fields to always get set the same way - so you might have ctors like:</p>
<pre><code>public Bar() : this("") {}
public Bar(string foo) {Foo = foo;}
</code></pre>
<p>edit: as a side comment, note that in the above, if there are other fields (not shown) with field initializers, then they are only directly initialized in the constructors that call <code>base(...)</code> - i.e. the <code>public Bar(string foo)</code> ctor. The other constructor does <em>not</em> run field initializers, since it knows they are done by the <code>this(...)</code> ctor.</p>
|
<p>On added point to the above - You always have a constructor when implementing classes that have an implementation. If you do not declare one then the default instructor is inferred by the compiler [public Foo(){}]; a constructor that takes no arguments.</p>
<p>Often times I like to offer both approaches. Allow constructors for those that wish to use them and allow the Field Initializers for situations where you wish to use a simplified or default implementation of your class / type. This adds flexibility to your code. Keep in mind that anyone can use the default field initializer if they choose ... be sure to declare it manually if you offer more than one constructor - public Foo(){}</p>
| 38,159
|
<p>The rich text editor must be implemented in Java, provide Swing support, and preferably be open source.</p>
<p>I'm looking to integrate it into an existing Java/Swing application. </p>
<p>Thanks.</p>
|
<p>This is probably not as drop-in-place as what you were after... but JTextPane supports rich text and HTML.
Its trivial to get it to <em>display</em> rtf or html, just set the encoding type before you fill it with content. </p>
<p>As for making the little "B" and "<em>I</em>" etc style-modifying buttons, well if it came down to it, in a pinch that wouldnt be very hard to make yourself.
Think JButtons with Icons set. Their listeners get JTextPane's current selection start and end index positions like this :
<code>jpane.getSelectionStart()</code> or <code>jpane.getSelectionEnd()</code>
and then insert opening and closing html/rtf tags at those locations. </p>
<p>Undo is easy too - maintain a simple stack of the string contents of the Jpanel, every time the user does an edit action, a simple <code>history.push(jpane.getText())</code> would store the state, and the undo button would be as simple as <code>jpane.setText(history.pop())</code>.</p>
<p>I/you could make one with B, <em>I</em> & undo in around 30 min I reckon - other buttons like lists will take longer, but not much so.</p>
|
<p>Have a look at <a href="http://www.pilotltd.com/index_en.jsp?pagenum=90004" rel="nofollow noreferrer">JWord</a> or <a href="https://github.com/hoesterholt/JRichTextEditor" rel="nofollow noreferrer">JRichTextEditor</a></p>
<p>JWord is a commercial swing rich text editor, with tables, paging and RTF/opendoc/XML support.
Also supports header/footer, multi-column layout, export HTML, SVG, WMF etc.</p>
<p>JRichTextEditor is an open source swing widget, that's quite ok for note taking. Supports images, a simple XML format for storage, export to PDF, HTML. Not as advanced as JWord, but open source. </p>
<p>Might help.</p>
| 23,943
|
<p>Is there a tool that creates a diff of a file structure, perhaps based on an MD5 manifest. My goal is to send a package across the wire that contains new/updated files and a list of files to remove. It needs to copy over new/updated files and remove files that have been deleted on the source file structure?</p>
|
<p>You might try rsync. Depending on your needs, the command might be as simple as this: </p>
<pre><code>rsync -az --del /path/to/master dup-site:/path/to/duplicate
</code></pre>
<p>Quoting from <a href="http://samba.anu.edu.au/rsync/" rel="nofollow noreferrer">rsync's web site</a>:</p>
<blockquote>
<p>rsync is an open source utility that
provides fast incremental file
transfer. rsync is freely available
under the GNU General Public License
and is currently being maintained by
Wayne Davison.</p>
</blockquote>
<p>Or, if you prefer <a href="http://en.wikipedia.org/wiki/Rsync" rel="nofollow noreferrer">wikipedia</a>:</p>
<blockquote>
<p>rsync is a software application for
Unix systems which synchronizes files
and directories from one location to
another while minimizing data transfer
using delta encoding when appropriate.
An important feature of rsync not
found in most similar
programs/protocols is that the
mirroring takes place with only one
transmission in each direction. rsync
can copy or display directory contents
and copy files, optionally using
compression and recursion.</p>
</blockquote>
|
<p>You might try rsync. Depending on your needs, the command might be as simple as this: </p>
<pre><code>rsync -az --del /path/to/master dup-site:/path/to/duplicate
</code></pre>
<p>Quoting from <a href="http://samba.anu.edu.au/rsync/" rel="nofollow noreferrer">rsync's web site</a>:</p>
<blockquote>
<p>rsync is an open source utility that
provides fast incremental file
transfer. rsync is freely available
under the GNU General Public License
and is currently being maintained by
Wayne Davison.</p>
</blockquote>
<p>Or, if you prefer <a href="http://en.wikipedia.org/wiki/Rsync" rel="nofollow noreferrer">wikipedia</a>:</p>
<blockquote>
<p>rsync is a software application for
Unix systems which synchronizes files
and directories from one location to
another while minimizing data transfer
using delta encoding when appropriate.
An important feature of rsync not
found in most similar
programs/protocols is that the
mirroring takes place with only one
transmission in each direction. rsync
can copy or display directory contents
and copy files, optionally using
compression and recursion.</p>
</blockquote>
| 22,738
|
<p><a href="http://www.5axismaker.com/5axis/" rel="nofollow noreferrer">5AxisMaker</a> has a 5 axis CNC/3D printer combo machine. I understand what the benefits of 5 axis are for CNC machines, but are there any benefits for 3D printing. In this <a href="https://youtu.be/w8Fl8L4yk8M" rel="nofollow noreferrer">video</a> they show the printer printing on an angle, but this could have been done with just linear layers.</p>
<p>Would there be any cases where a 5 axis printer would preform better than a 3 axis printer?</p>
|
<p>One aspect of having this level of control with 3d printing of a model is the removal of the need for supports and the attendant post-processing. In the case of the model shown in the video, some effects are created by printing the continents in a conformal manner that would otherwise be impossible with conventional 3d printing. Cosmetically, the results of the "5d" printer are superior in this example.</p>
<p>There would also be some structural benefit for models with high organic content, that is curves and bulges, as opposed to orthogonal designs. Even with orthogonal designs, one can achieve stronger parts with cross-layered plastic in all directions, rather than being limited by x and y filament layers.</p>
<p>I see on the web site that one can exchange tool heads as well. One could print a 3d model, layering the filament on all the surfaces, then use a tool head change to a milling bit and smooth the surface under CAD control. Alternatively, one could use foam or wood and mill a model shape to be covered with a 3d printed material.</p>
<p>Considering the relative novelty of this product, it's likely that many aspects of the creative utility have yet to be discovered!</p>
|
<p>Slicing prints for printing in 5 Axis is not going to be simple with the current software. If you look at the web site for the 5AxisMaker you can see they are using Algorithmic modeling software (Grasshopper). You would probably need to buy this as well and then spend a decent amount of time learning how to use this software as well if you were going to try and take advantage of the 5th Axis for 3D printing. </p>
<p>I have only seen Grasshopper used for 3D printing and 5 Axis used in research papers. </p>
| 428
|
<p>Given an empty method body, will the JIT optimize out the call (I know the C# compiler won't). How would I go about finding out? What tools should I be using and where should I be looking?</p>
<p>Since I'm sure it'll be asked, the reason for the empty method is a preprocessor directive.</p>
<hr>
<p>@Chris:
Makes sense, but it could optimize out calls to the method. So the method would still exist, but static calls to it could be removed (or at least inlined...)</p>
<p>@Jon:
That just tells me the language compiler doesn't do anything. I think what I need to do is run my dll through ngen and look at the assembly.</p>
|
<p>This chap has quite a good treatment of JIT optimisations, do a search on the page for 'method is empty', it's about half way down the article -</p>
<p><a href="http://www.codeproject.com/KB/dotnet/JITOptimizations.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/JITOptimizations.aspx</a></p>
<p>Apparently empty methods do get optimised out through inlining what is effectively no code.</p>
<p>@Chris: I do realise the that the methods will still be part of the binary and that these are JIT optimisations :-). On a semi-related note, Scott Hanselman had quite an interesting article on inlining in Release build call stacks:</p>
<p><a href="http://www.hanselman.com/blog/ReleaseISNOTDebug64bitOptimizationsAndCMethodInliningInReleaseBuildCallStacks.aspx" rel="noreferrer">http://www.hanselman.com/blog/ReleaseISNOTDebug64bitOptimizationsAndCMethodInliningInReleaseBuildCallStacks.aspx</a></p>
|
<p>All things being equal, yes it should be optimized out. The JIT inlines functions where appropriate and there are few things more appropriate than empty functions :)</p>
<p>If you really want to be sure then change your empty method to throw an exception and print out the stack trace it contains.</p>
| 3,289
|
<p>This will require a little setup. Trust me that this is for a good cause.</p>
<h2>The Background</h2>
<p>A friend of mine has run a non-profit public interest website for two years. The site is designed to counteract misinformation about a certain public person. Of course, over the last two years those of us who support what he is doing have relentlessly linked to the site in order to boost it in Google so that it appears very highly when you search for this public person's name. (In fact it is the #2 result, right below the public person's own site). He does <em>not</em> have the support of this public person, but what he is doing is in the public interest and good.</p>
<p>The friend had a stroke recently. Coincidentally, the domain name came up for renewal right when he was in the hospital and his wife missed the email about it. A domain squatter snapped up the domain, and put up content diametrically opposed to his intent. This squatter is now benefitting from his Google placement and page rank. </p>
<p>Fortunately there were other domains he owned which were aliased to point to this domain, i.e. they used a DNS mapping or HTTP 301 redirect (I'm not sure which) to send people to the right site. We reconfigured one of the alias domains to point directly to the original content. </p>
<p>We have publicized this new name for the site and the community has now created thousands of links to the new domain, and is fixing all the old links. We can see from the cache that Google has in fact crawled the original site at the new address, and has re-crawled the imposter site.</p>
<h2>The Problem</h2>
<p>Even though Google has crawled both sites, you can't get the site to appear in relevant searches under the new URL!</p>
<p>It appears to me that Google remembers the old redirect between the two names (probably because someone linked to the new domain back when it was an alias). It is treating the two sites as if they are the same site in all results. The results for the site name, and using the "link:" operator to find sites that link to this site, are entirely consistent with Google being convinced they are the same site.</p>
<p>Keep in mind that we do <em>not</em> have control of the content of the <em>old</em> domain, and we do <em>not</em> have the cooperation of the person that these sites relate to.</p>
<p><strong>How can we convince the Googlebot that domain "a" and domain "b" are now two different sites and should be treated as such in results?</strong></p>
<p>EDIT: Forward was probably DNS, not HTTP based.</p>
|
<p>Google will detect the decrease in links to the old domain and that will hurt it.</p>
<p>Include some new interesting content on the new domain. This will encourage Google to crawl this domain.</p>
<p>The 301 redirects will be forgotten, in time. Perhaps several months. Note that they redirected one set of URLs to another set, not from one domain to another. Get some links to some <em>new</em> pages within the site, not just the homepage, as these URLs will not be in the old redirected set.</p>
<p>Set up Google Webmaster Tools and submit an XML sitemap. Thoroughly check everything in Webmaster Tools about once per week.</p>
<p>Good luck.</p>
|
<p>Time heals all wounds...</p>
<p>Losing control of the domain is a big blow, and it will take time to recover. It sounds like you're following all the correct procedures (getting people to change links, using 301s, etc.)</p>
<p>Has the content of the original site changed since being put up again? If not, you should probably make some changes. If Google re-crawls the page and finds it substantially identical to the one previously indexed, it might consider it a copy and that's why it's using the original URL.</p>
<p>Also, I believe that Google has a resolution process for just such situations. I'm not sure what the form to fill out is or who to contact, but surely some other SO citizens could help.</p>
<p>Good luck!</p>
| 32,795
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.