instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
---|---|---|---|
<p>What are the ways to retrieve data submitted to the web server from a form in the client HTML in ASP.NET?</p>
| <p>You can also search through both the Form and QueryString collections at the same time so that the data will be found regardless of the the request method.</p>
<pre><code>value = Request("formElementID")
</code></pre>
| <p>In VB.NET</p>
<p>For POST requests:</p>
<pre><code>value = Request.Form("formElementID")
</code></pre>
<p>For GET requests:</p>
<pre><code>value = Request.QueryString("formElementID")
</code></pre>
| 5,064 |
<p>I teach the third required intro course in a CS department. One of my homework assignments asks students to speed up code they have written for a previous assignment. Factor-of-ten speedups are routine; factors of 100 or 1000 are not unheard of. (For a factor of 1000 speedup you have to have made rookie mistakes with malloc().)</p>
<p>Programs are improved by a sequence is small changes. I ask students to record and describe each change and the resulting improvement.</p>
<p>While you're improving a program it is also possible to break it. Wouldn't it be nice to back out?</p>
<p>You can see where I'm going with this: my students would benefit enormously from version control. But there are some caveats:</p>
<ul>
<li>Our computing environment is locked down. Anything that depends on a central repository is suspect.</li>
<li>Our students are incredibly overloaded. Not just classes but jobs, sports, music, you name it. For them to use a new tool it has to be incredibly easy and have obvious benefits.</li>
<li>Our students do most work in pairs. Getting bits back and forth between accounts is problematic. Could this problem also be solved by distributed version control?</li>
<li>Complexity is the enemy. I know setting up a CVS repository is too baffling---I myself still have trouble because I only do it once a year. I'm told SVN is even harder.</li>
</ul>
<p>Here are my comments on existing systems:</p>
<ul>
<li>I think central version control (CVS or SVN) is ruled out because our students don't have the administrative privileges needed to make a repository that they can share with one other student. (We are stuck with Unix file permissions.) Also, setup on CVS or SVN is too hard.</li>
<li>darcs is way easy to set up, but it's not obvious how you share things. darcs send (to send patches by email) seems promising but it's not clear how to set it up.</li>
<li>The introductory documentation for git is not for beginners. Like CVS setup, it's something I myself have trouble with.</li>
</ul>
<p>I'm soliciting suggestions for what source-control to use with beginning students. I suspect we can find resources to put a thin veneer over an existing system and to simplify existing documentation. We probably don't have resources to write new documentation. </p>
<p>So, what's really easy to <strong>setup</strong>, <strong>commit</strong>, <strong>revert</strong>, and <strong>share changes with a partner</strong> but does not have to be easy to merge or to work at scale? </p>
<p>A key constraint is that <strong>programming pairs have to be able to share work with each other and only each other</strong>, and <strong>pairs change every week</strong>. Our infrastructure is Linux, Solaris, and Windows with a netapp filer. I doubt my IT staff wants to create a Unix group for each pair of students. Is there an easier solution I've overlooked?</p>
<p>(Thanks for the accepted answer, which beats the others on account of its excellent reference to <a href="http://www-cs-students.stanford.edu/~blynn/gitmagic/" rel="noreferrer">Git Magic</a> as well as the helpful comments.)</p>
| <p>I would say something like Git might fit the bill:</p>
<ul>
<li>As it's a distributed system, you don't need to have a central repository, the repos exist with the source directory</li>
<li>It is easy to create patch files that can be mailed and applied.</li>
<li>Although it might seem that git is difficult to use, the basic ideas of committing, merging, adding and removing files are not that hard to learn.</li>
</ul>
<p>Have a look at this site <a href="http://www-cs-students.stanford.edu/~blynn/gitmagic/ch01.html" rel="noreferrer">Git Magic</a>
or, even this tip site <a href="http://gitready.com/" rel="noreferrer">GitReady</a></p>
| <p>I would say your best bet will be to try to work with your IT department to set up a system/method for your students to easily create new SVN/CVS repositories.</p>
<p>Probably you could get the IT department to give you the privileges necessary to create repositories for your students even if they won't give the priveleges to the students themselves. You could probably pretty easily write a few scripts to mass-create repositories from lists of students at the beginning of the semester.</p>
| 42,299 |
<p>Do you know what's the format of the DepartureWindow parameter for sabre web-services' OTA_AirLowFareSearch call? Whatever I pass, it shows me an error.</p>
<p>This is the entire documentation for those parameters (I kid you not):</p>
<pre><code><!--"DepartureDateTime" represents the date and time of departure.-->
<DepartureDateTime>2004-11-22T15:00:00</DepartureDateTime>
<!--"DepartureWindow" represents a window of time to search prior and post departure.-->
<!--Example: JR.DFW/S-OYLAS22NOV1500‡ZRD09001700-->
<DepartureWindow>09001700</DepartureWindow>
</code></pre>
<p>I've already tryied passing the number of seconds since DepartureDateTime and a unix timestamp without success. The error message it's:</p>
<pre><code>Error response received. The error was: INVALID TIME WINDOW IN Z FIELDS
</code></pre>
<p>Thanks</p>
| <p>You must specify time within window in DepartureDateTime</p>
<pre><code> <ns1:DepartureDateTime>2009-01-03T15:00:00</ns1:DepartureDateTime>
<ns1:DepartureWindow>11001559</ns1:DepartureWindow>
</code></pre>
<p>works fine for me</p>
| <p>also, you can use OriginDestinationInformation.TPA_Extensions.AlternateTime instead</p>
| 37,080 |
<p>When I launch perfmon and try to add a counter, the displayed performance objects are all numbers. How can I reset these Performance objects?</p>
| <p>I found a way to solve the problem:</p>
<ul>
<li>copy C:\WINDOWS\system32\PerfStringBackup.INI from a PC where perfmon works correctly</li>
<li>cd C:\WINDOWS\system32</li>
<li>lodctr /R:PerfStringBackup.INI</li>
</ul>
| <p>What do you mean my "reset"? What's the behavior you're expecting? </p>
<p>The perfmon "System Monitor" view shows the (near) real time value of the counter. Since these measurements are always being taken there will (almost) always be a number there.</p>
<p>If you want to be able to control the collection of these measurements, you need to create a Counter Log. Additionally, you can use the logman command to manage the log from the command line or a script.</p>
| 30,040 |
<p>I'm writing a query to summarize some data. I have a flag in the table that is basically boolean, so I need some sums and counts based on one value of it, and then the same thing for the other value, like so:</p>
<pre><code>select
location
,count(*)
,sum(duration)
from my.table
where type = 'X'
and location = @location
and date(some_tstamp) = @date
group by location
</code></pre>
<p>And then the same for another value of the type column. If I join this table twice, how do I still group so I can only get aggregation for each table, i.e. count(a.<code>*</code>) instead of count(*)...</p>
<p>Would it be better to write two separate queries?</p>
<p><strong>EDIT</strong></p>
<p>Thanks everybody, but that's not what I meant. I need to get a summary where type = 'X' and a summary where type = 'Y' separately...let me post a better example. What I meant was a query like this:</p>
<pre><code>select
a.location
,count(a.*)
,sum(a.duration)
,count(b.*)
,sum(b.duration)
from my.table a, my.table b
where a.type = 'X'
and a.location = @location
and date(a.some_tstamp) = @date
and b.location = @location
and date(b.some_tstamp) = @date
and b.type = 'Y'
group by a.location
</code></pre>
<p>What do I need to group by? Also, DB2 doesn't like count(a.<code>*</code>), it's a syntax error.</p>
| <pre>
<code>
select
location
,Sum(case when type = 'X' then 1 else 0 end) as xCount
,Sum(case when type = 'Y' then 1 else 0 end) as YCount
,Sum(case when type = 'X' then duration else 0 end) as xCountDuration
,Sum(case when type = 'Y' then duration else 0 end) as YCountDuration
from my.table
where
location = @location
and date(some_tstamp) = @date
group by location
</code>
</pre>
<p>This should work in SQL Server. I guess db2 should have something similar.</p>
<p>Edit: Add a where condition to limit the records to select type = X or type = Y, if "type" can have value other than X and Y. </p>
| <p>To make the counts work, instead of count(a.*) just do count(a.location), or any other not-null column (the PK would be ideal).</p>
<p>As to the main question, either of the answers given by shahkalpesh or George Eadon above would work. There is no reason in this example to join the table twice.</p>
| 28,146 |
<p>Almost every Java book I read talks about using the interface as a way to share state and behaviour between objects that when first "constructed" did not seem to share a relationship. </p>
<p>However, whenever I see architects design an application, the first thing they do is start programming to an interface. How come? How do you know all the relationships between objects that will occur within that interface? If you already know those relationships, then why not just extend an abstract class?</p>
| <p>Programming to an interface means respecting the "contract" created by using that interface. And so if your <code>IPoweredByMotor</code> interface has a <code>start()</code> method, future classes that implement the interface, be they <code>MotorizedWheelChair</code>, <code>Automobile</code>, or <code>SmoothieMaker</code>, in implementing the methods of that interface, add flexibility to your system, because one piece of code can start the motor of many different types of things, because all that one piece of code needs to know is that they respond to <code>start()</code>. It doesn't matter <em>how</em> they start, just that they <em>must start</em>.</p>
| <p>In one sense, I think your question boils down to simply, "why use interfaces and not abstract classes?" Technically, you can achieve loose coupling with both -- the underlying implementation is still not exposed to the calling code, and you can use Abstract Factory pattern to return an underlying implementation (interface implementation vs. abstract class extension) to increase the flexibility of your design. In fact, you could argue that abstract classes give you slightly more, since they allow you to both require implementations to satisfy your code ("you MUST implement start()") and provide default implementations ("I have a standard paint() you can override if you want to") -- with interfaces, implementations must be provided, which over time can lead to brittle inheritance problems through interface changes.</p>
<p>Fundamentally, though, I use interfaces mainly due to Java's single inheritance restriction. If my implementation MUST inherit from an abstract class to be used by calling code, that means I lose the flexibility to inherit from something else even though that may make more sense (e.g. for code reuse or object hierarchy).</p>
| 7,108 |
<p>Ok, so there has to be a way to do this... no? If not I'd love some ideas. </p>
<p>I have two repeaters and an image inside an update panel along with some AJAX dropdowns with link buttons to the left. I want to update the data inside the update panel as fast as possible as values are selected from the dropdowns. </p>
<p>What do you think would be the best way to update the data? The repeaters are populated by objects, so if I could just filter the objects by some properties I could end up with the correct data. No new data from the server is needed. </p>
<p>Anyone have some ideas?</p>
| <p>As far as I know, it is not easy to get just Data and data-bind the repeater on the client side. But, you might want to <a href="http://dotnetslackers.com/articles/ajax/ASPNETRepeater.aspx" rel="nofollow noreferrer">check this out</a>.</p>
| <p>Wrap only the repeater you want to rebind with an update panel of its own. The only viewstate transferred when doing this is the portion inside the update panel. You may have to play around with the triggers and update mode of the panels to get everything to play nicely. </p>
<p>Another option is instead of using repeaters, serialize your objects into XML and then write a page method that returns an html string of your transformed data using xsl. Then client side call your path method and update the DOM as appropriate. </p>
<p>A third option is to use use a service reference/page method to return JSON objects and update the DOM manually.</p>
<p><a href="http://www.asp.net/AJAX/Documentation/Live/tutorials/ASPNETAJAXWebServicesTutorials.aspx" rel="nofollow noreferrer">http://www.asp.net/AJAX/Documentation/Live/tutorials/ASPNETAJAXWebServicesTutorials.aspx</a></p>
<p>Good luck! I have done all 3,</p>
| 8,715 |
<p>How do I format a string to <a href="http://www.grammar-monster.com/lessons/capital_letters_title_case.htm" rel="noreferrer">title case</a>?</p>
| <p>Here is a simple static method to do this in C#:</p>
<pre><code>public static string ToTitleCaseInvariant(string targetString)
{
return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(targetString);
}
</code></pre>
| <p>Without using a ready-made function, a super-simple low-level algorithm to convert a string to title case:</p>
<p><pre><code>
convert first character to uppercase.
for each character in string,
if the previous character is whitespace,
convert character to uppercase.
</pre></code></p>
<p>This asssumes the "convert character to uppercase" will do that correctly regardless of whether or not the character is case-sensitive (e.g., '+').</p>
| 2,316 |
<p>is there a way to change an oracle user's default schema?</p>
<p>I found it in the FAQ that I can alter it in the session, but it's not what I want. E.G. the user at log on always sees another schema as default.</p>
<p>Thanks in advance.</p>
| <p>I believe a logon trigger should work:</p>
<pre><code>CREATE OR REPLACE TRIGGER db_logon
AFTER logon ON DATABASE WHEN (USER = 'A')
BEGIN
execute immediate 'ALTER SESSION SET CURRENT_SCHEMA = B';
END;
</code></pre>
| <pre><code>create or replace trigger AFTER_LOGON_TSFREL
AFTER LOGON ON "TSFRELEASEAPP".SCHEMA
BEGIN
EXECUTE IMMEDIATE 'ALTER SESSION SET current_schema=TSF_RELEASE';
END;
</code></pre>
| 35,960 |
<p>In Ruby, is there the equivalent of the <code>__str__()</code> method that you can define on Python classes? </p>
| <p>You could use to_s.</p>
<p><a href="http://briancarper.net/2006/09/26/ruby-to_s-vs-to_str/" rel="nofollow noreferrer">http://briancarper.net/2006/09/26/ruby-to_s-vs-to_str/</a></p>
| <p>On the core classes it is typically 'inspect'.</p>
<p>Eg:</p>
<pre><code>irb(main):001:0> puts "array is: #{[1,2,3].inspect}"
array is: [1, 2, 3]
=> nil
irb(main):002:0> puts "array is: #{[1,2,3]}"
array is: 123
=> nil
irb(main):003:0>
</code></pre>
| 16,349 |
<p>In the past and with most my current projects I tend to use a for loop like this:</p>
<pre><code>var elements = document.getElementsByTagName('div');
for (var i=0; i<elements.length; i++) {
doSomething(elements[i]);
}
</code></pre>
<p>I've heard that using a "reverse while" loop is quicker but I have no real way to confirm this:</p>
<pre><code>var elements = document.getElementsByTagName('div'),
length = elements.length;
while(length--) {
doSomething(elements[length]);
}
</code></pre>
<p>What is considered as best practice when it comes to looping though elements in JavaScript, or any array for that matter?</p>
| <p>Here's a nice form of a loop I often use. You create the iterated variable from the for statement and you don't need to check the length property, which can be expensive specially when iterating through a NodeList. However, <strong>you must be careful</strong>, you <strong>can't use it if any of the values in array could be "falsy"</strong>. In practice, I only use it when iterating over an array of objects that does not contain nulls (like a NodeList). But I love its syntactic sugar.</p>
<pre><code>var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];
for (var i=0, item; item = list[i]; i++) {
// Look no need to do list[i] in the body of the loop
console.log("Looping: index ", i, "item" + item);
}
</code></pre>
<p>Note that this can also be used to loop backwards.</p>
<pre><code>var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];
for (var i = list.length - 1, item; item = list[i]; i--) {
console.log("Looping: index ", i, "item", item);
}
</code></pre>
<p><strong>ES6 Update</strong></p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of" rel="nofollow noreferrer"><code>for...of</code></a> gives you the name but not the index, available since <a href="https://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements" rel="nofollow noreferrer">ES6</a></p>
<pre><code>for (const item of list) {
console.log("Looping: index ", "Sorry!!!", "item" + item);
}
</code></pre>
| <p>I like to use a <a href="https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker" rel="nofollow">TreeWalker</a> if the set of elements are children of a root node.</p>
| 19,028 |
<p>I have the following html code: </p>
<pre><code><h3 id="headerid"><span onclick="expandCollapse('headerid')">&uArr;</span>Header title</h3>
</code></pre>
<p>I would like to toggle between up arrow and down arrow each time the user clicks the span tag. </p>
<pre><code>function expandCollapse(id) {
var arrow = $("#"+id+" span").html(); // I have tried with .text() too
if(arrow == "&dArr;") {
$("#"+id+" span").html("&uArr;");
} else {
$("#"+id+" span").html("&dArr;");
}
}
</code></pre>
<p>My function is going always the else path. If I make a javacript:alert of <code>arrow</code> variable I am getting the html entity represented as an arrow. How can I tell jQuery to interpret the <code>arrow</code> variable as a string and not as html. </p>
| <p>When the HTML is parsed, what JQuery sees in the DOM is a <code>UPWARDS DOUBLE ARROW</code> ("⇑"), not the entity reference. Thus, in your Javascript code you should test for <code>"⇑"</code> or <code>"\u21d1"</code>. Also, you need to change what you're switching to:</p>
<pre><code>function expandCollapse(id) {
var arrow = $("#"+id+" span").html();
if(arrow == "\u21d1") {
$("#"+id+" span").html("\u21d3");
} else {
$("#"+id+" span").html("\u21d1");
}
}
</code></pre>
| <p>Maybe you're not getting an exact match because the browser is lower-casing the entity or something. Try using a carat (^) and lower-case "v" just for testing.</p>
<p>Edited - My first theory was plain wrong.</p>
| 4,983 |
<p>I'm using an <em>Edit in Place</em> jquery plugin which needs to post the data to a script that will do the actual database update.</p>
<p>The URL to this update script is easily viewable in the html source as well as with Firebug, so I need to add some sort of authentication check before the update is processed. This is of course so the user can't just pass in any old userid / field / value they want and mess with other people's records.</p>
<p>I was initially passing their username and password in as well, but this isn't ideal as it's in a GET request so it's all in the URL. The site itself is SSL at least, but still not a best practice by any stretch.</p>
<p>What's the best way to authenticate this type of update?</p>
<p>FWIW, the update script is in PHP, and the Edit in Place plugin is: <a href="http://www.appelsiini.net/projects/jeditable" rel="nofollow noreferrer">jeditable</a>.</p>
<p><strong>Edit:</strong> To clarify: The actual data payload is POSTed to the script, but the edit in place plugin has no explicit method for authentication, so I was passing the authentication as part of the URL to the update script, which was then taking those variables via GET and using them to check.</p>
<p><strong>Edit 2:</strong> Yes, I can access the session info from the update script, so I've decided to just pull the previously saved User ID and using that in the db update statement. That would appear to be the most secure method.</p>
| <p>I think you'd be best off switching the script to a POST method as most edit-in-place uses will be too big to use GET practically. You should never use the SessionId or the password as a URL parameter and I wouldn't use the username for anything but viewing a public profile. If your AJAX URL is a PHP file, I'm fairly certain it <em>should</em> be able to access the session without needing to pass it in either a GET or POST array. As an additional note, make sure that you validate and sanitize all information before updating the database.</p>
| <p>To pass the information you should use the session id in the actual GET string. This way the php script can connect to the session, validate the user, and see if the user has the rights to edit what they've posted. Then if they have the rights, proceed, or else return an error message.</p>
<p>I believe you can, in javascript, get the session id so it needn't be passed overtly.</p>
| 29,950 |
<p>Let's say I have the three following lists</p>
<p>A1<br>
A2<br>
A3 </p>
<p>B1<br>
B2</p>
<p>C1<br>
C2<br>
C3<br>
C4<br>
C5 </p>
<p>I'd like to combine them into a single list, with the items from each list as evenly distributed as possible sorta like this:</p>
<p>C1<br>
A1<br>
C2<br>
B1<br>
C3<br>
A2<br>
C4<br>
B2<br>
A3<br>
C5</p>
<p>I'm using .NET 3.5/C# but I'm looking more for how to approach it then specific code.</p>
<p>EDIT: I need to keep the order of elements from the original lists.</p>
| <ol>
<li><p>Take a copy of the list with the most members. This will be the destination list.</p>
</li>
<li><p>Then take the list with the next largest number of members.</p>
</li>
<li><p>divide the destination list length by the smaller length to give a fractional value of greater than one.</p>
</li>
<li><p>For each item in the second list, maintain a float counter. Add the value calculated in the previous step, and mathematically round it to the nearest integer (keep the original float counter intact). Insert it at this position in the destination list and increment the counter by 1 to account for it. Repeat for all list members in the second list.</p>
</li>
<li><p>Repeat steps 2-5 for all lists.</p>
</li>
</ol>
<p>EDIT: This has the advantage of being O(n) as well, which is always nice :)</p>
| <p>A quick suggestion, in python-ish pseudocode:</p>
<pre><code>merge = list()
lists = list(list_a, list_b, list_c)
lists.sort_by(length, descending)
while lists is not empty:
l = lists.remove_first()
merge.append(l.remove_first())
if l is not empty:
next = lists.remove_first()
lists.append(l)
lists.sort_by(length, descending)
lists.prepend(next)
</code></pre>
<p>This should distribute elements from shorter lists more evenly than the other suggestions here.</p>
| 44,866 |
<p>I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can't just use 127.0.0.1 in this case.</p>
<p>How can I accomplish this?</p>
| <p>In <a href="http://www.devcity.net/Articles/62/1/gethostbyname.aspx" rel="nofollow noreferrer" title="Article by John Spano, Published 1 Dec 2002"><em>How to get IP addresses in .NET with a host name</em></a> by John Spano, it says to add the <code>System.Net</code> namespace, and use the following code:</p>
<blockquote>
<pre><code>//To get the local IP address
string sHostName = Dns.GetHostName ();
IPHostEntry ipE = Dns.GetHostByName (sHostName);
IPAddress [] IpA = ipE.AddressList;
for (int i = 0; i < IpA.Length; i++)
{
Console.WriteLine ("IP Address {0}: {1} ", i, IpA[i].ToString ());
}
</code></pre>
</blockquote>
| <p>If you know there are one or more IPv4 addresses for your computer, this will provide one of them:</p>
<pre><code>Dns.GetHostAddresses(Dns.GetHostName())
.First(a => a.AddressFamily == AddressFamily.InterNetwork).ToString()
</code></pre>
<p><code>GetHostAddresses</code> normally blocks the calling thread while it queries the DNS server, and throws a <code>SocketException</code> if the query fails. I don't know whether it skips the network call when looking up your own host name.</p>
| 18,229 |
<p>We are currently working on an application that will use a WCF service. The host (the client) is using the excellent <a href="http://bloggingabout.net/blogs/erwyn/archive/2006/12/09/WCF-Service-Proxy-Helper.aspx" rel="nofollow noreferrer">WCF Service Proxy Helper from Erwyn van der Meer</a>.</p>
<p>What I would like to know... is if I open this object multiple times... will it lead to multiple (expensive) connections or will WCF manage it and pool the connections.</p>
<p>The reason why I want to know this is because we will be calling methods of the service at different point in time within the same web request and we currently have wrapped the instanciation of the Service proxy class within the call.</p>
<p>Eg.:</p>
<pre><code>MyService.MyMethod1() // wraps the connection usage as well as the call to the service
</code></pre>
<p>Any suggestions about how I would go to minimize the amount of connection while keeping the code conform with <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="nofollow noreferrer">SRP</a> would be excellent.</p>
<p>So? Any idea?</p>
| <p>You should try to minimize the number of proxy objects you create. Proxies in WCF are quite expensive to set up, so creating one and calling functions on it multiple times is definitely more efficient than creating a new one for each method invocation.</p>
<p>The relationship between proxy objects and connections depends on the transport used. For http transports, an HTTP connection is initiated for each function invocation. For the net.tcp transport, the connection is established at Open() time and kept until a Close(). Certain binding settings (eg those supporting WS-SecureConversation) will incur extra "housekeeping" connections and message exchanges.</p>
<p>AKAIK, none of the out-of-the-box bindings perform connection pooling.</p>
| <p>It doesn't do pooling like SqlConnection, if that is what you mean.</p>
<p>[caveat: I use "connection" here loosely to mean a logical connection, not necessarily a physical connection]</p>
<p>Between using a connection on-demand, and keeping one around, there are advantages and disadvantages to both approaches. There is some overhead in initializing a connection, so if you are doing 5 things you should try to do them on the same proxy - but I wouldn't keep a long term proxy around just for the sake of it.</p>
<p>In particular, in terms of life-cycle management, once a proxy has faulted, it stays faulted - so you need to be able to recover from the occasional failure (which should be expected). Equally, in some configurations (some combinations of session/instancing), a connection has a definite footprint on the server - so to improve scalability you should keep connections short-lived. Of course, for <em>true</em> scalability you'd usually want to disable those options anyway!</p>
<p>The cost of creating a connection also depends on things like the security mode. IIRC, it will be more expensive to open a two-way validated connection using message security than it will to set up a TransportWithMessageCredential connection - so "YMMV" is very much the case here.</p>
<p>Personally, I find that the biggest common issue with proxy performance isn't anything to do with the time to set up a conncetion - it is the chattiness of the API. i.e.</p>
<p>Scenario A:</p>
<ul>
<li>open a connection</li>
<li>perform 1 operation with a large payload (i.e. a message that means "do these 19 things")</li>
<li>close the proxy</li>
</ul>
<p>Scenario B:</p>
<ul>
<li>open a connecton</li>
<li>perform 19 operations with small payloads</li>
<li>close the connection</li>
</ul>
<p>Then scenario A will usually be <em>significantly</em> faster due to latency etc. And IMO don't even think about distributed transactions over WCF ;-p</p>
| 34,738 |
<p>I have very little experience building software for Windows, and zero experience using the Windows API, but I'm reasonably familiar with Python. How should I go about learning to use the Windows API with Python?</p>
| <p>Honestly, no. The Windows API is an 800 pound monster covered with hair. <a href="http://www.charlespetzold.com/faq.html" rel="noreferrer">Charlie Petzold's 15 pound book</a> was the canonical reference once upon a time.</p>
<p>That said, the <a href="http://python.net/crew/mhammond/win32/" rel="noreferrer">Python for Windows</a> folks have some good material. Microsoft has the <a href="http://msdn.microsoft.com/en-us/library/aa383749(VS.85).aspx" rel="noreferrer">whole API online</a>, including some sample code and such. And the <a href="http://en.wikipedia.org/wiki/Win32" rel="noreferrer">Wikipedia article</a> is a good overview.</p>
| <p>Once upon a time I read over some Win32 API tutorials at <a href="http://www.relisoft.com" rel="nofollow noreferrer">www.relisoft.com</a></p>
<p>They are an anti-MFC and pro-Win32 API shop and have a manifesto of sorts explaining practical reasons for why.</p>
<p>They also have a general C++ tutorial. 99% of the time I like their programming style for what it's worth.</p>
| 44,562 |
<p>I am trying to pass some Subsonic collections to a client via a web service. When I reference the web service the IDE complains with:</p>
<p>Cannot serialize member 'EndDate' of type System.Nullable`1[System.DateTime]. XmlAttribute/XmlText cannot be used to encode complex types.</p>
<p>Is there any way of serializing nullable complex types in a .net web service?</p>
| <p>The way you handle optional properties is to include a boolean XXXSpecified member where XXX is the name of the property. Nullable types are not handled properly by the xml serializer used by ASMX. Note that this is not a limitation of WCF.</p>
| <p>This is a .NET Limitation</p>
<p>If you want you can try generating your classes with this property in the SubSonicService section in the the web.config file.</p>
<p>generateNullableProperties="false"</p>
<p><a href="http://forums.subsonicproject.com/forums/t/3285.aspx" rel="nofollow noreferrer">http://forums.subsonicproject.com/forums/t/3285.aspx</a></p>
| 25,361 |
<p>I have a windows service written in dotNet. There is a worker service that spawns worker threads using various Delegate.BeginInvokes. When the service crashes are those threads going to be cleaned up automatically? And if so, when?</p>
| <p>All threads created by your process are inside that process. When your application crashes your process dies, and all threads in that process are terminated abruptly. They are not terminated friendly-like (they're not given an abort signal or anything), they are just killed. They may or may not be given enough processor time to finish executing -- rather depends on what they were doing, and how fast Windows dumps the process.</p>
<p>All robust versions of Windows (2000+) should have your process segregated, so when it dies the whole process space is dumped and the memory is reclaimed. If you were accessing unmanaged resources at the time of the crash, then the whole picture changes and the answer is "it depends".</p>
| <p>only when the service is terminated and unloaded from memory</p>
| 49,189 |
<p>I'd like to see a series of diffs for a file. I'd settle for simply the log listing restricted to only those entries that modified the file.</p>
| <p><code>svn log filename</code></p>
<p>or </p>
<pre><code>svn log URL
</code></pre>
<p>I also recommend adding <code>--limit N</code> to show only recent entries:</p>
<pre><code>svn log main.cpp --limit 4
</code></pre>
<p>These can be applied to a file or project, BTW.</p>
| <p>SVN Log for a single file</p>
<blockquote>
<p>svn log filename.php</p>
</blockquote>
<p>SVN diff for changes on a file between revision 1033 and 1191</p>
<blockquote>
<p>svn -r 1033:1191 diff filename.php</p>
</blockquote>
| 45,658 |
<p>I have a site where users can post stuff (as in forums, comments, etc) using a customised implementation of TinyMCE. A lot of them like to copy & paste from Word, which means their input often comes with a plethora of associated MS inline formatting.</p>
<p>I can't just get rid of <code><span whatever></code> as TinyMCE relies on the span tag for some of it's formatting, and I can't (and don't want to) force said users to use TinyMCE's "Paste From Word" feature (which doesn't seem to work that well anyway).</p>
<p>Anyone know of a library/class/function that would take care of this for me? It must be a common problem, though I can't find anything definitive. I've been thinking recently that a series of brute-force regexes looking for MS-specific patterns might do the trick, but I don't want to re-write something that may already be available unless I must.</p>
<p>Also, fixing of curly quotes, em-dashes, etc would be good. I have my own stuff to do this now, but I'd really just like to find one MS-conversion filter to rule them all.</p>
| <p><a href="http://htmlpurifier.org/" rel="noreferrer">HTML Purifier</a> will create standards compliant markup and filter out many possible attacks (such as XSS).</p>
<p>For faster cleanups that don't require XSS filtering, I use the PECL extension <a href="http://www.php.net/tidy" rel="noreferrer">Tidy</a> which is a binding for the <a href="http://www.w3.org/People/Raggett/tidy/" rel="noreferrer">Tidy HTML</a> utility.</p>
<p>If those don't help you, I suggest you switch to FCKEditor which has this feature <a href="http://docs.fckeditor.net/FCKeditor_2.x/Users_Guide/Common_Tasks/Cut%2C_Copy_and_Paste" rel="noreferrer">built-in</a>.</p>
| <p>The website <a href="http://word2cleanhtml.com/" rel="nofollow">http://word2cleanhtml.com/</a> does a good job on converting from Word. I'm using it in PHP by scrapping, to process some legacy HTML, and until now it's working pretty fine (the result is very clean <code><p>, <b></code> code). Of course, being an external service it's not good to use it in online processing like your case.</p>
<p>If you try it and it brings many 400 errors, try filtering the HTML with <a href="http://php.net/manual/en/tidy.repairstring.php" rel="nofollow" title="Tidy">Tidy</a> first.</p>
| 49,696 |
<p>When should you NOT use a singleton class although it might be very tempting to do so? It would be very nice if we had a list of most common instances of 'singletonitis' that we should take care to avoid.</p>
| <p>Do not use a singleton for something that might evolve into a multipliable resource.</p>
<p>This probably sounds silly, but if you declare something a singleton you're making a very strong statement that it is absolutely unique. You're building code around it, more and more. And when you then find out after thousands of lines of code that it is not a singleton at all, you have a huge amount of work in front of you because all the other objects expect "the" sacred object of class WizBang to be a singleton.</p>
<p>Typical example: "There is only one database connection this application has, thus it is a singleton." - Bad idea. You may want to have several connections in the future. Better create a pool of database connections and populate it with just one instance. Acts like a Singleton, but all other code will have growable code for accessing the pool.</p>
<p><strong>EDIT:</strong> I understand that theoretically you can extend a singleton into several objects. Yet there is no real life cycle (like pooling/unpooling) which means there is no real ownership of objects that have been handed out, i.e. the now multi-singleton would have to be stateless to be used simultaneously by different methods and threads.</p>
| <p>One of the things that tend to make it a nightmare is if it contains <strong>modifiable</strong> global state. I worked on a project where there were Singletons used all over the place for things that should have been solved in a completely different way (pass in strategies etc.) The "de-singletonification" was in some cases a major rewrite of parts of the system. I would argue that in the bigger part of the cases when people use a Singleton, it's just wrong b/c it looks nice in the first place, but turns into a problem especially in testing.</p>
| 16,394 |
<p>is it possible to throw a custom error message to a ThrowActivity, in windows workflow foundation?</p>
<p>eg. Imagine i want to throw this exception, in my WF :-</p>
<pre><code>CutomException("This is my custom error message", myNumber, myObect);
</code></pre>
<p>cheers :)</p>
| <p>Maybe I do not understand your question well, but you can set the specific exception with the <code>Fault</code> property of <code>ThrowActivity</code> in any place before the activity execution, e.g.:</p>
<pre><code>throwActivity1.Fault = new CustomException("This is my custom error message", myNumber, myObect);
</code></pre>
| <p>You can throw any custom exception like this way.</p>
<p>public DiscontinuedProductException discontinuedProductException1 = new DiscontinuedProductException();</p>
<p>[SerializableAttribute()]
public class DiscontinuedProductException : Exception
{
public DiscontinuedProductException()
: base()
{
}</p>
<pre><code> public DiscontinuedProductException(string message)
: base(message)
{
}
public DiscontinuedProductException(string message, Exception innerException)
: base(message, innerException)
{
}
protected DiscontinuedProductException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
</code></pre>
| 36,370 |
<p>I've been asked to display the 'correct' time on our website which I frankly feel is rather pointless as 'correct' can be interpretted in such a variety of ways.</p>
<p>Our current method definately results in an inaccurate time as it uses a server control rendering JavaScript that runs onload using the datetime from the server as a parameter to create a clock object in JavaScript that finally renders on the page and then starts incrementing the clock. Between the server processing, network latency and client-side performance (there's plenty other stuff running onload) the clock ends up way off the actual server time and who knows compared to the client PC.</p>
<p>So to get the 'correct' time shown I could;</p>
<ul>
<li>Use local PC time and pass new Date() to the JavaScript clock object. Pros: Should be as close to the PC clock as possible. Cons: Not sure how accurate the PC clock is let alone in which timezone.</li>
<li>Use web service for TCP request to NTP server to update clock on web page. Pros: If local PC also sync'd to NTP will be accurate and best possible match. Cons: Will have to handle all the timezone adjustments relative to our servers. If PC clock is out will still have mismatch.</li>
</ul>
<p>Do I implement my own web service or use something like; <a href="http://www.earthtools.org/webservices.htm" rel="nofollow noreferrer">Earth Tools</a> or World Time Web Service (<strong>EDIT:</strong> link removed - now 404)</p>
<p>Here's a blog post from <a href="http://weblogs.asp.net/jgalloway/archive/2004/04/08/110029.aspx" rel="nofollow noreferrer">Jon Galloway on Atomic Clock Web Service</a> which is pretty old and yet ranks high when I google and he doesn't reach a conclusion.</p>
<p>Hoepfully I can win the argument with management why syncing to our server clock (GMT) doesn't makes sense if your not in that timezone and why we even need to match a local PC.</p>
<p>Any angles on this I'm missing?</p>
| <p>I needed to show the accurate time to clients in an auction web app. You can send the current server time with the page and have the javascript initialize right away without waiting for the rest of the page to load. So the, you only are dealing with network latency which in the worst case is not likely to be more than a couple of seconds. </p>
<p>After that, you're pretty darn close to accurate time. As long as your Javascript timer code is written properly, you're not going to far out of sync before the next page load. But I have seen a lot of bad JS clock code. (Hint: Date() good, setTimeout() bad.)</p>
<p>If you have an application that users are going to be sitting on for a long time, just refresh your time sync either by reloading the page or Ajax.</p>
<p>I wouldn't worry about time zones, just use UTC time so there is no confusion about what time things will happen. </p>
| <p>you can use <a href="http://en.wikipedia.org/wiki/Geo_targeting" rel="nofollow noreferrer">geo targeting</a> to know the physical location of a website visitor and in your database stored the (GMT - XX:XX) of the zone and then calculate the time based on the location of the request. that is going to save the long trip to any third party web service.</p>
| 30,263 |
<p>We are getting very slow compile times, which can take upwards of 20+ minutes on dual core 2GHz, 2G Ram machines.</p>
<p>A lot of this is due to the size of our solution which has grown to 70+ projects, as well as VSS which is a bottle neck in itself when you have a lot of files. (swapping out VSS is not an option unfortunately, so I don't want this to descend into a VSS bash)</p>
<p>We are looking at merging projects. We are also looking at having multiple solutions to achieve greater separation of concerns and quicker compile times for each element of the application. This I can see will become a DLL hell as we try to keep things in synch.</p>
<p>I am interested to know how other teams have dealt with this scaling issue, what do you do when your code base reaches a critical mass that you are wasting half the day watching the status bar deliver compile messages.</p>
<p><strong>UPDATE</strong>
I neglected to mention this is a C# solution. Thanks for all the C++ suggestions, but it's been a few years since I've had to worry about headers.</p>
<p><strong>EDIT:</strong></p>
<p>Nice suggestions that have helped so far (not saying there aren't other nice suggestions below, just what has helped)</p>
<ul>
<li>New 3GHz laptop - the power of lost utilization works wonders when whinging to management
<li>Disable Anti Virus during compile
<li>'Disconnecting' from VSS (actually the network) during compile - I may get us to remove VS-VSS integration altogether and stick to using the VSS UI
</ul>
<p>Still not rip-snorting through a compile, but every bit helps.</p>
<p>Orion did mention in a comment that generics may have a play also. From my tests there does appear to be a minimal performance hit, but not high enough to sure - compile times can be inconsistent due to disc activity. Due to time limitations, my tests didn't include as many Generics, or as much code, as would appear in live system, so that may accumulate. I wouldn't avoid using generics where they are supposed to be used, just for compile time performance</p>
<p><strong>WORKAROUND</strong></p>
<p>We are testing the practice of building new areas of the application in new solutions, importing in the latest dlls as required, them integrating them into the larger solution when we are happy with them.</p>
<p>We may also do them same to existing code by creating temporary solutions that just encapsulate the areas we need to work on, and throwing them away after reintegrating the code. We need to weigh up the time it will take to reintegrate this code against the time we gain by not having Rip Van Winkle like experiences with rapid recompiling during development.</p>
| <p>The Chromium.org team listed several options for <a href="http://dev.chromium.org/developers/how-tos/build-instructions-windows" rel="noreferrer">accelerating the build</a> (at this point about half-way down the page):</p>
<blockquote>
<p>In decreasing order of speedup:</p>
<ul>
<li>Install Microsoft hotfix <a href="http://support.microsoft.com/kb/935225" rel="noreferrer">935225</a>.</li>
<li>Install Microsoft hotfix <a href="http://support.microsoft.com/kb/947315" rel="noreferrer">947315</a>. </li>
<li>Use a true multicore processor (ie. an Intel Core Duo 2; not a Pentium 4 HT).</li>
<li>Use 3 parallel builds. In Visual Studio 2005, you will find the option in <strong>Tools > Options... > Projects and Solutions > Build and Run > maximum number of parallel project builds</strong>.</li>
<li>Disable your anti-virus software for .ilk, .pdb, .cc, .h files and only check for viruses on <strong>modify</strong>. Disable scanning the directory where your sources reside. Don't do anything stupid.</li>
<li>Store and build the Chromium code on a second hard drive. It won't really speed up the build but at least your computer will stay responsive when you do gclient sync or a build.</li>
<li>Defragment your hard drive regularly.</li>
<li>Disable virtual memory.</li>
</ul>
</blockquote>
| <p>Slow Visual Studio Performance … Solved!
September 24th, 2014 by Uzma Abidi</p>
<p>I had an odd performance-related issue today. My Microsoft Visual Studio seemed to be taking far too long to perform even the simplest of operations. I Googled around and tried a few ideas that people had such as disabling add-ins or clearing Visual Studio’s recent projects list but those suggestions didn’t seem to solve the problem. I remembered that the Windows SysInternals website had a tool called Process Monitor that would sniff registry and file accesses by any running program. It seemed to me that Visual Studio was up to something and Process Monitor should help me figure out what it was. I downloaded the most recent version, and after fiddling around a bit with its display filters, ran it and to my horror, I saw that Visual Studio was so slow because it was accessing the more than 10,000 folders in C:\Users\krintoul\AppData\Local\Microsoft\WebSiteCache on most IDE operations. I’m not sure why there were that many folders and moreover, wasn’t sure what Visual Studio was doing with them, but after I zipped those folders up and moved them somewhere else, Visual Studio’s performance improved tremendously.</p>
<p>The Windows SysInternals website has a number of other useful utilities for network management, security, system information and more. Check it out. I’m sure you’ll find something of value.</p>
| 7,932 |
<p>I'm writing a few little bash scripts under Ubuntu linux. I want to be able to run them from the GUI without needing a terminal window to enter any input or view any output.</p>
<p>So far the only input required is a password for sudo - and gksudo handles that fine.
But I haven't found an easy way to show a message box yet. Is there some kind of 'gkmessage' command available? I'd prefer something present in a default Ubuntu install, but I don't mind installing a new package if necessary.</p>
| <p>I believe <a href="http://live.gnome.org/Zenity" rel="noreferrer">Zenity</a> will do what you want. It's specifically designed for displaying GTK dialogs from the command line, and it's available as an <a href="http://packages.ubuntu.com/hardy/zenity" rel="noreferrer">Ubuntu package</a>.</p>
| <p>Kdialog and dialog are both good, but I'd recommend Zenity. Quick, easy, and much better looking the xmessage or dialog. </p>
| 2,870 |
<p>In Nant, I would like to be able to extract the last name of the directory in a path.<br>
For example, we have the path 'c:\my_proj\source\test.my_dll\'</p>
<p>I would like to pass in that path and extract 'test.my_dll'</p>
<p>Is there a way to easily do this?</p>
| <p>You can actually do it with existing NAnt string functions. Just a bit ugly...</p>
<pre><code>${string::substring(path, string::last-index-of(path, '\') + 1, string::get-length(path) - string::last-index-of(path, '\') - 1)}
</code></pre>
| <p>No. You'll need to write a custom task for something like that.</p>
| 17,612 |
<p>I have several blocks of the following code that each use there own matrix. Is there a way to run each block in it's own thread rather then run all of them sequentially?</p>
<pre>
for i=1:length(DJI)
DJI2(:,1) = reshape(datenum(strvcat(DJI(:,2)(:)), length(DJI(:,2)),'yyyy-mm-dd'));
DJI2(:,2:6) = reshape(str2num(strvcat(DJI(:,3:7)(:)), length(DJI(:,3:7))));
end
</pre>
| <p>If you want to go with the preconfigured distribution, but still want to let your developers choose, which plugins from a restricted set of plugins to install additionally, then its worth to create a company internal update site, which <strong>mirrors selected features</strong> and plugins, so your developers can install them (and only them!).</p>
<p>The <a href="http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/update_sitemap.html" rel="nofollow noreferrer">Eclipse help</a> has a full description of how to mirror update sites (from the command line).</p>
| <p>We do not have <em>exactly</em> a common eclipse configuration but rather a common eclipse <strong>distribution</strong>.</p>
<p>A new developer copy that distribution, and launches it through a custom "eclipse.exe" which:</p>
<ul>
<li>calls a script checking if there is any in-house updates I have set up since the last launch (like a new enhanced eclipse.ini, new plugins, new config files, ...)</li>
<li>calls the real eclipse.exe and actually launches the IDE</li>
</ul>
<p>That way, all developer have a platform which evolves according to <em>my common</em> additions to the global common development system.</p>
| 45,802 |
<p>If I have a form-backing object that has a complicated object tree -- say a Person that has a Contact Info object that has an Address object that has a bunch of Strings -- it seems that the object needs to be fully populated with component objects before I can bind to it. So if I'm creating a new Person, I need to make sure it has all the component objects populated off the bat, and if I'm retrieving a Person from the database, I need to make sure that any objects that aren't populated from the database get populated with empty objects.</p>
<p>First question, of course -- am I correct in my assumptions above? It does seem that if I try to bind to person.contactInfo.homeAddress.street and there is no ContactInfo, I get a null pointer exception.</p>
<p>Second, what's the best way to initialize my object. I can think of a couple of approaches. One is to initialize all member objects at declaration:</p>
<pre><code>public class Person {
String name;
ContactInfo contactInfo = new ContactInfo();
//getters, setters, etc.
}
public class ContactInfo {
String phone;
Address homeAddress = new Address();
}
</code></pre>
<p>and so forth.</p>
<p>Another approach is to have a PersonFactory that initializes everything (or to have a factory method Person.getInstance that initializes everything).</p>
<p>In the case of retrieving a Person from the database, the first approach will solve the issue (i.e. if this particular person doesn't have an address in the database, the object will still have an Address), but this will mean creating each object twice. Not sure how to handle this otherwise, except to make the DAO explicitly populate everything even if nothing has been retrieved from the database. Or to give the factory a method to go through the object and "fill in" anything that's missing.</p>
<p>Suggestions?</p>
| <p>Call it overkill if you like, but what we actually ended up doing was to create a generic factory that will take any object and use reflection to (recursively) find all the null properties and instantiate an object of the correct type. I did this using Apache Commons BeanUtils. </p>
<p>This way you can take an object that you may have gotten from various sources (a DAO, deserialization from XML, whatever), pass it through this factory, and use it as a form-backing object without worrying that something you need for binding may be null.</p>
<p>Admittedly, this means instantiating properties that we may not need for a given form, but in our case that doesn't typically apply.</p>
| <p>I guess you are talking about something like <code> < form:input path="person.contactInfo.homeAddress.street"/></code> ?
Not clear for me but assuming i'm right :) :</p>
<p>1) Yes, When you write <code>person.contactInfo.homeAddress.street </code>, read <code>person.getContactInfo().getHomeAddress().getStreet()</code>. If ContactInfo or HomeAddress or Street objects are null, invocation of one of their method raises a NullPointException.</p>
<p>2)I usually initializes member objects at declaration, just like in code snippet. Don't see the benefit of factory class to do the job if initialization values are inconditionnal.
I don't clearly see the problem where you are forced to create a Person twice... but i may be tired ;)</p>
| 49,511 |
<p>What is the simplest way to install memcached on CentOS for someone new to the world of Linux? What is the best way to enable it for Apache and PHP</p>
| <p>Unless Apache and PHP have some option to utilize memcached for internal workings (of which I am unaware of), you typically don't "enable" it for such apps. Instead, you would get a <a href="http://www.danga.com/memcached/apis.bml" rel="nofollow noreferrer">client library</a> to use memcached from within your application, then start up memcached on whatever servers you want to provide memory with, then just use the client library API to store and retrieve cached data across multiple servers.</p>
| <p>The easiest way is to find a reilable source of the RPM's needed to install memcached and memcached for PHP. There is a blog post which addresses this concern:</p>
<p><a href="http://blog.gahooa.com/2009/02/08/update-on-fedora-vs-redhat-enterprise-linux/" rel="nofollow noreferrer">http://blog.gahooa.com/2009/02/08/update-on-fedora-vs-redhat-enterprise-linux/</a></p>
<p>We have been using EPEL (Extra Packages for Enterprise Linux) for exactly that on RedHat Enterprise 5.3. I believe it is a stated goal of EPEL to support Centos.</p>
<p><a href="http://fedoraproject.org/wiki/EPEL" rel="nofollow noreferrer">http://fedoraproject.org/wiki/EPEL</a></p>
<p>Essentially, it is a YUM repository which contains lots of extra packages from Fedora that were compiled for RHEL. <strong>Super easy to use.</strong></p>
| 4,358 |
<p>I'm building a site using ajax and am trying to decide where to put the files that supply the data for the ajax requests.</p>
<p>For example, I am going to have a .js file that can be included in a page that will create country/state select boxes. I will have the .js file under /inc/js.</p>
<p>However, I am not sure where I want to put the ajax file that supplies the state data based on the country selected. I could put it next to the file it supports, make a folder for ajax data request files, etc.</p>
<p>What do you do to keep your ajax requests organized by file?</p>
| <p>If you're planning on using a Model-View-Controller architecture, then you would place your ajax handler scripts where you maintain the remainder of the your controller scripts for the site.</p>
<p>For example:</p>
<pre>
/application
/default
/controllers
index.php
index.ajax.php
/views
index.tpl
index.ajax.tpl
/admin
</pre>
<p>Using a model like this, it leaves you free to decide whether it makes more sense to create handler scripts for your ajax calls or to integrate the handler scripts for your ajax calls into the other, existing controller scripts.</p>
| <p>Create a separate site (same server or on another) that will serve only as a REST service generating output for your requests.
When you work with AJAX you are in essence consuming published web services.</p>
| 30,913 |
<p>Is there a tool for Windows XP and Vista (built-in or otherwise ideally freeware/<a href="http://en.wikipedia.org/wiki/Open_source_software" rel="nofollow noreferrer">OSS</a>) that can notify the user when the CPU is above a (configurable) threshold for some (configurable) duration?</p>
<p>I am particularly interested in a <em>minimalist</em> tool that fits the following bill and in order of importance (which a lot of the built-in Windows facilities like <a href="http://technet.microsoft.com/en-us/library/cc749249.aspx" rel="nofollow noreferrer">Performance/Resource Monitor</a> do not):</p>
<ol>
<li>Does not require administrative privileges</li>
<li>Has a <em>low working set</em> so it has no observable cost if left running forever</li>
<li>Monitors silently in the system tray</li>
<li>Uses a subtle (not in-your-face) notification method like showing a balloon tip with the name of the offending process that has been maximizing the CPU</li>
<li>Can be configured to start automatically when a user logs on interactively</li>
</ol>
| <p>Maybe <a href="http://www.donationcoder.com/Software/Mouser/proctamer/index.html" rel="nofollow noreferrer">ProcessTamer</a> could be helpfull. It does not exactly what you are look for. But it might be a quick and dirty solution.</p>
<blockquote>
<p>Process Tamer is a tiny (140k) and super efficient utility for Microsoft Windows XP/2K/NT that runs in your system tray and constantly monitors the cpu usage of other processes. When it sees a process that is overloading your cpu, it reduces the priority of that process temporarily, until its cpu usage returns to a reasonable level.</p>
<p><a href="https://i.stack.imgur.com/YlwLp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YlwLp.png" alt="Screenshot"></a><br>
<sub>(source: <a href="https://www.donationcoder.com/Software/Mouser/proctamer/screenshots/pt.png" rel="nofollow noreferrer">donationcoder.com</a>)</sub> </p>
</blockquote>
| <p>You could write your own utility.</p>
<p>Here a sample as starter:
<a href="http://gist.github.com/11658" rel="nofollow noreferrer">http://gist.github.com/11658</a></p>
<ol>
<li>Create a CpuMeter instance</li>
<li>ResetCounter</li>
<li>Wait for an intervall</li>
<li>Check Cpu utilisation</li>
<li>Start again</li>
</ol>
| 12,634 |
<p>Please consider the following <code>fork()</code>/<code>SIGCHLD</code> pseudo-code.</p>
<pre><code> // main program excerpt
for (;;) {
if ( is_time_to_make_babies ) {
pid = fork();
if (pid == -1) {
/* fail */
} else if (pid == 0) {
/* child stuff */
print "child started"
exit
} else {
/* parent stuff */
print "parent forked new child ", pid
children.add(pid);
}
}
}
// SIGCHLD handler
sigchld_handler(signo) {
while ( (pid = wait(status, WNOHANG)) > 0 ) {
print "parent caught SIGCHLD from ", pid
children.remove(pid);
}
}
</code></pre>
<p>In the above example there's a race-condition. It's possible for "<code>/* child stuff */</code>" to finish before "<code>/* parent stuff */</code>" starts which can result in a child's pid being added to the list of children after it's exited, and never being removed. When the time comes for the app to close down, the parent will wait endlessly for the already-finished child to finish.</p>
<p>One solution I can think of to counter this is to have two lists: <code>started_children</code> and <code>finished_children</code>. I'd add to <code>started_children</code> in the same place I'm adding to <code>children</code> now. But in the signal handler, instead of removing from <code>children</code> I'd <em>add</em> to <code>finished_children</code>. When the app closes down, the parent can simply wait until the difference between <code>started_children</code> and <code>finished_children</code> is zero.</p>
<p>Another possible solution I can think of is using shared-memory, e.g. share the parent's list of children and let the children <code>.add</code> and <code>.remove</code> themselves? But I don't know too much about this.</p>
<p>EDIT: Another possible solution, which was the first thing that came to mind, is to simply add a <code>sleep(1)</code> at the start of <code>/* child stuff */</code> but that smells funny to me, which is why I left it out. I'm also not even sure it's a 100% fix.</p>
<p>So, how would you correct this race-condition? And if there's a well-established recommended pattern for this, please let me know!</p>
<p>Thanks.</p>
| <p>Simplest solution would be to block SIGCHLD signal before <code>fork()</code> with <code>sigprocmask()</code> and unblock it in parent code after you have processed the pid.</p>
<p>If child died, signal handler for SIGCHLD will be called after you unblock the signal. It is a critical section concept - in your case critical section starts before <code>fork()</code> and ends after <code>children.add()</code>.</p>
| <p>In addition to the existing "children" add a new data structure "early deaths". This will keep the contents of children clean.</p>
<pre><code> // main program excerpt
for (;;) {
if ( is_time_to_make_babies ) {
pid = fork();
if (pid == -1) {
/* fail */
} else if (pid == 0) {
/* child stuff */
print "child started"
exit
} else {
/* parent stuff */
print "parent forked new child ", pid
if (!earlyDeaths.contains(pid)) {
children.add(pid);
} else {
earlyDeaths.remove(pid);
}
}
}
}
// SIGCHLD handler
sigchld_handler(signo) {
while ( (pid = wait(status, WNOHANG)) > 0 ) {
print "parent caught SIGCHLD from ", pid
if (children.contains(pid)) {
children.remove(pid);
} else {
earlyDeaths.add(pid);
}
}
}
</code></pre>
<p>EDIT: this can be simplified if your process is single threaded -- earlyDeaths doesn't have to be a container, it just has to hold one pid.</p>
| 44,210 |
<p>What is the difference between ArrayList and List in VB.NET</p>
| <p>ArrayLists are essentially deprecated as they're untyped - you need to use casts with them - and they're slower and less space efficient for value types because they require the items to be boxed.</p>
<p>Generic lists were introduced with .Net 2.0 and are the way to go. Often a List is better than an array, with few downsides.</p>
<p>As these collections are part of the .Net Base Class Library, this advice also applies to C# and to any .Net language which supports generics - it's not specific to VB.NET.</p>
| <p>List can make use of generics so that only objects of specific types can be placed into it, so that you can have extra type checking and so that you can cut down on processing time due to boxing and unboxing. Arraylist cannot use this. In almost all cases, you'll want to use a List rather than an Arraylist.</p>
| 47,717 |
<p>I am trying to write a grammar in EBNF (barring a really good reason, it has to be EBNF) and am looking for a couple of utilities for it - if there's a GUI interface that can make one, that would be great, but the thing I'm looking for most is something that can check the grammar, for instance to see if it is LALR(<em>n</em>), and if so, what the value of <em>n</em> is. Do such utilities exist? Are there any other useful grammar-writing tools I should know about (I'm not looking for parser generators).</p>
| <p>Taking Steven Dee's suggestion one step further, you might want to check out <a href="http://www.antlr.org/works/index.html" rel="nofollow noreferrer">ANTLRWorks</a>, which is an interactive GUI development tool for ANTLR grammars.</p>
| <p><a href="http://www.antlr.org/" rel="nofollow noreferrer">ANTLR</a> is a GUI parser generator in Java that has extensive capabilities for grammar analysis and factoring. Check the FAQ; it might support what you're looking for.</p>
| 33,094 |
<p>I have a pretty good knowledge of programming languages like C/C++, Java, Python. But they were all mostly learnt in a college / high school class room setting where the best user interface was a numbered menu. You know, the standard data structures, implementation of various algorithms, file handling and the like. </p>
<p>What I want to do now is to get into GUI programming. I am not sure if I am asking the right way, but I am looking at using the WIMP paradigm (windows icons menus pointers). I want to place buttons and forms. Event driven programming, I believe is the right word, where my application waits till the user clicks something, types something etc. </p>
<p>Given my background, where would be a good place to start? I am looking at the following requirements - </p>
<p>1> Preferably cross platform.
2> Lots of documentations, tutorials, and if possible sample code that I can learn off of
3> A good GUI builder tool, where I can drag / drop stuff the way I want them to be displayed. </p>
<p>Any ideas or suggestions to get me started? </p>
| <p>I'l try the book <a href="https://rads.stackoverflow.com/amzn/click/com/1568843224" rel="noreferrer" rel="nofollow noreferrer">About face: Essential of User Interface Design</a>, its centered on design practices for UI as well as designing taking into account the user goals, that is, what the user wants to acomplish trying to get you away for the "developer GUI design".</p>
<p>It also reviews some history about GUI design from Microsoft, Apple and other companys. Things like defaults for MacOsX (where the accept and cancel buttons are usually located, etc) as well and the whys beneath that.</p>
<p>I'll also look up the <a href="http://www.microsoft.com/downloadS/details.aspx?FamilyID=68fc3e77-871c-4b14-915c-1cb029e63cca&displaylang=en" rel="noreferrer">Office 2007 UI Design Guidelines</a> for Microsoft as it's probably "gonna be a thing".</p>
| <p>I would look into C# .NET development and its <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="nofollow noreferrer">WinForms</a> API. It's much easier to program GUI desktop apps for Windows with that than with the Win32 API. You can always ease into Win32 API stuff later, if it's still relevant.</p>
<p>For cross-platform solutions, look into <a href="http://www.gtk.org/" rel="nofollow noreferrer">Gtk+</a>, perhaps <a href="http://www.pygtk.org/" rel="nofollow noreferrer">PyGtk</a>. Another good one is <a href="http://www.wxwidgets.org/" rel="nofollow noreferrer">WxWidgets</a>.</p>
<p>If you want to get really funky, check out <a href="http://shoooes.net/" rel="nofollow noreferrer">Shoes</a> for Ruby.</p>
| 11,399 |
<p>From the man page on git-merge, there are a number of merge strategies you can use. </p>
<ul>
<li><p><em>resolve</em> -
This can only resolve two heads (i.e. the current branch and another branch you pulled from) using 3-way merge algorithm. It tries to carefully detect criss-cross merge ambiguities and is considered generally safe and fast.</p></li>
<li><p><em>recursive</em> -
This can only resolve two heads using 3-way merge algorithm. When there are more than one common ancestors that can be used for 3-way merge, it creates a merged tree of the common ancestors and uses that as the reference tree for the 3-way merge. This has been reported to result in fewer merge conflicts without causing mis-merges by tests done on actual merge commits taken from Linux 2.6 kernel development history. Additionally this can detect and handle merges involving renames. This is the default merge strategy when pulling or merging one branch.</p></li>
<li><p><em>octopus</em> -
This resolves more than two-head case, but refuses to do complex merge that needs manual resolution. It is primarily meant to be used for bundling topic branch heads together. This is the default merge strategy when pulling or merging more than one branches.</p></li>
<li><p><em>ours</em> -
This resolves any number of heads, but the result of the merge is always the current branch head. It is meant to be used to supersede old development history of side branches.</p></li>
<li><p><em>subtree</em> -
This is a modified recursive strategy. When merging trees A and B, if B corresponds to a subtree of A, B is first adjusted to match the tree structure of A, instead of reading the trees at the same level. This adjustment is also done to the common ancestor tree.</p></li>
</ul>
<p>When should I specify something different than the default? What scenarios are each best for?</p>
| <p>I'm not familiar with resolve, but I've used the others:</p>
<h2>Recursive</h2>
<p>Recursive is the default for non-fast-forward merges. We're all familiar with that one.</p>
<h2>Octopus</h2>
<p>I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.</p>
<p>An octopus branch merges multiple heads in one commit as long as it can do it cleanly.</p>
<p>For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).</p>
<p>A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):</p>
<p><a href="https://i.stack.imgur.com/y9LeY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/y9LeY.png" alt="series of recursive merges"></a></p>
<p>However, a single octopus merge would look like this:</p>
<pre><code>commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...
</code></pre>
<p><a href="https://i.stack.imgur.com/jctXz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jctXz.png" alt="octopus merge"></a></p>
<h2>Ours</h2>
<p>Ours == I want to pull in another head, but throw away all of the changes that head introduces.</p>
<p>This keeps the history of a branch without any of the effects of the branch.</p>
<p>(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use <code>git merge -X ours</code>)</p>
<h2>Subtree</h2>
<p>Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.</p>
| <p>With Git 2.30 (Q1 2021), there will be a <em>new</em> merge strategy: <strong>ORT</strong> ("<strong>Ostensibly Recursive's Twin</strong>").</p>
<pre><code>git merge -s ort
</code></pre>
<p>This comes from <a href="https://public-inbox.org/git/CABPp-BFRftNf8hoj8nTDiw+akci=w2qVAgamVDyRw1NUk-QCNA@mail.gmail.com/" rel="noreferrer">this thread</a> from Elijah Newren:</p>
<blockquote>
<p>For now, I'm calling it "Ostensibly Recursive's Twin", or "ort" for short. >
At first, people shouldn't be able to notice any difference between it and the current recursive strategy, other than the fact that I think I can make it a bit faster (especially for big repos).</p>
<p>But it should allow me to fix some (admittedly corner case) bugs that are harder to handle in the current design, and I think that a merge that doesn't touch <code>$GIT_WORK_TREE</code> or <code>$GIT_INDEX_FILE</code> will allow for some fun new features.<br />
That's the hope anyway.</p>
</blockquote>
<p><a href="https://public-inbox.org/git/[email protected]/" rel="noreferrer">Problem</a>:</p>
<blockquote>
<p>In the ideal world, we should:</p>
<ul>
<li><p>ask <code>unpack_trees()</code> to do "<code>read-tree -m</code>" without "<code>-u</code>";</p>
</li>
<li><p>do all the merge-recursive computations in-core and prepare the
resulting index, while keeping the current index intact;</p>
</li>
<li><p>compare the current in-core index and the resulting in-core index, and notice the paths that need to be added, updated or removed in the working tree, and ensure that there is no loss of information when the change is reflected to the working tree;<br />
E.g. the result wants to create a file where the working tree currently has a directory with non-expendable contents in it, the result wants to remove a file where the working tree file has local modification, etc.;<br />
And then finally</p>
</li>
<li><p>carry out the working tree update to make it match what the resulting in-core index says it should look like.</p>
</li>
</ul>
</blockquote>
<p>Result:</p>
<p>See <a href="https://github.com/git/git/commit/14c4586c2dfa94d86d71a60481dd20bc5b56e562" rel="noreferrer">commit 14c4586</a> (02 Nov 2020), <a href="https://github.com/git/git/commit/fe1a21d5267cae88d4312e3595909720717eb31c" rel="noreferrer">commit fe1a21d</a> (29 Oct 2020), and <a href="https://github.com/git/git/commit/47b1e890e3f7ba57e8c5bc364dcb04d8b2dc1c58" rel="noreferrer">commit 47b1e89</a>, <a href="https://github.com/git/git/commit/17e5574b0446836af08136ae269b30767c05b1d7" rel="noreferrer">commit 17e5574</a> (27 Oct 2020) by <a href="https://github.com/newren" rel="noreferrer">Elijah Newren (<code>newren</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/a1f95951efc55c97477e32287b06e204553be5c2" rel="noreferrer">commit a1f9595</a>, 18 Nov 2020)</sup></p>
<blockquote>
<h2><a href="https://github.com/git/git/commit/17e5574b0446836af08136ae269b30767c05b1d7" rel="noreferrer"><code>merge-ort</code></a>: barebones API of new merge strategy with empty implementation</h2>
<p><sup>Signed-off-by: Elijah Newren</sup></p>
</blockquote>
<blockquote>
<p>This is the beginning of a new merge strategy.</p>
<p>While there are some API differences, and the implementation has some differences in behavior, it is essentially meant as an eventual drop-in replacement for <a href="https://github.com/git/git/blob/17e5574b0446836af08136ae269b30767c05b1d7/merge-recursive.c" rel="noreferrer"><code>merge-recursive.c</code></a>.</p>
<p>However, it is being built to exist side-by-side with merge-recursive so that we have plenty of time to find out how those differences pan out in the real world while people can still fall back to merge-recursive.<br />
(Also, I intend to avoid modifying merge-recursive during this process, to keep it stable.)</p>
<p>The primary difference noticable here is that the updating of the working tree and index is not done simultaneously with the merge algorithm, but is a separate post-processing step.<br />
The new API is designed so that one can do repeated merges (e.g. during a rebase or cherry-pick) and only update the index and working tree one time at the end instead of updating it with every intermediate result.</p>
<p>Also, one can perform a merge between two branches, neither of which match the index or the working tree, without clobbering the index or working tree.</p>
</blockquote>
<p>And:</p>
<p>See <a href="https://github.com/git/git/commit/848a856b136c6aaeb2b7944add318485c6c6d6ae" rel="noreferrer">commit 848a856</a>, <a href="https://github.com/git/git/commit/fd15863ec8a90a4c2b4429f5f5de370c8599e700" rel="noreferrer">commit fd15863</a>, <a href="https://github.com/git/git/commit/23bef2e33c3290ae308c2ce37e290a25eb5b97bc" rel="noreferrer">commit 23bef2e</a>, <a href="https://github.com/git/git/commit/c8c35f6a02f3841d4383a5ce4c9d8e426776d151" rel="noreferrer">commit c8c35f6</a>, <a href="https://github.com/git/git/commit/c12d1f2ac227cbec44be27de83ef07d135f243c2" rel="noreferrer">commit c12d1f2</a>, <a href="https://github.com/git/git/commit/727c75b23f25f752810f412e936d420f5c7fee04" rel="noreferrer">commit 727c75b</a>, <a href="https://github.com/git/git/commit/489c85ff43b292cc22ae2e003fad74c75f7ae190" rel="noreferrer">commit 489c85f</a>, <a href="https://github.com/git/git/commit/ef527787089ce9a5c137ffde24701dfb7fda841c" rel="noreferrer">commit ef52778</a>, <a href="https://github.com/git/git/commit/f06481f12732e846c0572a0109e2c5b5684f508a" rel="noreferrer">commit f06481f</a> (26 Oct 2020) by <a href="https://github.com/newren" rel="noreferrer">Elijah Newren (<code>newren</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/66c62eaec66bb585caabf560a5e1e49cd64e7a1f" rel="noreferrer">commit 66c62ea</a>, 18 Nov 2020)</sup></p>
<blockquote>
<h2><a href="https://github.com/git/git/commit/23bef2e33c3290ae308c2ce37e290a25eb5b97bc" rel="noreferrer"><code>t6423, t6436</code></a>: note improved ort handling with dirty files</h2>
<p><sup>Signed-off-by: Elijah Newren</sup></p>
</blockquote>
<blockquote>
<p>The "recursive" backend relies on <code>unpack_trees()</code> to check if unstaged changes would be overwritten by a merge, but <code>unpack_trees()</code> does not understand renames -- and once it returns, it has already written many updates to the working tree and index.<br />
As such, "recursive" had to do a special 4-way merge where it would need to also treat the working copy as an extra source of differences that we had to carefully avoid overwriting and resulting in moving files to new locations to avoid conflicts.</p>
<p><strong>The "ort" backend, by contrast, does the complete merge inmemory, and only updates the index and working copy as a post-processing step</strong>.<br />
If there are dirty files in the way, it can simply abort the merge.</p>
</blockquote>
<blockquote>
<h2><a href="https://github.com/git/git/commit/c12d1f2ac227cbec44be27de83ef07d135f243c2" rel="noreferrer"><code>t6423</code></a>: expect improved conflict markers labels in the ort backend</h2>
<p><sup>Signed-off-by: Elijah Newren</sup></p>
</blockquote>
<blockquote>
<p>Conflict markers carry an extra annotation of the form
REF-OR-COMMIT:FILENAME
to help distinguish where the content is coming from, with the <code>:FILENAME</code> piece being left off if it is the same for both sides of history (thus only renames with content conflicts carry that part of the annotation).</p>
<p>However, there were cases where the <code>:FILENAME</code> annotation was accidentally left off, due to merge-recursive's every-codepath-needs-a-copy-of-all-special-case-code format.</p>
</blockquote>
<blockquote>
<h2><a href="https://github.com/git/git/commit/727c75b23f25f752810f412e936d420f5c7fee04" rel="noreferrer"><code>t6404, t6423</code></a>: expect improved rename/delete handling in ort backend</h2>
<p><sup>Signed-off-by: Elijah Newren</sup></p>
</blockquote>
<blockquote>
<p>When a file is renamed and has content conflicts, merge-recursive does not have some stages for the old filename and some stages for the new filename in the index; instead it copies all the stages corresponding to the old filename over to the corresponding locations for the new filename, so that there are three higher order stages all corresponding to the new filename.</p>
<p>Doing things this way makes it easier for the user to access the different versions and to resolve the conflict (no need to manually '<a href="https://github.com/git/git/blob/727c75b23f25f752810f412e936d420f5c7fee04/Documentation/git-rm.txt" rel="noreferrer"><code>git rm</code></a> '<sup>(<a href="https://git-scm.com/docs/git-rm" rel="noreferrer">man</a>)</sup> the old version as well as '<a href="https://github.com/git/git/blob/727c75b23f25f752810f412e936d420f5c7fee04/Documentation/git-add.txt" rel="noreferrer"><code>git add</code></a>'<sup>(<a href="https://git-scm.com/docs/git-add" rel="noreferrer">man</a>)</sup> the new one).</p>
<p>rename/deletes should be handled similarly -- there should be two stages for the renamed file rather than just one.<br />
We do not want to destabilize merge-recursive right now, so instead update relevant tests to have different expectations depending on whether the "<code>recursive</code>" or "<code>ort</code>" merge strategies are in use.</p>
</blockquote>
<hr />
<p>With Git 2.30 (Q1 2021), Preparation for a new merge strategy.</p>
<p>See <a href="https://github.com/git/git/commit/848a856b136c6aaeb2b7944add318485c6c6d6ae" rel="noreferrer">commit 848a856</a>, <a href="https://github.com/git/git/commit/fd15863ec8a90a4c2b4429f5f5de370c8599e700" rel="noreferrer">commit fd15863</a>, <a href="https://github.com/git/git/commit/23bef2e33c3290ae308c2ce37e290a25eb5b97bc" rel="noreferrer">commit 23bef2e</a>, <a href="https://github.com/git/git/commit/c8c35f6a02f3841d4383a5ce4c9d8e426776d151" rel="noreferrer">commit c8c35f6</a>, <a href="https://github.com/git/git/commit/c12d1f2ac227cbec44be27de83ef07d135f243c2" rel="noreferrer">commit c12d1f2</a>, <a href="https://github.com/git/git/commit/727c75b23f25f752810f412e936d420f5c7fee04" rel="noreferrer">commit 727c75b</a>, <a href="https://github.com/git/git/commit/489c85ff43b292cc22ae2e003fad74c75f7ae190" rel="noreferrer">commit 489c85f</a>, <a href="https://github.com/git/git/commit/ef527787089ce9a5c137ffde24701dfb7fda841c" rel="noreferrer">commit ef52778</a>, <a href="https://github.com/git/git/commit/f06481f12732e846c0572a0109e2c5b5684f508a" rel="noreferrer">commit f06481f</a> (26 Oct 2020) by <a href="https://github.com/newren" rel="noreferrer">Elijah Newren (<code>newren</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/66c62eaec66bb585caabf560a5e1e49cd64e7a1f" rel="noreferrer">commit 66c62ea</a>, 18 Nov 2020)</sup></p>
<blockquote>
<h2><a href="https://github.com/git/git/commit/ef527787089ce9a5c137ffde24701dfb7fda841c" rel="noreferrer"><code>merge tests</code></a>: expect improved directory/file conflict handling in ort</h2>
<p><sup>Signed-off-by: Elijah Newren</sup></p>
</blockquote>
<blockquote>
<p><a href="https://github.com/git/git/blob/ef527787089ce9a5c137ffde24701dfb7fda841c/merge-recursive.c" rel="noreferrer"><code>merge-recursive.c</code></a> is built on the idea of running <code>unpack_trees()</code> and then "doing minor touch-ups" to get the result.<br />
Unfortunately, <code>unpack_trees()</code> was run in an update-as-it-goes mode, leading <a href="https://github.com/git/git/blob/ef527787089ce9a5c137ffde24701dfb7fda841c/merge-recursive.c" rel="noreferrer"><code>merge-recursive.c</code></a> to follow suit and end up with an immediate evaluation and fix-it-up-as-you-go design.</p>
<p>Some things like directory/file conflicts are not well representable in the index data structure, and required special extra code to handle.<br />
But then when it was discovered that rename/delete conflicts could also be involved in directory/file conflicts, the special directory/file conflict handling code had to be copied to the rename/delete codepath.<br />
...and then it had to be copied for modify/delete, and for rename/rename(1to2) conflicts, ...and yet it still missed some.<br />
Further, when it was discovered that there were also file/submodule conflicts and submodule/directory conflicts, we needed to copy the special submodule handling code to all the special cases throughout the codebase.</p>
<p>And then it was discovered that our handling of directory/file conflicts was suboptimal because it would create untracked files to store the contents of the conflicting file, which would not be cleaned up if someone were to run a '<a href="https://github.com/git/git/blob/ef527787089ce9a5c137ffde24701dfb7fda841c/Documentation/git-merge.txt#L95" rel="noreferrer"><code>git merge --abort</code></a>'<sup>(<a href="https://git-scm.com/docs/git-merge#Documentation/git-merge.txt---abort" rel="noreferrer">man</a>)</sup> or '<a href="https://github.com/git/git/blob/ef527787089ce9a5c137ffde24701dfb7fda841c/Documentation/git-rebase.txt#L250" rel="noreferrer"><code>git rebase --abort</code></a>'<sup>(<a href="https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---abort" rel="noreferrer">man</a>)</sup>.</p>
<p>It was also difficult or scary to try to add or remove the index entries corresponding to these files given the directory/file conflict in the index.<br />
But changing <a href="https://github.com/git/git/blob/ef527787089ce9a5c137ffde24701dfb7fda841c/merge-recursive.c" rel="noreferrer"><code>merge-recursive.c</code></a> to handle these correctly was a royal pain because there were so many sites in the code with similar but not identical code for handling directory/file/submodule conflicts that would all need to be updated.</p>
<p>I have worked hard to push all directory/file/submodule conflict handling in merge-ort through a single codepath, and avoid creating untracked files for storing tracked content (it does record things at alternate paths, but makes sure they have higher-order stages in the index).</p>
</blockquote>
<hr />
<p>With Git 2.31 (Q1 2021), the merge backend "done right" starts to emerge.<br />
Example:</p>
<p>See <a href="https://github.com/git/git/commit/6d37ca21651408b6d29b86a67d0179eb98629fd8" rel="noreferrer">commit 6d37ca2</a> (11 Nov 2020) by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano (<code>gitster</code>)</a>.<br />
See <a href="https://github.com/git/git/commit/89422d29b1d63004683aaa6d11faa65ba734d46f" rel="noreferrer">commit 89422d2</a>, <a href="https://github.com/git/git/commit/ef2b369387004f4f11497a55174d0d9859549054" rel="noreferrer">commit ef2b369</a>, <a href="https://github.com/git/git/commit/70912f66de751b2f1af145887dc64c9c0d06de36" rel="noreferrer">commit 70912f6</a>, <a href="https://github.com/git/git/commit/6681ce5cf6a869aa73cfe56d041dce133262587a" rel="noreferrer">commit 6681ce5</a>, <a href="https://github.com/git/git/commit/9fefce68dc85d96781090f86c067d83f7c50b617" rel="noreferrer">commit 9fefce6</a>, <a href="https://github.com/git/git/commit/bb470f4e13e90889030d48f618ded5c0961943a3" rel="noreferrer">commit bb470f4</a>, <a href="https://github.com/git/git/commit/ee4012dcf962fa26ae83d1e7ff28263b9d2d1452" rel="noreferrer">commit ee4012d</a>, <a href="https://github.com/git/git/commit/a9945bba600914bc8feb7aa52dce7b8e41237649" rel="noreferrer">commit a9945bb</a>, <a href="https://github.com/git/git/commit/8adffaa818d17595b23959e995ad395c8cd0b0be" rel="noreferrer">commit 8adffaa</a>, <a href="https://github.com/git/git/commit/6a02dd90c99c59eada5e5b80e7140e56c1d4a2b0" rel="noreferrer">commit 6a02dd9</a>, <a href="https://github.com/git/git/commit/291f29caf6b045576f9953f0ea41fc8367966750" rel="noreferrer">commit 291f29c</a>, <a href="https://github.com/git/git/commit/98bf98416726430b6cbc8670725f008588e478a7" rel="noreferrer">commit 98bf984</a>, <a href="https://github.com/git/git/commit/34e557af5469299453f63d3594d5b392a09937d1" rel="noreferrer">commit 34e557a</a>, <a href="https://github.com/git/git/commit/885f0063e9962068d381ca5256ca49070bb2480c" rel="noreferrer">commit 885f006</a>, <a href="https://github.com/git/git/commit/d2bc1994f363ac2049da0cdd0b8a7bed61eeaab0" rel="noreferrer">commit d2bc199</a>, <a href="https://github.com/git/git/commit/0c0d705b5cba39c70b01b8b21e2c4d3ca014daf3" rel="noreferrer">commit 0c0d705</a>, <a href="https://github.com/git/git/commit/c8017176ac8fb5cc85ca8742bbdeec8943427340" rel="noreferrer">commit c801717</a>, <a href="https://github.com/git/git/commit/e4171b1b6d32a147638f52c3199477d3ea161b3e" rel="noreferrer">commit e4171b1</a>, <a href="https://github.com/git/git/commit/231e2dd49d11c1ea5d19956920651bd3a90ccfce" rel="noreferrer">commit 231e2dd</a>, <a href="https://github.com/git/git/commit/5b59c3db059d85306ebeb680c4d322a69ee29fde" rel="noreferrer">commit 5b59c3d</a> (13 Dec 2020) by <a href="https://github.com/newren" rel="noreferrer">Elijah Newren (<code>newren</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/f9d29daba64ae2c81ed62d0c1f4c5e4493247f6b" rel="noreferrer">commit f9d29da</a>, 06 Jan 2021)</sup></p>
<blockquote>
<h2><a href="https://github.com/git/git/commit/ef2b369387004f4f11497a55174d0d9859549054" rel="noreferrer"><code>merge-ort</code></a>: add implementation of <code>record_conflicted_index_entries()</code></h2>
<p><sup>Signed-off-by: Elijah Newren</sup></p>
</blockquote>
<blockquote>
<p>After <code>checkout()</code>, the working tree has the appropriate contents, and the index matches the working copy.<br />
That means that all unmodified and cleanly merged files have correct index entries, but conflicted entries need to be updated.</p>
<p>We do this by looping over the conflicted entries, marking the existing index entry for the path with <code>CE_REMOVE</code>, adding new higher order staged for the path at the end of the index (ignoring normal index sort order), and then at the end of the loop removing the <code>CE_REMOVED-marked</code> cache entries and sorting the index.</p>
</blockquote>
<hr />
<p>With Git 2.31 (Q1 2021), rename detection is added to the "ORT" merge strategy.</p>
<p>See <a href="https://github.com/git/git/commit/6fcccbd75556d1dcc80493f6eb51109f53a5dc83" rel="noreferrer">commit 6fcccbd</a>, <a href="https://github.com/git/git/commit/f1665e69188f54c941f9bf10ed388a72a91cc2a1" rel="noreferrer">commit f1665e6</a>, <a href="https://github.com/git/git/commit/35e47e3514b5129e6075a67fa9f4659da2f1a1a1" rel="noreferrer">commit 35e47e3</a>, <a href="https://github.com/git/git/commit/2e91ddd24e7240460fd2a9aee1962345ed858b6b" rel="noreferrer">commit 2e91ddd</a>, <a href="https://github.com/git/git/commit/53e88a03539db70a7e990489784400b0b2916fa9" rel="noreferrer">commit 53e88a0</a>, <a href="https://github.com/git/git/commit/af1e56c49e61a39d5a7d78cecb97f350b5a3834a" rel="noreferrer">commit af1e56c</a> (15 Dec 2020), and <a href="https://github.com/git/git/commit/c2d267df0215d49f06638463889465389134021a" rel="noreferrer">commit c2d267d</a>, <a href="https://github.com/git/git/commit/965a7bc21c6bb11fb15eb798fd472ec9deb5e3fa" rel="noreferrer">commit 965a7bc</a>, <a href="https://github.com/git/git/commit/f39d05ca2637dfcbf0498824d06e7854427936a5" rel="noreferrer">commit f39d05c</a>, <a href="https://github.com/git/git/commit/e1a124e8dc3d21afedc80cc2842d705c1d5a90c9" rel="noreferrer">commit e1a124e</a>, <a href="https://github.com/git/git/commit/864075ec433644e5908589fe79f8b3296f896867" rel="noreferrer">commit 864075e</a> (14 Dec 2020) by <a href="https://github.com/newren" rel="noreferrer">Elijah Newren (<code>newren</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/2856089e367cc126f70d0a3d6d6ff5290d204f2e" rel="noreferrer">commit 2856089</a>, 25 Jan 2021)</sup></p>
<p>Example:</p>
<blockquote>
<h2><a href="https://github.com/git/git/commit/f1665e69188f54c941f9bf10ed388a72a91cc2a1" rel="noreferrer"><code>merge-ort</code></a>: add implementation of normal rename handling</h2>
<p><sup>Signed-off-by: Elijah Newren</sup></p>
</blockquote>
<blockquote>
<p>Implement handling of normal renames.<br />
This code replaces the following from <code>merge-recurisve.c</code>:</p>
<ul>
<li>the code relevant to <code>RENAME_NORMAL</code> in <code>process_renames()</code></li>
<li>the <code>RENAME_NORMAL</code> case of <code>process_entry()</code></li>
</ul>
<p>Also, there is some shared code from <a href="https://github.com/git/git/blob/f1665e69188f54c941f9bf10ed388a72a91cc2a1/merge-recursive.c" rel="noreferrer"><code>merge-recursive.c</code></a> for multiple different rename cases which we will no longer need for this case (or other rename cases):</p>
<ul>
<li><code>handle_rename_normal()</code></li>
<li><code>setup_rename_conflict_info()</code></li>
</ul>
<p>The consolidation of four separate codepaths into one is made possible by a change in design: <code>process_renames()</code> tweaks the <code>conflict_info</code> entries within <code>opt->priv->paths</code> such that <code>process_entry()</code> can then handle all the non-rename conflict types (directory/file, modify/delete, etc.) orthogonally.</p>
<p>This means we're much less likely to miss special implementation of some kind of combination of conflict types (see commits brought in by <a href="https://github.com/git/git/commit/66c62eaec66bb585caabf560a5e1e49cd64e7a1f" rel="noreferrer">66c62ea</a> ("Merge branch 'en/merge-tests'", 2020-11-18, Git v2.30.0-rc0 -- <a href="https://github.com/git/git/commit/66c62eaec66bb585caabf560a5e1e49cd64e7a1f" rel="noreferrer">merge</a> listed in <a href="https://github.com/git/git/commit/faefdd61ec7c7f6f3c8c9907891465ac9a2a1475" rel="noreferrer">batch #6</a>), especially <a href="https://github.com/git/git/commit/ef527787089ce9a5c137ffde24701dfb7fda841c" rel="noreferrer">commit ef52778</a> ("merge tests: expect improved directory/file conflict handling in ort", 2020-10-26, Git v2.30.0-rc0 -- <a href="https://github.com/git/git/commit/66c62eaec66bb585caabf560a5e1e49cd64e7a1f" rel="noreferrer">merge</a> listed in <a href="https://github.com/git/git/commit/faefdd61ec7c7f6f3c8c9907891465ac9a2a1475" rel="noreferrer">batch #6</a>) for more details).</p>
<p>That, together with letting worktree/index updating be handled orthogonally in the <code>merge_switch_to_result()</code> function, dramatically simplifies the code for various special rename cases.</p>
<p>(To be fair, the code for handling normal renames wasn't all that complicated beforehand, but it's still much simpler now.)</p>
</blockquote>
<p>And, still with Git 2.31 (Q1 2021), With Git 2.31 (Q1 2021), oRT merge strategy learns more support for merge conflicts.</p>
<p>See <a href="https://github.com/git/git/commit/4ef88fc3a8d402de272c6bfa36538bd8e4cdd439" rel="noreferrer">commit 4ef88fc</a>, <a href="https://github.com/git/git/commit/4204cd591b62f3e184f617d01b282b9847298dbd" rel="noreferrer">commit 4204cd5</a>, <a href="https://github.com/git/git/commit/70f19c7fced2ec49fd9bca827370835d84d782c7" rel="noreferrer">commit 70f19c7</a>, <a href="https://github.com/git/git/commit/c73cda76b104795d1455ecbf031a18045ab37a84" rel="noreferrer">commit c73cda7</a>, <a href="https://github.com/git/git/commit/f591c4724615b2fc1e4dc3d6bfe5da96a88eacbe" rel="noreferrer">commit f591c47</a>, <a href="https://github.com/git/git/commit/62fdec17a111e419b750938d24b6d65e3076b76d" rel="noreferrer">commit 62fdec1</a>, <a href="https://github.com/git/git/commit/991bbdcab94d93c2a325c4ce74cff139f0f49d97" rel="noreferrer">commit 991bbdc</a>, <a href="https://github.com/git/git/commit/5a1a1e8ea9fdd4a575c711b91f176838ea502e44" rel="noreferrer">commit 5a1a1e8</a>, <a href="https://github.com/git/git/commit/23366d2aa97544fe76bc86964f4493b7b89e7b22" rel="noreferrer">commit 23366d2</a>, <a href="https://github.com/git/git/commit/0ccfa4e5d8489abe7c5d3fe29b68e4fe0cae6fe1" rel="noreferrer">commit 0ccfa4e</a> (01 Jan 2021) by <a href="https://github.com/newren" rel="noreferrer">Elijah Newren (<code>newren</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/b65b9ff1ff8a809246cc6bd8ad9051b28e5bf330" rel="noreferrer">commit b65b9ff</a>, 05 Feb 2021)</sup></p>
<blockquote>
<h2><a href="https://github.com/git/git/commit/4ef88fc3a8d402de272c6bfa36538bd8e4cdd439" rel="noreferrer"><code>merge-ort</code></a>: add handling for different types of files at same path</h2>
<p><sup>Signed-off-by: Elijah Newren</sup></p>
</blockquote>
<blockquote>
<p>Add some handling that explicitly considers collisions of the following types:</p>
<ul>
<li>file/submodule</li>
<li>file/symlink</li>
<li>submodule/symlink> Leaving them as conflicts at the same path are hard for users to resolve, so move one or both of them aside so that they each get their own path.</li>
</ul>
<p>Note that in the case of recursive handling (i.e.<br />
<code>call_depth > 0</code>), we can just use the merge base of the two merge bases as the merge result much like we do with modify/delete conflicts, binary files, conflicting submodule values, and so on.</p>
</blockquote>
| 47,882 |
<p>I have just converted a project from Visual Studio 2003 to 2005 and although most of it 'converted' fine, I have a series of STL errors from the following line:</p>
<pre><code>void SomeFn( std::vector<CSomeObject*>::iterator it,
std::vector<CSomeObject*>::iterator itBegin = NULL,
std::vector<CSomeObject*>::iterator itEnd = NULL );
</code></pre>
<p>The Visual Studio error is as follows:</p>
<pre><code>c:\<path>\Headerfile.h(20) : error C2440: 'default argument' : cannot convert from 'int' to 'std::_Vector_iterator<_Ty,_Alloc>'
with
[
_Ty=CObject *,
_Alloc=std::allocator<CObject *>
]
No constructor could take the source type, or constructor overload resolution was ambiguous
</code></pre>
<p>I can't see anything wrong with that code and it worked perfectly in VS 2003. Any ideas?</p>
| <p>Your program is incorrect as NULL cannot be converted as an iterator. I don't really know what you want these iterators to be initialized as. If you need an iterator guarantied not to be in a container but to be still "valid", you can use a default-constructor:</p>
<pre><code>typedef std::vector<CSomeObject*> myvector_t;
void SomeFn( myvector_t::iterator it,
myvector_t::iterator itBegin = myvector_t::iterator(),
myvector_t::iterator itEnd = myvector_t::iterator() );
</code></pre>
<p>Note, however, that if you do so, <code>it</code>, <code>itBegin</code> and <code>itEnd</code> won't be comparable in a meaningful way! Only iterators obtained from a given container are comparable meaningfully. In the end, I would recommend against using defaults values for <code>itBegin</code> and <code>itEnd</code>. If you really need to not have these, create another function without the arguments and do something meaningful. i.e.:</p>
<pre><code>typedef std::vector<CSomeObject*> myvector_t;
void SomeFn( myvector_t::iterator it,
myvector_t::iterator itBegin,
myvector_t::iterator itEnd );
void SomeFn( myvector_t::iterator it ); // No begin/end arguments
</code></pre>
<p>Another problem of your program is the use of a vector to store pointers. This is really unsafe. Make sure you never erase elements from the vector without deleting the element first. You might also have problems with algorithms copying objects around. It is better to use smart pointers in vectors.</p>
| <p>In 2003, <code>std::vector<T>::iterator</code> is just <code>T *</code>. In 2005, at least in debug mode, it is a class, and hence you can't use <code>NULL</code> for its value (<code>NULL</code> resolves to <code>0</code>).</p>
<p>You can use a default-constructed iterator instead:</p>
<pre><code>std::vector<CSomeObject*>::iterator itBegin = std::vector<CSomeObject*>::iterator()
</code></pre>
| 35,969 |
<p>I'm trying to get the start element and the end element of a selection and the offset of the selection in each, i do this in firefox as follows:</p>
<pre><code>var delselection = window.getSelection();
var startOffset = delselection.anchorOffset;
var endOffset = delselection.focusOffset;
var startNode = delselection.anchorNode.parentNode;
var endNode = delselection.focusNode.parentNode;
</code></pre>
<p>However i have no idea how to do this in IE6, anyone able to point me in the right direction?</p>
| <p>document.selection.</p>
<p>However the TextRange object returned by IE does not match Firefox/WebKit/W3's, and determining the exact positions of the start and end points is very frustrating. Depending on what exactly you are doing with the range you may be able to get somewhere with range.parentElement(), range.inRange() or range.compareEndPoints(). For rich text editors you will usually end up using the staggeringly ugly range.execCommand() interface.</p>
<p>The IE Range implementation is so odd and different to the Mozilla/Webkit/W3 model that you typically end up with completely different code paths for everything to do with selections between the two.</p>
| <p>You should look at the <a href="http://msdn.microsoft.com/en-us/library/ms537447(VS.85).aspx#" rel="nofollow noreferrer">ControlRange</a> and <a href="http://msdn.microsoft.com/en-us/library/ms535872(VS.85).aspx" rel="nofollow noreferrer">TextRange</a> objects of the IE BOM.</p>
<p>AnchorOffset,focusOffset and window.getSelection() are not supported by IE6/7 I believe.</p>
| 26,817 |
<p>I just read a post mentioning "full text search" in SQL. </p>
<p>I was just wondering what the difference between FTS and LIKE are. I did read a couple of articles but couldn't find anything that explained it well.</p>
| <p>In general, there is a tradeoff between "precision" and "recall". High precision means that fewer irrelevant results are presented (no false positives), while high recall means that fewer relevant results are missing (no false negatives). Using the LIKE operator gives you 100% precision with no concessions for recall. A full text search facility gives you a lot of flexibility to tune down the precision for better recall.</p>
<p>Most full text search implementations use an "inverted index". This is an index where the keys are individual terms, and the associated values are sets of records that contain the term. Full text search is optimized to compute the intersection, union, etc. of these record sets, and usually provides a ranking algorithm to quantify how strongly a given record matches search keywords.</p>
<p>The SQL LIKE operator can be extremely inefficient. If you apply it to an un-indexed column, a full scan will be used to find matches (just like any query on an un-indexed field). If the column is indexed, matching can be performed against index keys, but with far less efficiency than most index lookups. In the worst case, the LIKE pattern will have leading wildcards that require every index key to be examined. In contrast, many information retrieval systems can enable support for leading wildcards by pre-compiling suffix trees in selected fields.</p>
<p>Other features typical of full-text search are </p>
<ul>
<li>lexical analysis or tokenization—breaking a
block of unstructured text into
individual words, phrases, and
special tokens</li>
<li>morphological
analysis, or stemming—collapsing variations
of a given word into one index term;
for example, treating "mice" and
"mouse", or "electrification" and
"electric" as the same word</li>
<li>ranking—measuring the
similarity of a matching record to
the query string</li>
</ul>
| <p>FTS is more efficient, powerful (especially for Word Breakers and stemming functionalities)
... but check your requirements because sometimes DBs don't support all languages for example MSSQL doesn't support Greek (check on this page <a href="http://msdn.microsoft.com/en-us/library/ms176076%28v=sql.110%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms176076(v=sql.110).aspx</a> ) </p>
| 27,773 |
<p>is it possible to extend vim functionality via custom extension (preferably, written in Python)?</p>
<p>What I need ideally is custom command when in command mode. E.g.</p>
<p>ESC</p>
<p>:do_this</p>
<p>:do_that</p>
| <p>vim supports scripting in python (and in perl as well, I think).</p>
<p>You just have to make sure that the vim distribution you are using has been compiled with python support.</p>
<p>If you are using a Linux system, you can download the source and then compile it with</p>
<pre><code>./configure --enable-pythoninterp
make
sudo make install
</code></pre>
<p>Inside vim, you can type</p>
<pre><code>:version
</code></pre>
<p>to list the available features; if it has python support, you should see a '+python' somewhere (a '-python' otherwise).</p>
<p>Then, to check the usage of the python module, you can type</p>
<pre><code>:help python
</code></pre>
<p>P.S: if you're going to compile the vim sources, make sure to check the available configure options, you might need to specify --with-python-config-dir as well.</p>
<p>P.P.S: to create a "custom command in command mode" (if I understand correctly what you mean), you can create a function "MyFunction" in a vim script (using python or the vim scripting language) and then invoke it with </p>
<pre><code>:Call MyFunction()
</code></pre>
<p>Check </p>
<pre><code>:help user-functions
</code></pre>
<p>for details</p>
| <p>Had a problems to compile Vim with Python. </p>
<blockquote>
<p>...checking if compile and link flags for Python are sane... no: PYTHON DISABLED" in the ./configure output.</p>
</blockquote>
<p>On Ubuntu 10.04 you have to install <code>python2.6-dev</code>. The flags for <code>./configure</code> are:</p>
<pre><code>--enable-pythoninterp
--with-python-config-dir=/usr/lib/python2.6/config
</code></pre>
<p>Make sure you got a path to directory, which contains <code>config.c</code> file. Also no <code>/</code> at the end of the path! That caused me problems.</p>
| 16,797 |
<p>I'm looking for an easiest way how to implement the "suggest" feature for a text entry field in a Rails application. The idea is to complete names stored in a database column, giving the user a drop-down menu of possible matches as he types.</p>
<p>Thanks for any suggestions!</p>
| <p>Ruby on Rails has the <a href="http://www.prototypejs.org" rel="noreferrer">Prototype framework</a> available. This framework is used by <a href="http://script.aculo.us/" rel="noreferrer">Script.aculo.us</a> and it provides an <a href="http://demo.script.aculo.us/ajax/autocompleter" rel="noreferrer">autocompleter control</a> that may provide the functionality that you're seeking.</p>
| <p>EDIT: I'll leave this answer here as a sort of theoretical reference point, but it sounds like the <a href="https://stackoverflow.com/questions/194450/suggest-feature-for-textboxes-in-a-rails-app#194453">autocompleter answer</a> is likely to be more useful to you :)</p>
<p>Disclaimer: Although I work for Google (which clearly has "Suggest" elements in various UIs) I haven't looked at any of the code around this area, nor even spoken to anyone about the client-side aspect.</p>
<p>The server-side language is probably irrelevant here. The important bit is the AJAX required on the client side.</p>
<p>I suggest you have a timer of about 1 second (experiment to find a sweet spot) which is reset each time the user enters a keystroke into the textbox and cancelled if the user navigates away from the textbox. If the timer fires, make it fire an AJAX request. The AJAX request would contain what the user has typed so far. The AJAX response should be the list of suggestions and the original request text.</p>
<p>If, when the AJAX response returns, the text in the textbox is still the same as the field in the response (i.e. the user hasn't typed since) and if the textbox still has focus, then offer a dropdown. (There must be hundreds of example pages about HTML comboboxes to do this side of things.)</p>
<p>All the server needs to do is respond to the AJAX request by performing the search and formatting the response appropriately - that's a lot easier than the client side!</p>
<p>Hope that helps - sorry to not have any sample code, but I suspect it's quite involved and I'm not really a JavaScript developer.</p>
| 23,627 |
<p>I have the following code:</p>
<pre><code>using System;
using System.Linq;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
Descendant d = new Descendant();
d.TestMethod();
}
}
public class Base
{
protected void FigureItOut<TClass, TMember>(Expression<Func<TClass, TMember>> expr)
{
}
}
public class Descendant : Base
{
public void TestMethod()
{
FigureItOut(c => c.Name);
}
public String Name { get; set; }
}
</code></pre>
<p>I get this compiler error message:</p>
<pre><code>The type arguments for method
'Base.FigureItOut<TClass,TMember>
(System.Linq.Expressions.Expression<System.Func<TClass,TMember>>)'
cannot be inferred from the usage. Try specifying the type arguments explicitly.
</code></pre>
<p>If I change the call to FigureItOut to this:</p>
<pre><code>FigureItOut((Descendant c) => c.Name);
</code></pre>
<p>Then it works. Is there a way to get the first example to compile by changing the base class instead?</p>
<p>I know that if I make the entire Base class generic, like this:</p>
<pre><code>public class Base<TDescendant>
{
protected void FigureItOut<TMember>(Expression<Func<TDescendant, TMember>> expr)
{
}
}
public class Descendant : Base<Descendant>
{
public void TestMethod()
{
FigureItOut(c => c.Name);
}
public String Name { get; set; }
}
</code></pre>
<p>Then it works, but I'd rather not do that, any other hacks that can be employed, perhaps on the method level (ie. change FigureItOut somehow).</p>
| <p>How about an extension method that calls the actual (<code>protected internal</code>) implementation? The only downside is you have to add <code>this.</code>.</p>
<p>This works because the <code>source</code> parameter (via <code>this</code>) infers a type for <code>TClass</code>.</p>
<pre><code>public class Base
{
protected internal void FigureItOut<TClass, TMember>(Expression<Func<TClass, TMember>> expr)
{
Debug.WriteLine("Got to actual method");
}
}
public static class BaseExt
{
public static void FigureItOut<TClass, TMember>(this TClass source, Expression<Func<TClass, TMember>> expr)
where TClass : Base
{ // call the actual method
Debug.WriteLine("Got to extension method");
source.FigureItOut(expr);
}
}
public class Descendant : Base
{
public void TestMethod()
{
this.FigureItOut(c => c.Name);
}
public String Name { get; set; }
}
</code></pre>
<hr>
<p>As an alternative (if the <code>internal</code> is a pain), consider making it static, with an instance argument that is used primarily for type inference:</p>
<pre><code>protected static void FigureItOut<TClass, TMember>(TClass source, Expression<Func<TClass, TMember>> expr)
{
}
public void TestMethod()
{
FigureItOut(this, c => c.Name);
}
</code></pre>
| <p>Unless it takes a parameter, it cant be inferred.
Unless it assigns a return value, it cant be inferred.</p>
| 32,734 |
<p>I have a small diagnostic VB.Net application ( 2 forms, 20 subs & functions) written using VB.Net 2008 that targets Framework 2.0 and higher, but now I realize I need to support Framework 1.1. I'm looking for the most efficient way to accomplish this given these constraints:</p>
<ul>
<li>I don't know which parts of the application are 2.0-specific. </li>
<li>I could reconstruct the forms without too much trouble. </li>
<li>I need to support SharpZipLib</li>
</ul>
<p>My current idea is to find and install VB.Net 2003, copy over my code and iteratively re-create the tool. Are there better options?</p>
| <p>Your app sounds small enough that I would create a fresh project/solution in a separate folder for the 1.1 framework, copy over the necessary files, use the "Add Existing Item" option, and then build. All the problems will bubble up to the surface that way.</p>
<p>A rather "ugly" approach, but it'll show you everything you need to fix up front.</p>
| <p>Probably not. If you don't understand which bits are 2.0-specific, you're probably going to have to go the trial-and-error route. However, you can probably save yourself quite a bit of work if you go looking for generics beforehand. In my experience, those are the most numerous 1.1-incompatible bits that tend to make it into my code.</p>
| 8,956 |
<p>Take this non-compiling code for instance:</p>
<pre><code>public string GetPath(string basefolder, string[] extraFolders)
{
string version = Versioner.GetBuildAndDotNetVersions();
string callingModule = StackCrawler.GetCallingModuleName();
return AppendFolders(basefolder, version, callingModule, extraFolders);
}
private string AppendFolders(params string[] folders)
{
string outstring = folders[0];
for (int i = 1; i < folders.Length; i++)
{
string fixedPath = folders[i][0] == '\\' ? folders[i].Substring(1) : folders[i];
Path.Combine(outstring, fixedPath);
}
return outstring;
}
</code></pre>
<p>This example is a somewhat simplified version of testing code I am using. Please, I am only interested in solutions having directly to do with the param keyword. I know how lists and other similar things work.</p>
<p>Is there a way to "explode" the extraFolders array so that it's contents can be passed into AppendFolders along with other parameters?</p>
| <p>Just pass it. The folders parameter is an array first. the "params" functionality is a little bit of compiler magic, but it's not required.</p>
<pre><code>AppendFolders(extraFolders);
</code></pre>
<p>Now, it this particulat instance, you'll have to add some things to that array, first.</p>
<pre><code>List<string> lstFolders = new List<string>(extraFolders);
lstFolder.Insert(0, callingModule);
lstFolder.Insert(0, version);
lstFolder.Insert(0, basefolder);
return AppendFolders(lstFolders.ToArray());
</code></pre>
| <p>A quick and dirty solution would be to build a List<string> from the items and then pass that (with ToArray()).</p>
<p>Note that you don't need to test for the backslash. Path.Combine handles <a href="https://stackoverflow.com/questions/144439/building-a-directory-string-from-component-parts-in-c">the dirty things rather fine</a>.</p>
| 23,417 |
<p>I have hit a classic problem of needing to do a string replace on a text field in an sql 2000 database. This could either be an update over a whole column or a single field I'm not fussy.</p>
<p>I have found a few examples of how to use updatetext to achieve it but they tend to be in stored procedures, does anyone know of a similar thing that is wrapped into a function so I can use it like I would usually use Replace(). The problem with the Replace() function for anyone who isn't aware is that it doesn't support text fields.</p>
<p>Edit: I realised I could probably get away with varchar(8000) so have swapped the fields to this type which fixes the issue. I never found a true solution.</p>
| <p>Here is the sample query to update table with text column using REPLACE function. Hope this is useful for you.</p>
<pre><code>UPDATE <Table> set textcolumn=
REPLACE(SUBSTRING(textcolumn,1,DATALENGTH(textcolumn)),'findtext','replacetext')
WHERE <Condition>
</code></pre>
| <p>You would have to cast the text field to a varchar(8000) or nvarchar(4000) if you are replacing over an ntext field.</p>
<p>MyField = REPLACE(CAST(MyField as VARCHAR(4000)), "string1", "string2")</p>
<p>This ofcourse will only work if you can guarantee the content in the field is <= 4000/8000 characters in length.</p>
| 36,899 |
<p>I've got this code in a pair of button click event handlers on a C# form:</p>
<pre><code>class frmLogin
{
private const int SHORT_HEIGHT = 120;
private const int LONG_HEIGHT = 220;
private EventHandler ExpandHandler;
private EventHandler ShrinkHandler;
public frmLogin()
{
InitializeComponent();
ExpandHandler = new EventHandler(btnExpand_Click);
ShrinkHandler = new EventHandler(btnShrink_Click);
btnExpand.Click += ExpandHandler;
}
private void btnExpand_Click(object sender, EventArgs e)
{
this.Height = LONG_HEIGHT;
btnExpand.Text = "<< Hide Server";
btnExpand.Click -= ExpandHandler;
btnExpand.Click += ShrinkHandler;
}
private void btnShrink_Click(object sender, EventArgs e)
{
this.Height = SHORT_HEIGHT;
btnExpand.Text = "Choose Server >>";
btnExpand.Click -= ShrinkHandler;
btnExpand.Click += ExpandHandler;
}
}
</code></pre>
<p>The text change occurs without issue, but on one particular client machine, a Dell M4300 laptop workstation, the height change does not take effect. Has anyone resolved a similar issue, and what was the fix if so?</p>
| <p>My guess: The DPI or system font size is different on that machine and your form's AutoScaleMode is either "Font" or "Dpi", making your form's MinimumSize or MaximumSize prevent the change.</p>
| <p>Make sure you do not have one of those AutoScale/Size/Whatever properties set to to true.</p>
| 47,170 |
<p>I recently learnt that oracle has a feature which was pretty useful to me - as the designer/implementator didn't care much about data history - I can query the historical state of a record if it's available yet in the oracle cache, like this:</p>
<pre><code>select *
from ( select *
from sometable where some_condition )
as of timestamp sysdate-1
</code></pre>
<p>But now I need to check the historical data within a range. Is it possible anyhow, using the cache?</p>
| <p>Yes, like this:</p>
<pre><code>SQL> select sal from emp where empno=7369;
SAL
----------
5800
SQL> update emp set sal = sal+100 where empno=7369;
1 row updated.
SQL> commit;
Commit complete.
SQL> update emp set sal = sal-100 where empno=7369;
1 row updated.
SQL> commit;
Commit complete.
SQL> select empno, sal, versions_starttime,versions_xid
2 from emp
3 versions between timestamp sysdate-1 and sysdate
4 where empno=7369;
EMPNO SAL VERSIONS_STARTTIME VERSIONS_XID
---------- ---------- --------------------------------------------------------------------------- --
7369 5900 11-DEC-08 16.05.32 0014001300002A74
7369 5800 11-DEC-08 16.03.32 000D002200012EB1
7369 5800
</code></pre>
<p>Note that how far back you can go is limited by the UNDO_RETENTION parameter, and will typically be hours rather than days.</p>
| <pre><code>SELECT *
FROM sometable
VERSIONS BETWEEN TIMESTAMP systimestamp - 1 AND systimestamp
</code></pre>
<p>will give you all versions of all rows in the last day.</p>
<p>There's lots more you can do with this. Check out the <a href="http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_10002.htm" rel="nofollow noreferrer">documentation</a> (you may want to find the docs for your version).</p>
| 46,931 |
<p>There seems to be three common approaches for mapping an application end user to a database user. </p>
<ol>
<li><strong>One to One Mapping:</strong> Each Application user (bob, nancy and fred) also get a corresponding database user account (bob nancy and fred).</li>
<li><strong>N to M mapping:</strong> Each application user is mapped to a database user that represents their role. bob and nancy are mapped to the 'clerk' database user while fred is mapped to the 'manager' database user.</li>
<li><strong>N to 1 mapping:</strong> Each application user is mapped to a single database user (app_user) and identity is only managed at the application tier.</li>
</ol>
<p>It seems that #3 is the most common in web application development. <strong>Why is there not a greater emphasis on the other two options?</strong></p>
<p>Oracle encourages techniques like #2 using its proxy authentication features for the following reason:</p>
<p><strong>Limited trust model</strong>-controlling the users on whose behalf middle tiers can connect, and the roles the middle tiers can assume for the user</p>
<p><strong>Scalability</strong>-by supporting lightweight user sessions and eliminating the overhead of re-authenticating clients</p>
<p><strong>Accountability</strong>, by preserving the identity of the real user through to the database, and enabling auditing of actions taken on behalf of the real user</p>
<p><a href="http://download.oracle.com/docs/cd/B28359_01/java.111/b31224/proxya.htm" rel="nofollow noreferrer">Oracle's Proxy Authentication documentation</a></p>
| <p>In addition to the simpler administration, there are performance advantages of option 3 on web-servers; this allows pooling of connections - i.e. a low number of physical database connections can be re-used continuously to service a large number of app users. This is known as the "<a href="http://msdn.microsoft.com/en-us/library/aa480587.aspx" rel="nofollow noreferrer">trusted subsystem</a>" model - i.e. your app-server validates external callers, but then the app-server itself is used as the identity for calling downwards. The biggest issue here is that for audit etc you need to keep telling the db who made the current change (things like <code>USER_NAME()</code>, <code>SUSER_SNAME()</code> cease to be useful) - and of course, this is relatively easy to spoof.</p>
<p>If the web-server used security per user, this wouldn't be possible - and so you'd essentially have to disable connection pooling. The act of establishing a connection is (relatively) expensive, so this would have a significant impact on performance. You wouldn't want to keep the (per-user) connection around between requests, as this would lead to a huge pool and a lot of open connections (also expensive).</p>
<p>The "per role" option site between them - but it is rare that roles are truly mutually exclusive, which makes this hard to implement.</p>
<p>With client apps that talk directly to the database, option 1 is the simplest to maintain, since you don't need to distribute any special account details to the client. The pooling likewise isn't an issue, since the client's machine is only acting as 1 user.</p>
| <p>Because the database roles (by object, CRUD, etc.) don't generally apply to usernames unless they are database developers. Both AD and the database have roles, but there is the same mismatch between the two. The only halfway defensible mappings would be for administrator roles, but even that is sloppy.</p>
<p>This issue is a result of a common misapprehension fostered by the term "integrated security", which really only ends up meaning "single-login" (i.e. user verification), and maybe creating yet another fleet of roles and groups within AD so that AD administrators can be assigned the responsibility for database security - not usually something they are well-trained at, although I'm sure there are exceptions.</p>
| 45,179 |
<p>I'm trying to get into java again (it's been a few years). I never really did any GUI coding in java. I've been using Netbeans to get started with this.</p>
<p>When using winforms in C# at work I use a usercontrols to build parts of my UI and add them to forms dynamically. </p>
<p>I've been trying to use <code>JPanels</code> like usercontrols in C#. I created a <code>JPanel</code> form called <code>BlurbEditor</code>. This has a few simple controls on it. I am trying to add it to another panel at run time on a button event. </p>
<p>Here is the code that I thought would work:</p>
<pre><code>mainPanel.add(new BlurbEditor());
mainPanel.revalidate();
//I've also tried all possible combinations of these too
//mainPanel.repaint();
//mainPanel.validate();
</code></pre>
<p>This unfortunately is not working. What am I doing wrong?</p>
| <p>I figured it out. The comments under the accepted answer here explain it:
<a href="https://stackoverflow.com/questions/121715/dynamically-added-jtable-not-displaying">Dynamically added JTable not displaying</a></p>
<p>Basically I just added the following before the mainPanel.add()</p>
<pre><code>mainPanel.setLayout(new java.awt.BorderLayout());
</code></pre>
| <p>Try <code>mainPanel.invalidate()</code> and then if necessary, <code>mainPanel.validate()</code>. It also might be worth checking that you're doing this all in the event dispatch thread, otherwise your results will be spotty and (generally) non-deterministic.</p>
| 20,490 |
<p>What is a free tool to compare two Sql Server tables (data and schema). </p>
<p>It would be great if the tool can script the differences found.</p>
<p>I also went through some older <a href="https://stackoverflow.com/questions/176316/compare-tools-to-generate-update-script-for-sql-server">posts</a>. The closest I have seen is <a href="http://sqldbtools.com/" rel="noreferrer">SQLDBDiff</a> but I would love to try more options.</p>
| <p>TableDiff.exe should have everything you need. It is one of the <a href="http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/gems-top-10.mspx" rel="noreferrer">hidden gems in SQL Server 2005</a>. So you don't have to download anything.</p>
<p>• Table Difference tool allows you to discover and reconcile differences between a source and destination table or a view. Tablediff Utility can report differences on schema and data. The most popular feature of tablediff is the fact that it can generate a script that you can run on the destination that will reconcile differences between the tables. TableDiff.exe takes 2 sets of input;
• Connectivity - Provide source and destination objects and connectivity information. </p>
<p>• Compare Options - Select one of the compare options
• Compare schemas: Regular or Strict</p>
<p>• Compare using Rowcounts, Hashes or Column comparisons</p>
<p>• Generate difference scripts with I/U/D statements to synchronize destination to the source.
TableDiff was intended for replication but can easily apply to any scenario where you need to compare data and schema.
You can find more information about command line utilities and the Tablediff Utility in Books Online for SQL Server 2005.</p>
| <p>A SQL Server specific database table diff tool is <a href="http://www.volpet.com/" rel="nofollow noreferrer">Volpet's Table Diff</a></p>
| 23,510 |
<p>Is there any way to verify in Java code that an e-mail address is valid. By valid, I don't just mean that it's in the correct format ([email protected]), but that's it's a real active e-mail address.</p>
<p>I'm almost certain that there's no 100% reliable way to do this, because such a technique would be the stuff of spammer's dreams. But perhaps there's some technique that gives some useful indication about whether an address is 'real' or not.</p>
| <p>Here is what I have around. To check that the address is a valid format, here is a regex that verifies that it's nearly rfc2822 (it doesn't catch some weird corner cases). I found it on the 'net last year.</p>
<pre><code>private static final Pattern rfc2822 = Pattern.compile(
"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"
);
if (!rfc2822.matcher(email).matches()) {
throw new Exception("Invalid address");
}
</code></pre>
<p>That will take care of simple syntax (for the most part). The other check I know of will let you check if the domain has an MX record. It looks like this:</p>
<pre><code>Hashtable<String, String> env = new Hashtable<String, String>();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext(env);
Attributes attrs = ictx.getAttributes(domainName, new String[] {"MX"});
Attribute attr = attrs.get("MX");
if (attr == null)
// No MX record
else
// If attr.size() > 0, there is an MX record
</code></pre>
<p>This, I also found on the 'net. It came from <a href="http://www.rgagnon.com/javadetails/java-0452.html" rel="noreferrer">this link</a>.</p>
<p>If these both pass, you have a good chance at having a valid address. As for if the address it's self (not just the domain), it's not full, etc... you really can't check that.</p>
<p>Note that the second check is <strong>time intensive</strong>. It can take anywhere from milliseconds to >30 seconds (if the DNS does not respond and times out). It's not something to try and run real-time for large numbers of people.</p>
<p>Hope this helps.</p>
<p><strong>EDIT</strong></p>
<p>I'd like to point out that, at least instead of the regex, there are better ways to check basic validity. Don and Michael point out that Apache Commons has something, and I recently found out you can use .validate() on InternetAddress to have Java check that the address is really RFC-8222, which is certainly more accurate than my regex.</p>
| <p>If you're using GWT, you can't use InternetAddress, and the pattern supplied by MBCook is pretty scary.</p>
<p>Here is a less scary regex (might not be as accurate):</p>
<pre><code>public static boolean isValidEmail(String emailAddress) {
return emailAddress.contains(" ") == false && emailAddress.matches(".+@.+\\.[a-z]+");
}
</code></pre>
| 18,561 |
<p>What is the best way to track changes in a database table?</p>
<p>Imagine you got an application in which users (in the context of the application not DB users ) are able to change data which are store in some database table. What's the best way to track a history of all changes, so that you can show which user at what time change which data how?</p>
| <p>In general, if your application is structured into layers, have the data access tier call a stored procedure on your database server to write a log of the database changes.</p>
<p>In languages that support such a thing <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming" rel="noreferrer">aspect-oriented programming</a> can be a good technique to use for this kind of application. Auditing database table changes is the kind of operation that you'll typically want to log for all operations, so AOP can work very nicely.</p>
<p>Bear in mind that logging database changes will create lots of data and will slow the system down. It may be sensible to use a message-queue solution and a separate database to perform the audit log, depending on the size of the application.</p>
<p>It's also perfectly feasible to use stored procedures to handle this, although there may be a bit of work involved passing user credentials through to the database itself.</p>
| <p>If all changes from php. You may use <a href="https://github.com/moledet/database-change-log" rel="nofollow noreferrer">class</a> to log evry INSERT/UPDATE/DELETE before query. It will be save <strong><em>action</em></strong>, <strong><em>table</em></strong>, <strong><em>column</em></strong>, <strong><em>newValue</em></strong>, <strong><em>oldValue</em></strong>, <strong><em>date</em></strong>, <strong><em>system</em></strong>(if need), <strong><em>ip</em></strong>, <strong><em>UserAgent</em></strong>, <strong><em>clumnReference</em></strong>, <strong><em>operatorReference</em></strong>, <strong><em>valueReference</em></strong>. All tables/columns/actions that need to log are configurable. </p>
| 5,936 |
<p>I would like to apply some logic to a page containing a CheckBoxList control when the user checks or unchecks individual checkbox items. Say, for instance to dynamically show or hide a related control.</p>
<p>I came up with a way using ASP.Net 2.0 callback mechanism (AJAX) with a combination of client-side Javascript and server-side logic in the code-behind. However, this solution is not very bullet-proof (i.e. most likely suffers from timing issues). It is not portable, because the code needs to know the sequential ids of individual items, etc.</p>
<p>The code I came up with is separated in two functions, one handling the <code>onclick</code> event, and the other processing the returned callback string :</p>
<pre><code><script type="text/javascript">
function OnCheckBoxClicked()
{
// gathers the semi-colon separated list of labels,
// associated with the currently checked items
var texts = '';
// iterate over each individual checkbox item
// items in a checkboxlist are sequential, so
// stop iteration at the first missing sequence number
for (var index = 0; index < 99; index++)
{
var checkbox = document.getElementById('ctl00_cphAdmin_cblCategories_' + index);
if (checkbox == null)
break;
if (checkbox.checked)
{
// find label associated with the current checkbox item
var labels = document.getElementsByTagName('label');
for (var index_ = 0; index_ < labels.length; index_ ++)
{
if (labels[index_].htmlFor == checkbox.id)
{
texts = texts + labels[index_].innerHTML + ';';
break;
}
}
}
}
// perform callback request
// result will be processed by the UpdateCheckBoxes function
WebForm_DoCallback('__Page', '_checkbox' + texts, UpdateCheckBoxes, 'checkbox', null, true /* synchronous */);
}
</script>
</code></pre>
<p>In this example, my checkboxes match categories of a blog post.</p>
<p>I need to process the resulting callback string as containing a list of semicolon-separated names of checkboxes to check/uncheck, in order to make sure that related parent/child categories are synchronized correctly. This string results from logic executed on the server.</p>
<p>In other cases, the resulting callback string might be something else.</p>
<pre><code><script type="text/javascript">
function UpdateCheckBoxes(returnmessage, context)
{
if (returnmessage == null || returnmessage == '')
return ;
// iterate over each individual checkbox item
// items in a checkboxlist are sequential, so
// stop iteration at the first missing sequence number
for (var index = 0; index < 99; index++)
{
var checkbox = document.getElementById('ctl00_cphAdmin_cblCategories_' + index);
if (checkbox == null)
break;
// find label associated with the current checkbox item
var label = '';
var labels = document.getElementsByTagName('label');
for (var index_ = 0; index_ < labels.length; index_ ++)
{
if (labels[index_].htmlFor == checkbox.id)
{
label = ';' + labels[index_].innerHTML + ';';
break;
}
}
// perform custom processing based on the contents
// of the returned callback string
// for instance, here we check whether the returnmessage
// contains the string ';' + label + ';'
if (returnmessage.indexOf(label, 1) > 0)
{
// do something
}
}
}
</script>
</code></pre>
<p>Isn't there a more elegant solution to this problem?</p>
| <p>I'd do a couple of things. One, I'd figure out a way to pass the value that needs to be passed back to the client-side onclick handler. Depending on how you are populating your CheckBoxList, this might be as simple as adding an "onclick" attribute to the ListItem for that checkbox that calls your function with the same value assigned to the label, say 'OnCheckBoxClicked(this,'Label'). That would eliminate the need to derive the label, although you could probably do this on the client side as well pretty easily by referencing the previous element of the checkbox if you just passed a reference to it (or parent, maybe, depends on whether the label precedes the input or the input is contained in it).</p>
<p>Two, I would also change it so that it only passes back the current item that is being clicked and handle them one at a time.</p>
<p>Assuming that you checkboxes (when rendered) look something like:</p>
<pre><code> <label for="something">CheckBox 1</label>
<input type='checkbox' id='ctl00_....' value='1' onclick="OnCheckBoxClicked(this,'CheckBox_1');" />
</code></pre>
<p>Your functions might look like:</p>
<pre><code>function OnCheckBoxClicked(checkbox,identifier)
{
// do something based on the checkbox clicked
WebForm_DoCallback('__Page', identifer, UpdateCheckBoxes, {checkbox: checkbox.id, label: identifier } , null, true /* synchronous */);
}
function UpdateCheckBoxes(result,context)
{
var checkbox = document.getElementById(context.checkbox);
var identifier = context.label;
if (result) // AJAX method now returns true/false as context holds info on controls
{
... do something...
}
}
</code></pre>
| <p>you can add an event to the checkbox control on the onclick() event. and send the id of the control as a parameter and then update the attributes of the desired control</p>
<pre><code><input type='checkbox' id='ctl00_....' value='1' onclick="OnCheckBoxClicked('ctrl_toUpdateID');" />
<script type="text/javascript">
function OnCheckBoxClicked(ctrlID)
{
var ctrl = document.getElementById(ctrlID);
if(ctrl.getAttribute('disabled')
ctrl.removeAttribute('disabled')
else
ctrl.setAttribute('disabled','disabled')
}
</script>
</code></pre>
| 28,184 |
<p>I have the need to build lots of sites that are very similar, but not exactly the same, using ASP.NET 2.0.</p>
<p>I'm trying to find the best way to make generating these sites quick and easy.</p>
<p>The sites will be used to collect information about a user, and there will be multiple steps for each site.</p>
<p>The sites will all collect similar information, but some sites may require less or more information than others. Additionally, certain form fields will need to be populated from different database tables, based on the site.</p>
<p>I would like to use a Microsoft patterns & practices solution, but I'm not sure that there is one that fits this scenario.</p>
<p>My current thinking is that I will put as much business logic as possible into an external assembly and then write a custom Web user control for each step for each site. I will include these user controls in a master page's Panel control.</p>
<p>I don't like this solution because each site will be nearly duplicating the code for the other sites.</p>
<p>How can I improve upon this design?</p>
<p>The main obstacle is that the sites are similar, but sufficiently different.</p>
<p>Thanks!</p>
<p>Alex</p>
| <p>you can create base classes which handle all of the common functionality and then have your site specific controls inherit from their respective base classes and then implement their specific implementations.</p>
| <p>Have you looked into Monorail (www.castleproject.org) this is an implementation of themvc pattern, similar to Ruby on rails with a few nice view engines, I prefer Nvelocity.
from castle project as well you can use n implementation of ActiveRecord that makes life real nice. if you are on that trail also have a look at coln ramsay screencasts .</p>
<p>To be honest all ms solutions are real fat
another great thing about the castleproject is that is totally open source so you can learn loads from their code</p>
| 15,714 |
<p>Basically I'm going to go a bit broad here and ask a few questions to get a bit of a picture of how people are handling UI these days.</p>
<p>Lately I've found it pretty easy to do some fancy things with UI design and with WPF specifically we're finding new ways to do layouts that are better looking and more functional for the user, but in contrast one of the business focused guys at our local .NET User Group wouldn't even think of using WPF until it had a datagrid that he could use to make Excel like input forms.</p>
<ol>
<li><p>So basically, have you rethought the design of your business apps as you move to Web/WPF/Silverlight designs, because for us at least - in winforms we kept things fairly functional and uniform, or are you trying to keep that "known" UI?</p></li>
<li><p>Would a dedicated design guy (for larger teams), or a dev with more design chops rank higher when looking at hiring these days? (Check out what a designer did for <a href="http://www.hanselman.com/blog/LearningWPFWithBabySmashManuallyManagingClickOnceAndSomeMoreDesignerGoodness.aspx" rel="nofollow noreferrer">Scott Hanselman's BabySmash</a> and <a href="http://codebetter.com/blogs/glenn.block/archive/2008/05/08/wpf-from-this-to-that-wow.aspx" rel="nofollow noreferrer">Microsoft's Prism demo</a>)</p></li>
<li><p>Are there any design hints/tips/guidelines you use for your UI - especially for WPF?</p></li>
<li><p>What sites would you recommend for design?</p></li>
</ol>
| <p>I recommend that you read <a href="https://rads.stackoverflow.com/amzn/click/com/0789723107" rel="nofollow noreferrer" rel="nofollow noreferrer">Steve Krug's Don't Make Me Think</a> first. The book has a great checklist of things that you have to take into consideration when designing your UIs. While it's focused on web usability, a lot of the lessons therein are valuable even to desktop application designers.</p>
<p>That being said, whether you use Windows forms or WPF or Flash or whatever new and shiny thing that comes around is, it is of utmost importance to hire either a) a real designer, or b) a development guy with a lot of UI design experience, either of which who can provide you a serious URL for their design portfolio. It will help a lot not only in improving the design of your application but also unburdening your developers from thinking about UI design, and allow them to focus on the back-end code.</p>
<p>As for "business focused" guys -- it would be really great if you would get the opinion of actual customers and stake holders, and have them do some usability testing for your application. It's their opinion that would matter most.</p>
<p>I think it would not be difficult to get a good designer up to speed on <a href="http://www.microsoft.com/expression/products/Overview.aspx?key=blend" rel="nofollow noreferrer">Microsoft Expression Blend</a> to whip up some good XAML designs that your team could use to come up with a really good product.</p>
| <p>@David H Aust That's part of the reason for asking the question - with these newer tools like WPF that lend themselves to providing newer, more intricate, and at the same time simpler for the user, interfaces that we might need to adapt to new ways of doing things.</p>
<p>And trying to find out who else is adapting/interested and what they are doing, and where they get some inspiration, knowledge or help :)</p>
<p>IE: This is me being proactive about change in possibly the slackest manner ever, short of actively googling :) </p>
<p>^ That was a joke, to make it clear, I'm actually pretty active about learning new stuff, I'm just finding some of the crowdsourcing stackoverflow vs googling pretty interesting :)</p>
| 6,214 |
<p>Service Oriented Architecture seems to be more and more of a hot quote these days, but after asking around the office I have found that I seem to get many different definitions for it. How would you guys define SOA? What would you consider the official definition?</p>
| <p>As Martin Fowler says, it means different things to different people. His article on the topic is pretty good although it isn't quite a definition.</p>
<p><a href="http://martinfowler.com/bliki/ServiceOrientedAmbiguity.html" rel="noreferrer">http://martinfowler.com/bliki/ServiceOrientedAmbiguity.html</a></p>
<p>It may explain, the difficulty coming up with a concrete definition.</p>
| <p>I attempted to define SOA in <a href="http://vincentfazio.blogspot.com/2008/07/something-old-something-new.html" rel="nofollow noreferrer">one of my blog posts</a>. Here's an excerpt...</p>
<blockquote>
<p>For years it's been standard practice to separate functionality into functions, classes, and modules. The idea has always been that these smaller, highly specialized components are easier to share and maintain than monolithic blocks of code.</p>
<p>Functionally, SOA is not much different. The goals are the same - reusability and easy maintenance. The biggest difference - in the case of a web service SOA - is that the shared library included in your application is replaced with an HTTP call.</p>
</blockquote>
| 8,416 |
<p>I was trying to compile a program using an external compiled object coreset.o. I wrote the public01.c test file and my functions are in computation.c, both of which compiles. However its failing on linking it together. What might be the problem?</p>
<pre><code>gcc -o public01.x public01.o computation.o coreset.o
ld: fatal: file coreset.o: wrong ELF class: ELFCLASS64
ld: fatal: File processing errors. No output written to public01.x
collect2: ld returned 1 exit status
</code></pre>
| <p>I think that coreset.o was compiled for 64-bit, and you are linking it with a 32-bit computation.o.</p>
<p>You can try to recompile computation.c with the '-m64' flag of <a href="http://www.manpagez.com/man/1/gcc-3.3/" rel="noreferrer">gcc(1)</a></p>
| <p>It turns out the compiler version I was using did not match the compiled version done with the coreset.o. </p>
<p>One was 32bit the other was 64bit. I'll leave this up in case anyone else runs into a similar problem.</p>
| 26,551 |
<p>I know that <a href="http://opencv.willowgarage.com/wiki/Mac_OS_X_OpenCV_Port" rel="noreferrer">OpenCV was ported to Mac OS X</a>, however I did not find any info about a port to the iPhone.</p>
<p>I am not a Mac developer, so that I do not know whether a Mac OS X port is enough for the iPhone.</p>
<p>Does anyone know better than me? </p>
| <p>OpenCV does indeed work on the iphone. Use the configure script here to compile the library: <a href="http://lambdajive.wordpress.com/2008/12/20/cross-compiling-for-iphone/" rel="nofollow noreferrer">cross compiling for iphone</a></p>
<p>You just have to cross-compile just as you do your apps.</p>
| <p>Here's modified script (based on the one from LambdaJive) that builds universal OpenCV framework for iPhone/iPhone Simulator - <a href="http://zaaghad.blogspot.com/2009/02/universal-i386arm-opencv-framework-for.html" rel="nofollow noreferrer">universal-i386arm opencv framework</a> </p>
| 45,289 |
<p>I am a newbie to 3D printing and ran into a weird infill line on my second 3D printing object on a new Qidi X-Pro machine (which works great). I've included a screenshot of the infill line, which is deliberately printed the full height of the object. I'm thinking this line has been deliberately inserted by the Qidi slicer for some reason, but I have no idea why. Do all slicers generate these kinds of lines? If so, why?</p>
<p><a href="https://i.stack.imgur.com/s1SAU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s1SAU.jpg" alt="Print object showing extra infill line"></a></p>
| <p>I do not know the Qidi slicer, but if you look closely, you will see this line is thinner than the normal support infill lines. You could try to visualize the G-code in a viewer, usually this can be done in the slicer itself, but <a href="http://gcode.ws/" rel="nofollow noreferrer">online viewers</a> are available. The viewer will not only show the printed lines, but also show moves by the print head (usually in a different color). You can check whether this extra line is actually printed or a move. If it is a move, this extra line is caused by your hotend which is leaking when it moves. You need to properly tune the hotend with respect to the retraction settings and temperature. There are numerous retraction test print objects to find on the internet.</p>
<p>Depending on your slicer settings, some slicers are able to define where each layer starts printing (e.g. random, or start at sharp corner). The fact you see a support structure "printed the full height of the object" tells you that each layer starts at the same position. It is not uncommon in uniform simple parts where each layer starts at the same position (X/Y) as this is instructed by the slicer setting. In Ultimaker Cura such an option is called <code>Z Seam Alignment</code>.</p>
<hr>
<p>Bottom line, all slicers will do this when your printer is improperly tuned (incorrect settings for e.g. print temperature, retraction, coasting, travel speed). It is up to you to find the correct settings, test print objects help you with that.</p>
| <p>Here have a posible solution -> <a href="https://3dprinting.stackexchange.com/questions/6990/how-to-remove-unwanted-filament-trails-from-sharp-corners">How to remove unwanted filament trails from sharp corners</a></p>
<p>I think, that can be a combination of z-hopping and combing-mode in the slicer that you use.</p>
| 1,042 |
<p>How can I get <strong>hierarchy recordset</strong> in ms access through <strong>select</strong> statement?</p>
| <p>You actually want <code>/proc/self/status</code>, which will give you information about the currently executed process.</p>
<p>Here is an example:</p>
<pre><code>$ cat /proc/self/status
Name: cat
State: R (running)
Tgid: 17618
Pid: 17618
PPid: 3083
TracerPid: 0
Uid: 500 500 500 500
Gid: 500 500 500 500
FDSize: 32
Groups: 10 488 500
VmPeak: 4792 kB
VmSize: 4792 kB
VmLck: 0 kB
VmHWM: 432 kB
VmRSS: 432 kB
VmData: 156 kB
VmStk: 84 kB
VmExe: 32 kB
VmLib: 1532 kB
VmPTE: 24 kB
Threads: 1
SigQ: 0/32268
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
Cpus_allowed: 00000003
Mems_allowed: 1
voluntary_ctxt_switches: 0
nonvoluntary_ctxt_switches: 3
</code></pre>
<p>You probably want to look at the first numbers on the Uid and Gid lines. You can look up which uid numbers map to what username by looking at <code>/etc/passwd</code>, or calling the relevant functions for mapping uid to username in whatever language you're using.</p>
<p>Ideally, you would just call the system call <code>getuid()</code> to look up this information, doing it by looking at <code>/proc/</code> is counterproductive.</p>
| <p>The things you are looking for may be in environment variables. You need to be careful about what shell you are using when you check environment variables. bash uses "UID" while tcsh uses "uid" and in <code>*nix</code> case matters. I've also found that tcsh sets "gid" but I wasn't able to find a matching variable in bash.</p>
| 11,522 |
<p>I just played with Java file system API, and came down with the following function, used to copy binary files. The original source came from the Web, but I added try/catch/finally clauses to be sure that, should something wrong happen, the Buffer Streams would be closed (and thus, my OS ressources freed) before quiting the function.</p>
<p>I trimmed down the function to show the pattern:</p>
<pre><code>public static void copyFile(FileOutputStream oDStream, FileInputStream oSStream) throw etc...
{
BufferedInputStream oSBuffer = new BufferedInputStream(oSStream, 4096);
BufferedOutputStream oDBuffer = new BufferedOutputStream(oDStream, 4096);
try
{
try
{
int c;
while((c = oSBuffer.read()) != -1) // could throw a IOException
{
oDBuffer.write(c); // could throw a IOException
}
}
finally
{
oDBuffer.close(); // could throw a IOException
}
}
finally
{
oSBuffer.close(); // could throw a IOException
}
}
</code></pre>
<p>As far as I understand it, I cannot put the two <code>close()</code> in the finally clause because the first <code>close()</code> could well throw, and then, the second would not be executed.</p>
<p>I know C# has the <em>Dispose</em> pattern that would have handled this with the <code>using</code> keyword.</p>
<p>I even know better a C++ code would have been something like (using a Java-like API):</p>
<pre><code>void copyFile(FileOutputStream & oDStream, FileInputStream & oSStream)
{
BufferedInputStream oSBuffer(oSStream, 4096);
BufferedOutputStream oDBuffer(oDStream, 4096);
int c;
while((c = oSBuffer.read()) != -1) // could throw a IOException
{
oDBuffer.write(c); // could throw a IOException
}
// I don't care about resources, as RAII handle them for me
}
</code></pre>
<p>I am missing something, or do I really have to produce ugly and bloated code in Java just to handle exceptions in the <code>close()</code> method of a Buffered Stream?</p>
<p>(Please, tell me I'm wrong somewhere...)</p>
<p><strong>EDIT: Is it me, or when updating this page, I saw both the question and all the answers decreased by one point in a couple of minutes? Is someone enjoying himself too much while remaning anonymous?</strong></p>
<p>EDIT 2: <strong>McDowell</strong> offered a very interesting link I felt I had to mention here:
<a href="http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html" rel="noreferrer">http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html</a></p>
<p>EDIT 3: Following McDowell's link, I tumbled upon a proposal for Java 7 of a pattern similar to the C# using pattern: <a href="http://tech.puredanger.com/java7/#resourceblock" rel="noreferrer">http://tech.puredanger.com/java7/#resourceblock</a> . My problem is explicitly described. Apparently, even with the Java 7 <code>do</code>, the problems remain.</p>
| <p>The try/finally pattern is the correct way to handle streams in most cases for Java 6 and lower.</p>
<p><em>Some are advocating silently closing streams. Be careful doing this for these reasons: <a href="http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html" rel="noreferrer">Java: how not to make a mess of stream handling</a></em></p>
<hr>
<p>Java 7 introduces <em>try-with-resources</em>:</p>
<pre><code>/** transcodes text file from one encoding to another */
public static void transcode(File source, Charset srcEncoding,
File target, Charset tgtEncoding)
throws IOException {
try (InputStream in = new FileInputStream(source);
Reader reader = new InputStreamReader(in, srcEncoding);
OutputStream out = new FileOutputStream(target);
Writer writer = new OutputStreamWriter(out, tgtEncoding)) {
char[] buffer = new char[1024];
int r;
while ((r = reader.read(buffer)) != -1) {
writer.write(buffer, 0, r);
}
}
}
</code></pre>
<p><a href="http://download.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html" rel="noreferrer"><code>AutoCloseable</code></a> types will be automatically closed:</p>
<pre><code>public class Foo {
public static void main(String[] args) {
class CloseTest implements AutoCloseable {
public void close() {
System.out.println("Close");
}
}
try (CloseTest closeable = new CloseTest()) {}
}
}
</code></pre>
| <p>Unfortunately, this type of code tends to get a bit bloated in Java.</p>
<p>By the way, if one of the calls to oSBuffer.read or oDBuffer.write throws an exception, then you probably want to let that exception permeate up the call hierarchy.</p>
<p>Having an unguarded call to close() inside a finally-clause will cause the original exception to be replaced by one produced by the close()-call. In other words, a failing close()-method may hide the original exception produced by read() or write(). So, I think you want to ignore exceptions thrown by close() if <em>and only if</em> the other methods did not throw.</p>
<p>I usually solve this by including an explicit close-call, inside the inner try:</p>
<pre>
try {
while (...) {
read...
write...
}
oSBuffer.close(); // exception NOT ignored here
oDBuffer.close(); // exception NOT ignored here
} finally {
silentClose(oSBuffer); // exception ignored here
silentClose(oDBuffer); // exception ignored here
}
</pre>
<pre>
static void silentClose(Closeable c) {
try {
c.close();
} catch (IOException ie) {
// Ignored; caller must have this intention
}
}
</pre>
<p>Finally, for performance, the code should probably work with buffers (multiple bytes per read/write). Can't back that by numbers, but fewer calls should be more efficient than adding buffered streams on top.</p>
| 23,602 |
<p>I made a simple game for the iPhone using OpenGL ES. Everything works fine except for this problem:</p>
<p>I turn the phone completely off, then back on, then launch my app and I get this wierd flickering! Every other frame is correct... the incorrect frames are just the same frame over and over again. If I quit the app, launch it again everything is fine. If I quit and restart 10 times in a row everything is fine every time.</p>
<p>But if I turn the phone off, then back on, then launch the app I get the same flickering the first time I launch the app.</p>
<p>Why is this happening?!</p>
<p>Has anyone else had this problem?</p>
<p>Cheers!</p>
| <p>Apple published additional information about this issue: </p>
<blockquote>
<p>Q: My OpenGL ES application flickers.
Especially when running on iPhone 3GS,
the flickering seems to happen every
frame. How do I fix this problem?</p>
<p>A: By default, the contents of a
renderbuffer are invalidated after it
is presented to the screen (by calling
-EAGLContext/presentRenderbuffer:). Your application must completely
redraw the contents of the
renderbuffer every time you draw a
frame, otherwise you may observe
flickering or other unexpected
results.</p>
<p>You must provide a color to every
pixel on the screen. At the beginning
of your drawing code, it is a good
idea to use glClear() to initialize
the color buffer. A full-screen clear
of each of your color, depth, and
stencil buffers (if you're using them)
at the start of a frame can also
generally improve your application's
performance.</p>
<p>If your application needs to preserve
the drawable contents between frames,
you can add the option
kEAGLDrawablePropertyRetainedBacking =
YES to your CAEAGLLayer object's
drawableProperties property. Using
this option requires additional memory
and can reduce your application's
performance.</p>
</blockquote>
| <p>Hmm. I haven't done much with OpenGL on the iPhone, but I have to say I haven't noticed this behavior with other applications. I'd suspect it's something to do with how you're switching active framebuffers. </p>
<p>Maybe take a look at some of the sample code, and see what you're doing differently?</p>
| 25,800 |
<p>Do you know a good source to learn how to design SQL solutions?</p>
<p>Beyond the basic language syntax, I'm looking for something to help me understand:</p>
<ol>
<li>What tables to build and how to link them</li>
<li>How to design for different scales (small client APP to a huge distributed website)</li>
<li>How to write effective / efficient / elegant SQL queries</li>
</ol>
| <p>I started with this book: <a href="http://www.amazon.co.uk/Relational-Database-Explained-Kaufmann-Management/dp/1558608206/ref=sr_1_3?ie=UTF8&s=books&qid=1229597641&sr=8-3" rel="noreferrer">Relational Database Design Clearly Explained (The Morgan Kaufmann Series in Data Management Systems) (Paperback)</a> by Jan L. Harrington and found it very clear and helpful</p>
<p>and as you get up to speed this one was good too <a href="http://www.amazon.co.uk/Database-Systems-Implementation-Management-International/dp/0321210255/ref=cm_lmf_tit_5_rsrrsi0" rel="noreferrer">Database Systems: A Practical Approach to Design, Implementation and Management (International Computer Science Series)</a> (Paperback)</p>
<p>I think SQL and database design are <strong>different</strong> (but complementary) skills.</p>
| <p>These are questions which, in my opionion, requires different knowledge from different domains.</p>
<ol>
<li>You just can't know in advance "which" tables to build, you have to know the problem you have to solve and design the schema accordingly;</li>
<li>This is a mix of database design decision and your database vendor custom capabilities (ie. you should check the documentation of your (r)dbms and eventually learn some "tips & tricks" for scaling), also the configuration of your dbms is crucial for scaling (replication, data partitioning and so on);</li>
<li>again, almost every rdbms comes with a particular "dialect" of the SQL language, so if you want efficient queries you have to learn that particular dialect --btw. much probably write elegant query which are also efficient is a big deal: elegance and efficiency are frequently conflicting goals--</li>
</ol>
<p>That said, maybe you want to read some books, personally I've used <a href="http://www.webml.org/dbbook/" rel="nofollow noreferrer" title="this book">this book</a> in my datbase university course (and found a decent one, but I've not read other books in this field, so my advice is to check out for some good books in database design).</p>
| 49,415 |
<p>When writing C/C++ code, in order to debug the binary executable the debug option must be enabled on the compiler/linker. In the case of GCC, the option is -g. When the debug option is enabled, how does the affect the binary executable? What additional data is stored in the file that allows the debugger function as it does?</p>
| <p>-g tells the compiler to store symbol table information in the executable. Among other things, this includes:</p>
<ul>
<li>symbol names</li>
<li>type info for symbols</li>
<li>files and line numbers where the symbols came from</li>
</ul>
<p>Debuggers use this information to output meaningful names for symbols and to associate instructions with particular lines in the source.</p>
<p>For some compilers, supplying -g will disable certain optimizations. For example, icc sets the default optimization level to -O0 with -g unless you explicitly indicate -O[123]. Also, even if you do supply -O[123], optimizations that prevent stack tracing will still be disabled (e.g. stripping frame pointers from stack frames. This has only a minor effect on performance).</p>
<p>With some compilers, -g will disable optimizations that can confuse where symbols came from (instruction reordering, loop unrolling, inlining etc). If you want to debug with optimization, you can use -g3 with gcc to get around some of this. Extra debug info will be included about macros, expansions, and functions that may have been inlined. This can allow debuggers and performance tools to map optimized code to the original source, but it's best effort. Some optimizations really mangle the code.</p>
<p>For more info, take a look at <a href="http://en.wikipedia.org/wiki/DWARF" rel="noreferrer">DWARF</a>, the debugging format originally designed to go along with ELF (the binary format for Linux and other OS's).</p>
| <p>There is some overlap with this <a href="https://stackoverflow.com/questions/69250/why-does-a-cc-program-often-have-optimization-turned-off-in-debug-mode#69313">question</a> which covers the issue from the other side.</p>
| 11,509 |
<p>When I ssh into a remote production server I would like the colour scheme of my terminal window to change to something brigh and scary, preferably red, to warn me that I am touching a live scary server. </p>
<p>How can I make it automatically detect that I have ssh'ed somewhere, and if that somewhere is on a specific list, change the colour scheme?</p>
<p>I want to update the Scheme of Terminal.app, not know how I would do this in a pure linux/unix env</p>
| <p>Put following script in <code>~/bin/ssh</code> (ensure <code>~/bin/</code> is checked before <code>/usr/bin/</code> in your PATH):</p>
<pre><code>#!/bin/sh
HOSTNAME=`echo $@ | sed s/.*@//`
set_bg () {
osascript -e "tell application \"Terminal\" to set background color of window 1 to $1"
}
on_exit () {
set_bg "{0, 0, 0, 50000}"
}
trap on_exit EXIT
case $HOSTNAME in
production1|production2|production3) set_bg "{45000, 0, 0, 50000}" ;;
*) set_bg "{0, 45000, 0, 50000}" ;;
esac
/usr/bin/ssh "$@"
</code></pre>
<p>Remember to make the script executable by running <code>chmod +x ~/bin/ssh</code></p>
<p>The script above extracts host name from line "username@host" (it assumes you login to remote hosts with "ssh user@host").</p>
<p>Then depending on host name it either sets red background (for production servers) or green background (for all other). As a result all your ssh windows will be with colored background.</p>
<p>I assume here your default background is black, so script reverts the background color back to black when you logout from remote server (see "trap on_exit").</p>
<p>Please, note however this script does not track chain of ssh logins from one host to another. As a result the background will be green in case you login to testing server first, then login to production from it.</p>
| <p>You should change the color of username and host machine name.</p>
<p>add the following line to your <code>~/.bash_profile</code> file:</p>
<pre><code>export PS1=" \[\033[34m\]\u@\h \[\033[33m\]\w\[\033[31m\]\[\033[00m\] $ "
</code></pre>
<p>The <strong>first part</strong> (purple colored) is what you're looking for.</p>
<p><strong>Preview:</strong>
<a href="https://i.stack.imgur.com/a4enm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a4enm.png" alt="enter image description here"></a> </p>
<p>This is my preferred colors. You can customize each part of prompt's color by changing <code>m</code> codes (e.g. <code>34m</code>) which are ANSI color codes.</p>
<p><strong>List of ANSI Color codes:</strong></p>
<ul>
<li>Black: 30m</li>
<li>Red: 31m</li>
<li>Green: 32m </li>
<li>Yellow: 33m</li>
<li>Blue: 34m</li>
<li>Purple: 35m</li>
<li>Cyan: 36m</li>
<li>White: 37m</li>
</ul>
| 19,102 |
<p>Suppose I have a vector that is nested in a dataframe one or two levels. Is there a quick and dirty way to access the last value, without using the <code>length()</code> function? Something ala PERL's <code>$#</code> special var?</p>
<p>So I would like something like:</p>
<pre><code>dat$vec1$vec2[$#]
</code></pre>
<p>instead of</p>
<pre><code>dat$vec1$vec2[length(dat$vec1$vec2)]
</code></pre>
| <p>I use the <code>tail</code> function:</p>
<pre><code>tail(vector, n=1)
</code></pre>
<p>The nice thing with <code>tail</code> is that it works on dataframes too, unlike the <code>x[length(x)]</code> idiom.</p>
| <p>The xts package provides a <code>last</code> function:</p>
<pre><code>library(xts)
a <- 1:100
last(a)
[1] 100
</code></pre>
| 10,294 |
<p>I have a piece of code in ANSI C which uses the time.h library and time_h structures to (amongst other date-related calculations) work out the interval between two given dates. This works fine but this limits my code to input between 1970 and 2038. I would now like to make my code more general.</p>
<p>Is there a common C library (ANSI or C99 standard) which implements date calculations on ranges larger than time.h, on a granularity of 1 day (i.e. I need to-the-day resolution but hour resolution is not necessary)?</p>
<p>(I'm adapting the code to deal with historical events hence it would be nice if it could also deal with dates in B.C. ....)</p>
| <p>Yes, the <a href="http://code.google.com/p/y2038/" rel="nofollow noreferrer">y2038 project</a> is reimplementing time.h to be 2038 safe. So far <code>gmtime()</code>, <code>localtime()</code>, <code>mktime()</code> and <code>gmtime()</code> are done and well tested. Those were the hard bits. It spans about 300 billion years in either direction.</p>
| <p>There's a public domain implementation used in SQLite: <a href="http://www.sqlite.org/lang_datefunc.html" rel="nofollow noreferrer">documentation</a>, <a href="http://www.sqlite.org/cvstrac/fileview?f=sqlite/src/date.c&v=1.94" rel="nofollow noreferrer">source</a></p>
<p>I've also found the <a href="http://www.tondering.dk/claus/calendar.html" rel="nofollow noreferrer">Calendar FAQ</a> useful; <a href="http://www.smart.net/~mmontes/ec-cal.html" rel="nofollow noreferrer">this</a> page pops up early on Google.</p>
| 42,910 |
<p>Can a <code>JApplet</code> use a <code>JFileChooser</code> so that the user can select a file on his hard-drive? Or would this violate Java applet security? (I'm assuming that the default security settings are being used. I don't want to ask my users to grant me extra permissions.)</p>
| <p><a href="http://forums.sun.com/thread.jspa?threadID=5322793&tstart=91" rel="nofollow noreferrer">This thread</a> indicates that you need to digitally sign your applet before a <code>JFileChooser</code> is permitted.</p>
| <p>In that case (of using default settings), you're correct, the default security manager does not allow access to local files.</p>
| 29,119 |
<p>I have a program that can have a lot of parameters (we have over +30 differents options).</p>
<p>Example:
<code>myProgram.exe -t alpha 1 -prod 1 2 -sleep 200</code></p>
<p>This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command.</p>
<p>For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command.</p>
<p>Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF?</p>
<p>The code is in C# but I think the logic can be any other language too...</p>
| <p>Create a hash table which stores function pointers (in C# that'd be delegates) for handling each of the parameters, keyed using the parameter text. Then you just go through the command line in a loop and make calls to delegates based on what comes out of hash table lookups.</p>
| <p>I dont think this is too cludging.. </p>
<pre><code>private void Main()
{
string c = "-t alpha 1 -prod 1 2 -sleep 200";
foreach (string incommand in Strings.Split(c, "-")) {
HandleCommand(Strings.Split(incommand.Trim, " "));
}
}
public void HandleCommand(string[] c)
{
switch (c(0).ToLower) {
case "t":
Interaction.MsgBox("Command:" + c(0) + " params: " + c.Length - 1);
break;
case "prod":
Interaction.MsgBox("Command:" + c(0) + " params: " + c.Length - 1);
break;
case "sleep":
Interaction.MsgBox("Command:" + c(0) + " params: " + c.Length - 1);
break;
}
}
</code></pre>
<p>Of course, instead of doing exactly same thing in those switch-statements, call appropriate functions or code.</p>
| 41,931 |
<p>Is there a function, that clears last line in command prompt? I dont mean "cls" - it clears the whole sreen, I want to delete just the last line.</p>
<p>e.g. I am searching for a file in a folder and its subfolders and I want to print to cmd current folder - but I want to rewrite it, when the folder changes, not just append to the end. I know, this is just a banality, but I am interested how could be it done.</p>
| <p>Which one is that last line?<br>
The one just above the prompt?<br>
If that's what you mean then no, there is no way to clear just that using the prompt.
If you're talking about doing it programatically, try using <code>"\r"</code> like so:</p>
<pre><code>print("\rNew text in the line");
</code></pre>
| <p>You Could use brackets to record the previous, then not record the line you want to delete using the TYPE command: (This is just an example)</p>
<pre><code>(
echo (Previous Outputs)
(This may happen as many times as needed)
) >> C:\file.txt
set /P thing=
cls
type C:\file.txt
pause
</code></pre>
| 48,033 |
<p>I am making a quiz system, and when quizmakers insert questions into the Question Bank, I am to check the DB for duplicate / very highly similar questions.</p>
<p>Testing MySQL's <a href="http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html#function_match" rel="noreferrer">MATCH() ... AGAINST()</a>, the highest relevance I get is 30+, when I test against a 100% similar string.</p>
<p>So what exactly is the relevance? To quote the <a href="http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html" rel="noreferrer">manual</a>:</p>
<blockquote>
<p>Relevance values are non-negative floating-point numbers. Zero relevance means no similarity. Relevance is computed based on the number of words in the row, the number of unique words in that row, the total number of words in the collection, and the number of documents (rows) that contain a particular word. </p>
</blockquote>
<p>My problem is how to test the relevance value if a string is a duplicate. If it's 100% duplicate, prevent it from being inserter into Question Bank. But if it is only so similar, prompt the quizmaker to verify, insert or not. So how do I do that? 30+ for 100% identical string is not percentage, so I'm stump.</p>
<p>Thanks in advance.</p>
| <p>andygeers is on the right track: Those numbers have no empirical meaning other than their relations to each other and cannot be used on their own to determine what is or is not an "exact match". You need to determine that yourself. Even aside from the limitations of fulltext search ranking, there's also the open question of just what you consider to consitiute an "exact match". (Actual text only or do soundex matches count? Do synonyms (e.g., "couch" vs. "sofa") count as matching or as distinct? Should an attempt be made to compensate for misspellings? Etc.)</p>
<p>If I had the need to perform such a check, I would grab only the highest-ranked entry returned by the fulltext search, remove any designated stopwords, normalize whitespace, convert to lowercase, do the comparison, and leave it at that until I encountered a case that called for it to be refined further. It's not really all <em>that</em> much extra work - if you specify the language you're using for your application, you could probably find someone around here who could write the normalization function within a dozen or so lines of code.</p>
| <p>I don't know the specifics of the MySQL function you're using, but I imagine it could be that there is no absolute meaning for those numbers - they're just designed to be compared with other values produced by the same function. To check for an absolute match you could select out the text itself and compare manually.</p>
| 29,436 |
<p>How do I save a jpg image to database and then load it in Delphi using FIBplus and TImage?</p>
| <pre><code>var
S : TMemoryStream;
begin
S := TMemoryStream.Create;
try
TBlobField(AdoQuery1.FieldByName('ImageField')).SaveToStream(S);
S.Position := 0;
Image1.Picture.Graphic.LoadFromStream(S);
finally
S.Free;
end;
end;
</code></pre>
<p>if you are using JPEG images, add JPG unit to <strong>uses</strong> clause of your unit file.</p>
| <p><a href="http://delphi.about.com/od/database/l/aa030601a.htm" rel="nofollow noreferrer">Take a look here.</a>
I think you have to convert it to a stream, store it and vice versa.</p>
| 8,759 |
<p>I've tried using source control for a couple projects but still don't really understand it. For these projects, we've used TortoiseSVN and have only had one line of revisions. (No trunk, branch, or any of that.) If there is a recommended way to set up source control systems, what are they? What are the reasons and benifits for setting it up that way? What is the underlying differences between the workings of a centralized and distributed source control system?</p>
| <p>I recommend checking out the following from Eric Sink:</p>
<p><a href="http://www.ericsink.com/scm/source_control.html" rel="noreferrer">http://www.ericsink.com/scm/source_control.html</a></p>
<p>Having some sort of revision control system in place is probably the most important tool a programmer has for reviewing code changes and understanding who did what to whom. Even for single person projects, it is invaluable to be able to diff current code against previous known working version to understand what might have gone wrong due to a change.</p>
| <p>Even if you don't branch, you may find it useful to use tags to mark releases.</p>
<p>Imagine that you rolled out a new version of your software yesterday and have started making major changes for the next version. A user calls you to report a serious bug in yesterday's release. You can't just fix it and copy over the changes from your development trunk because the changes you've just made the whole thing unstable.</p>
<p>If you had tagged the release, you could check out a working copy of it and use it to fix the bug.</p>
<p>Then, you might choose to create a branch at the tag and check the bug fix into it. That way, you can fix more bugs on that release while you continue to upgrade the trunk. You can also merge those fixes into the trunk so that they'll be present in the next release.</p>
| 3,438 |
<p>I need to generate a tone that I can manipulate frequency and wave. The overall goal is to create a basic piano. Does anyone know how I can achieve this?</p>
<p>My development platform is the iPhone 2.x</p>
| <p>You could always start with <code>sin</code> waves. :-)</p>
<pre><code>#include <cmath>
typedef double Sample;
typedef double Time;
class MonoNote {
protected:
Time start, duration;
virtual void internalRender(double now, Sample *mono) = 0;
public:
MonoNote(Time s, Time d) : start(s), duration(d) {}
virtual ~MonoNote() {}
void render(double now, Sample *mono) {
if (start <= now && now < start + duration) {
internalRender(now, mono);
}
}
};
class MonoSinNote : public MonoNote {
Time freq;
Sample amplitude;
protected:
void internalRender(double now, Sample *mono) {
const double v = sin(2*M_PI*(now - start) * freq);
*mono += amplitude*v;
}
public:
MonoSinNote(Time s, Time d, Time f, Sample a) : MonoNote(s, d), freq(f), amplitude(a) {}
~MonoSinNote() {}
};
</code></pre>
| <p>Check out <a href="http://mda.smartelectronix.com/" rel="nofollow noreferrer">http://mda.smartelectronix.com/</a>. They are a series of open source VST plugins. Look at the source for Piano, ePiano or DX10. It's about as simple as you are going to find.</p>
| 45,182 |
<p>So we've discussed logging in passing at my place of work and I was wondering if some of you guys here could give me some ideas of your approaches?</p>
<p>Typically our scenario is, no logging really at all, and mostly .NET apps, winforms/WPF clients talking through web services or direct to a db.</p>
<p>So, the real question is, where or what would you log? At the moment we have users reporting error messages - so I would assume log startups/shutdowns, exceptions...</p>
<p>Do you take it to calls to the web services or db? Page loads?</p>
<p>How do you get a good idea of what the user was trying to do at the time?</p>
<p>Is it better to go all the way and log everything across multiple attempts/days, or log only what you need to (given hdd is cheap).</p>
<p>I guess that's a few questions, but I wanted to get more of an idea of what the actual practice is out there in larger shops!</p>
| <p>The key thing for logging is good planning. I would suggest that you look into the enterprise library exception and logging application block (<a href="http://msdn.microsoft.com/en-us/library/cc467894.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cc467894.aspx</a>). There is a wee bit of a learning curve but it does work quite well. The approach I favour at the moment is to define 4 priority levels. 4=Unhandled exception (error in event log), 3=Handled exception (warning in event log), 2=Access an external resource such as a webservice, db or mainframe system (information in event log), 1=Verbose/anything else of interest (information in event log).</p>
<p>Using the application block it's then quite easy to tweak what level of priority you want to log. So in development you'd log everything but as you get a stable system in production, you'd probably only be interested in unhandled exceptions and possibly handled exceptions.</p>
<p><strong>Update</strong>: For clarity, I would suggest you have logging in both your winform/wpf app and your webservices. In a web scenario, I've had problems in the past where it can be difficult to tie an error on the client back through to the app servers. Mainly because any error through webservices gets wrapped up as a SOAP exception. I can't remember off the top of my head, but I think if you use a custom exception handler (that is part of the enterprise library) you can add data onto exceptions such as the handlinginstance id of the exception from the app server. This makes it easier to tie up exceptions on a client back to your app box by using LogParser (<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07&displaylang=en" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07&displaylang=en</a>). </p>
<p><strong>Second Update</strong>: I also like to give each different event a seperate event id and to track that in a text file or spreadsheet under source control. Yes, its a pain but if you're lucky enough to have an IT team looking after your systems in production, I find they tend to expect different events to have different event ids.</p>
| <p>Thanks guys, lot of good info, but Martin has given me a bit more detail on how to proceed. I'll give him the answer, as it seems like now we're off the front few pages answers will drop off.</p>
| 5,644 |
<p>I currently have some code that pulls down a list of users in a group and then iterates through that group to determine if a given account exists, but it seems like there ought to be a more concise (and perhaps faster) way to accomplish this.</p>
<p>This code (VB.NET) attempts to use the member property of the group object, but it is returning false even when the user is a member of that group. Can anyone see what I am doing wrong here?</p>
<pre><code>Dim group As DirectoryEntry = GetNetworkObject(GroupDomanName, NetworkObjectType.NetworkGroup, GroupName)
Dim user As DirectoryEntry =GetNetworkObject(UserDomainName, NetworkObjectType.NetworkUser, Login)
Return group.Properties("member").Contains(user.Path)
</code></pre>
<p>FYI: The GetNetworkObject calls just return a directoryEntry object, I have confirmed that the correct object is being returned for both the group and user object.</p>
| <p>If you are on .NET 3.5 stack, <a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx" rel="noreferrer">System.DirectoryServices.AccountManagement.dll assembly</a> has a nice API on top of AD. The following method can be implemented to solve your issue:</p>
<pre><code>static bool IsUserMemberOf(string userName, string groupName)
{
using (var ctx = new PrincipalContext(ContextType.Domain))
using (var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupName))
using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, userName))
{
return userPrincipal.IsMemberOf(groupPrincipal);
}
}
// Usage:
bool result = IsUserMemberOf("CONTOSO\\john.doe", "CONTOSO\\Administrators");
</code></pre>
<p>I don't know how this method performs but it is a clean solution.</p>
| <p>I found an answer that seems to work in NET 2.0, is relatively quick and overcomes the possible issue of groups containing more than 100 items (which require range searching)</p>
<p>Here is the code that I wound up with:</p>
<pre><code>Dim DSearcher As New DirectorySearcher(group, "(&(objectClass=user)(cn=" + Login + "))", New String() {"member;Range=0-5000"}, SearchScope.OneLevel)
group = GetNetworkObject(GroupDomanName, NetworkObjectType.NetworkGroup, GroupName)
user = GetNetworkObject(UserDomainName, NetworkObjectType.NetworkUser, Login)
DSearcher.AttributeScopeQuery = "member"
Return (DSearcher.FindOne() IsNot Nothing)
</code></pre>
| 48,157 |
<p>I am creating a GUI for a machine that runs remote (WinXP) or on the machine itself (Windows CE 6.0).</p>
<p>Right now I've created a fast visualisation (read: very simple) of the machine itself. The goal is to make a bit more complex visualisation of the machine and for that I would need a lightweight 3d engine.</p>
<p>The engine should run on both full and compact .net framework (I am prepared to do some porting :). <br />
What I mean with lightweigt is that it doesn't need shading, lighting, advanced camera's. The Idea is that the whole scene is shown in Isometric perspective.</p>
<p>So what I was wondering is that anyone knows a good engine (open source?) or has some helpfull resources you could share with me.</p>
| <p>Did you try <a href="http://irrlicht.sourceforge.net/" rel="nofollow noreferrer">Irrlicht</a>. </p>
<blockquote>
<p>Recently Irrlicht has acquired official .NET bindings, allowing users to develop in .Net languages such as VB.NET, C# and Boo.</p>
</blockquote>
<p>There is also <a href="http://en.wikipedia.org/wiki/OGRE_3D" rel="nofollow noreferrer">Ogre 3D</a> and also <a href="http://en.wikipedia.org/wiki/Axiom_Engine" rel="nofollow noreferrer">Axiom Engine</a></p>
| <p>It is a good question. I have looked as well, and not seen anything. It would be great to see some easy to access great visual effects for mobile, to somewhat compete with other platforms that are getting better looking.</p>
<p>Sometimes with Windows Mobile I feel like I am in the Windows 3.1 days!</p>
| 6,726 |
<p>Is there a javascript function to swap a still image(jpg) to a movie(swf)? If there is is there a disjointed swap image path?</p>
| <p>You could do something like this:</p>
<pre><code><div id="still_image" style="display:block">
<!-- img code here -->
</div>
<div id="ani_swf" style="display:none">
<!-- embedded swf here -->
</div>
<input type="button" value="Swap" onclick="imgToSWF();" />
<script type="text/javascript">
function imgToSWF() {
document.getElementById('still_image').style.display = 'none';
document.getElementById('ani_swf').style.display = 'block';
}
</script>
</code></pre>
| <p>You can use <a href="http://code.google.com/p/swfobject/" rel="nofollow noreferrer">swfobject</a>. Ofcourse, you didn't said too much about what do you really want to do: on mouseover, on page load (and the image will be only a replacement), and so on...</p>
| 49,570 |
<p>I’ve got an issue with loading a particular X509 certificate within an ASP.NET application (i.e. not through IIS for https). I’ve loaded it into my ‘Personal’ and ‘Trusted Root’ stores on my local machine (through the MMC snap in) but can’t load it from either store.</p>
<p>It seems the NETWORK SERVICE account doesn’t have permissions to read/load it because when I change the app pools identity to a user with administration rights I can find, load and use the cert.</p>
<p>It’s only a public cert, so unlike a cert with a private key, I can’t see anywhere to set permissions on it.</p>
<p>It’s odd because I haven’t had this problem with public certs in this application previously. The only difference I can see to this public cert and previous public certs (which loaded fine) is that this particular public cert has be signed by Verisign and therefore has a certification chain with a couple of other verisign certs.</p>
<p>Thanks in advance,<br/>
Charles</p>
<p>FYI, My dev enviroment is just my Vista Business machine with IIS7.</p>
| <p>It's been a while, but I seem to recall having had permission-related certificate issues that I solved by importing the cert into a <em>physical</em> store (click the "Show physical stores" check box when installing your certificate).</p>
<p>Alternatively, you could take a look with <a href="http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx" rel="nofollow noreferrer">FileMon</a> or <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow noreferrer">ProcMon</a> and check for Access Denieds for NETWORK SERVICE. This MSDN page lists the <a href="http://msdn.microsoft.com/en-us/library/bb204778(VS.85).aspx#key_directories_and_files" rel="nofollow noreferrer">locations of the stores on disk</a>.</p>
<p>Still remains a vague answer, but hopefully this eventually leads to a solution...</p>
| <p>Couple different thoughts. I'm a little confused by how you are using the term "cert with a private key" and what you mean by "use the cert" after you have tried to access it with admin rights. I'm guessing that you are trying to do one of the following:</p>
<ul>
<li><p>get a copy of the certificate and do something like verify it, or use it to encrypt something.</p></li>
<li><p>get a copy of the certificate <em>and</em> the private key, and use it to do something like sign something.</p></li>
</ul>
<p><strong>So... if it's #1</strong>, my first bet is that the settings for the certificate have messed up something in the ASP.NET protocols. Verisign would have configured the profile used to generate and sign the certificate in a specific way. This would give the certificate settings that you can't change that might interfere with uploading the certificate. I would check the certificate that gives you problems against the certificates that don't have any problems and see how the extensions on the certificates vary. You can do this through the IE certificate preview pane in the client. Check into any different settings that you find online - there are usually published reports about Microsoft integration issues. </p>
<p>Sadly, if you find a problem, you have to go back to Versign and get a new certificate signed with the correct extensions. If you have a corporate account, ask to talk to their upper tier support, they should be clueful enough to help you find a certificate profile that will work for your tools.</p>
<p><strong>If it's #2</strong> - you may have made the private key for the certificate non-exportable. I'm assuming you're using a software certificate and you uploaded a PKCS12 or other certificate storage file into the browser. At that time, it would have asked if you wanted to be able to export the private key. If you said no (left the box unchecked), then the private key won't leave the browser. </p>
<p>If you have the original certificate/private key storage file around, the answer is painless - delete the cert from your personal certificate store, and reupload it. Be sure to check the exportable box. </p>
| 43,929 |
<p>There have been plenty of questions on MVC validation but so far the answer has been pretty much inconclusive.</p>
<p>For my needs in particular, I would like something that generates client validation and server validation from the same description and should allow both model based attributes as well as code based declarations for those using an ORM (e.g. LINQ TO SQL) exclusively.</p>
<p>I have seen some validation packs that have been whipped up to do this but they tend to introduce a lot of dependencies or are reasonably incomplete (e.g. no support for check boxes or no "higher-level" validation).</p>
<p>Do we begin writing our own validation framework or do we wait in hope that the team may actually release something now that they have the structure for validation in place and jQuery on board?</p>
<p>For those out there actually using MVC in the field now what are you using for validation?</p>
| <p>Different search engines have different algorithms to get the description out of the page if/when they are lacking the description meta tag. Some ignore the tag even it it's there.</p>
<p>If you want the description Google has, the most accurate way to get it would be to scrape it. Otherwise, you could write your own or look around on the web for code that does it.</p>
| <p>You may want to check AboutUs.org (i.e. <a href="http://www.aboutus.org/StackOverflow.com" rel="nofollow noreferrer">http://www.aboutus.org/StackOverflow.com</a>).
But, there's little chance that the site will have an aboutus page and not have a meta description.</p>
| 38,609 |
<p>Is there a way to include all the jar files within a directory in the classpath?</p>
<p>I'm trying <code>java -classpath lib/*.jar:. my.package.Program</code> and it is not able to find class files that are certainly in those jars. Do I need to add each jar file to the classpath separately? </p>
| <p>Using Java 6 or later, the classpath option supports wildcards. Note the following:</p>
<ul>
<li>Use straight quotes (<code>"</code>)</li>
<li>Use <code>*</code>, not <code>*.jar</code></li>
</ul>
<p><strong>Windows</strong></p>
<blockquote>
<p><code>java -cp "Test.jar;lib/*" my.package.MainClass</code></p>
</blockquote>
<p><strong>Unix</strong></p>
<blockquote>
<p><code>java -cp "Test.jar:lib/*" my.package.MainClass</code></p>
</blockquote>
<p>This is similar to Windows, but uses <code>:</code> instead of <code>;</code>. If you cannot use wildcards, <code>bash</code> allows the following syntax (where <code>lib</code> is the directory containing all the Java archive files):</p>
<blockquote>
<p><code>java -cp "$(printf %s: lib/*.jar)"</code></p>
</blockquote>
<p>(Note that using a classpath is incompatible with the <code>-jar</code> option. See also: <a href="https://stackoverflow.com/questions/13018100/execute-jar-file-with-multiple-classpath-libraries-from-command-prompt">Execute jar file with multiple classpath libraries from command prompt</a>)</p>
<p><strong>Understanding Wildcards</strong></p>
<p>From the <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpath.html" rel="noreferrer">Classpath</a> document:</p>
<blockquote>
<p>Class path entries can contain the basename wildcard character <code>*</code>, which is considered equivalent to specifying a list of all the files
in the directory with the extension <code>.jar</code> or <code>.JAR</code>. For example, the
class path entry <code>foo/*</code> specifies all JAR files in the directory named
foo. A classpath entry consisting simply of <code>*</code> expands to a list of all
the jar files in the current directory.</p>
<p>A class path entry that contains <code>*</code> will not match class files. To
match both classes and JAR files in a single directory foo, use either
<code>foo;foo/*</code> or <code>foo/*;foo</code>. The order chosen determines whether the
classes and resources in <code>foo</code> are loaded before JAR files in <code>foo</code>, or
vice versa.</p>
<p>Subdirectories are not searched recursively. For example, <code>foo/*</code> looks
for JAR files only in <code>foo</code>, not in <code>foo/bar</code>, <code>foo/baz</code>, etc.</p>
<p>The order in which the JAR files in a directory are enumerated in the
expanded class path is not specified and may vary from platform to
platform and even from moment to moment on the same machine. A
well-constructed application should not depend upon any particular
order. If a specific order is required then the JAR files can be
enumerated explicitly in the class path.</p>
<p>Expansion of wildcards is done early, prior to the invocation of a
program's main method, rather than late, during the class-loading
process itself. Each element of the input class path containing a
wildcard is replaced by the (possibly empty) sequence of elements
generated by enumerating the JAR files in the named directory. For
example, if the directory <code>foo</code> contains <code>a.jar</code>, <code>b.jar</code>, and <code>c.jar</code>, then
the class path <code>foo/*</code> is expanded into <code>foo/a.jar;foo/b.jar;foo/c.jar</code>,
and that string would be the value of the system property
<code>java.class.path</code>.</p>
<p>The <code>CLASSPATH</code> environment variable is not treated any differently from
the <code>-classpath</code> (or <code>-cp</code>) command-line option. That is, wildcards are
honored in all these cases. However, class path wildcards are not
honored in the <code>Class-Path jar-manifest</code> header.</p>
</blockquote>
<p>Note: due to a known bug in java 8, the windows examples must use a backslash preceding entries with a trailing asterisk: <a href="https://bugs.openjdk.java.net/browse/JDK-8131329" rel="noreferrer">https://bugs.openjdk.java.net/browse/JDK-8131329</a></p>
| <p>Order of arguments to <code>java</code> command is also important:</p>
<pre><code>c:\projects\CloudMirror>java Javaside -cp "jna-5.6.0.jar;.\"
Error: Unable to initialize main class Javaside
Caused by: java.lang.NoClassDefFoundError: com/sun/jna/Callback
</code></pre>
<p>versus</p>
<pre><code>c:\projects\CloudMirror>java -cp "jna-5.6.0.jar;.\" Javaside
Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable
</code></pre>
| 27,034 |
<p>ASP.NET MVC routes have names when mapped:</p>
<pre><code>routes.MapRoute(
"Debug", // Route name -- how can I use this later????
"debug/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = string.Empty } );
</code></pre>
<p>Is there a way to get the route name, e.g. "Debug" in the above example? I'd like to access it in the controller's OnActionExecuting so that I can set up stuff in the ViewData when debugging, for example, by prefixing a URL with /debug/...</p>
| <p>The route name is not stored in the route unfortunately. It is just used internally in MVC as a key in a collection. I think this is something you can still use when creating links with HtmlHelper.RouteLink for example (maybe somewhere else too, no idea).</p>
<p>Anyway, I needed that too and here is what I did:</p>
<pre><code>public static class RouteCollectionExtensions
{
public static Route MapRouteWithName(this RouteCollection routes,
string name, string url, object defaults, object constraints)
{
Route route = routes.MapRoute(name, url, defaults, constraints);
route.DataTokens = new RouteValueDictionary();
route.DataTokens.Add("RouteName", name);
return route;
}
}
</code></pre>
<p>So I could register a route like this:</p>
<pre><code>routes.MapRouteWithName(
"myRouteName",
"{controller}/{action}/{username}",
new { controller = "Home", action = "List" }
);
</code></pre>
<p>In my Controller action, I can access the route name with:</p>
<pre><code>RouteData.DataTokens["RouteName"]
</code></pre>
<p>Hope that helps.</p>
| <p>another option - use MapRoute with string[] namespaces argument, then you can see your namespaces as <code>RouteData.DataTokens["Namespaces"]</code></p>
| 47,419 |
<pre><code> [SoapRpcMethod(Action = "http://cyberindigo/TempWebService/InsertXML",
RequestNamespace = "http://cyberindigo/TempWebService/Request",
RequestElementName = "InsertXMLRequest",
ResponseNamespace = "http://cyberindigo/TempWebService/Response",
ResponseElementName = "InsertXMLResponse",
Use = System.Web.Services.Description.SoapBindingUse.Literal)]
[WebMethod]
public string InsertXML(string Jobs)
{
return "Hi";
}
</code></pre>
<p>The Problem when I am accessing it using XMLHttpRequest it gives following error
Server did not recognize the value of HTTP Header SOAPAction: <a href="http://Cyberindigo/TempWebService/InsertXML" rel="noreferrer">http://Cyberindigo/TempWebService/InsertXML</a></p>
| <p>The source of the next part of this post is: </p>
<blockquote>
<p><a href="http://bluebones.net/2003/07/server-did-not-recognize-http-header-soapaction/" rel="noreferrer">http://bluebones.net/2003/07/server-did-not-recognize-http-header-soapaction/</a> </p>
</blockquote>
<p>(since the OP didn't want to give attribution, and thanks to Peter)</p>
<p>Please note that bakert is the original author of the text, not the OP.</p>
<hr>
<p>Seeing as nowhere on the internet can I find an explanation of this error I thought I’d share the fruits of my long search for this bug.</p>
<p>It means (at least in my case) that you are accessing a web service with SOAP and passing a <code>SOAPAction</code> parameter in the HTTP request that does not match what the service is expecting.</p>
<p>I got in a pickle because we moved a web service from one server to another and thus I changed the “namespace” (don’t get confused between web service namespaces and .net namespaces) in the calling C# file to match the new server. But the server doesn’t care about the actual web reality of <code>http://yournamespace.com/blah</code> it only cares that you send it what you have said you are expecting on the server. It doesn’t care if there’s actually anything there or not.</p>
<p>So basically the web service was moved from <code>http://foo.com/servicename</code> to <code>http://bar.com/servicename</code> but the “namespace” of the web service stayed as <code>http://foo.com/servicename</code> because no one changed it.</p>
<p>And that only took about 4 hours to work out!</p>
<p>If you’re having a similar problem but can’t work what I’m saying here, feel free to mail me on [email protected] – I wouldn’t wish my four hours on anyone!</p>
| <p>I had to sort out capitalisation of my service reference, delete the references and re add them to fix this. I am not sure if any of these steps are superstitious, but the problem went away.</p>
| 45,857 |
<p>I am working on a small parser that should accept input in a number of languages. I am going to have maybe 50 strings that will serve as keywords/anchors in parsing the input. In PHP, what would be the best way to organize these translated keywords? </p>
<p>One possible solution that comes to my mind is to use an associative array. Like this:</p>
<pre><code>$lang = array('us' => array('totalDebt' => 'Total Debt', 'color' => 'Color'),
'gb' => array('totalDebt' => 'Total Debt', 'color' => 'Colour'))
</code></pre>
<p>which I could then access using the following:</p>
<pre><code>$langCode = 'en';
$debtPos = strpos($lang[$langCode]['totalDebt']);
</code></pre>
<p>Are there any better, proven methods for dealing with a bunch of short strings translated into a bunch of languages?</p>
| <p>For a complete translation solution, you can look on a solution like <a href="http://www.php.net/manual/en/intro.gettext.php" rel="nofollow noreferrer">gettext</a>.</p>
<p>you solution is good enough (fast, cheap on resources) for small dictionaries.
I didn't understand what you tried to do using the strpos() function.</p>
<p>Don't forget to use some kind of fallback if the term you want to translate doesn't exists in the language, usually the fallback is to the English.</p>
| <p>Generally people use l10n (or something similar) in their application because it allows for additional languages by adding a localization file which means the programmers do not have to change code. But if it is a simple script, then <a href="http://codeutopia.net/blog/2007/11/22/localize-your-site-in-3-easy-steps/" rel="nofollow noreferrer">full on localization</a> would be overkill. </p>
| 33,864 |
<p>We have a large ASP.NET project consisting of several hundred reports. We are in the process of moving all the SQL Queries (running against an Oracle Database) into three web services. The web services are categorized by command, selections and report queries. We have to deploy a sub-set of our project using a SQL*Server backend to several locations that are disconnected from the Internet. Therefore, having all connections to the database and queries in the web services makes the application manageable and we can pull the sub-set of reports and not have to modify the code. The project is under source control using Serena ChangeMan software. </p>
<p>The issue is we have several programmers and they all need check out the web services files to work on their items. We have just implemented branching, but it is slowly becoming a nightmare. We have monthly production deliveries and sometimes items that are supposed to go into the monthly build get held up until next month. The merging has become a manual process.</p>
<p>I have conduct Internet Searches and I’m surprised that I have not been able to find any good “Best Practice” web services architecture white pages. There are many big companies that must have faced these issues. </p>
<p>Do most large development groups use branching? I did read that Visual Studio Team System Database Edition could provide standard code that will allow the application to connect to different databases. Would purchasing Team System be the best method? Or does anyone know where I can find documentation that will help us address these issues? </p>
<p>Thank you,
Lorie</p>
| <p>This problem would seem to be quite independent of the purpose of the software. The issue here is that you have a small, finite number of files that multiple developers will be working with on a daily basis. I do not have experience with Serena ChangeMan software nor TFS other than playing around with it. I do have experience with a couple of version control systems that use a merge/commit model: <strong><a href="http://en.wikipedia.org/wiki/Concurrent_Versions_System" rel="nofollow noreferrer">CVS</a></strong> and <strong><a href="http://en.wikipedia.org/wiki/Subversion_(software)" rel="nofollow noreferrer">Subversion</a></strong>. These are both excellent, free version control systems that are widely used. </p>
<p>If you are unfamiliar with the merge/commit model, the idea here is that no single developer can "checkout" and lock a file for changes. Everyone can download and make changes to any file. When it is time to commit these changes to the source code database, the repository software will prevent a commit if other changes have been made to the file by another developer. The new version is then downloaded, and in most cases the changes are automatically merged with your changes. You re-test, and then you commit that version. This model is very successful and very scalable.</p>
<p>Having said all of that, even the merge/commit model cannot solve the grief of having a small number of files with a lot of developers making changes to said files. I would recommend splitting your functionality into more web services. Perhaps instead of three, monolithic web services you might create three groups of related web services. I think this, coupled with using a version control system with merge/commit will solve your problems.</p>
<p>CVS and Subversion servers run on Windows, Mac and Linux. There are a number of clients for each, available on a number of operating systems. These include stand-along clients, Visual Studio plug-ins, and shell plugins. Another plus is that both CVS and Subversion are available from the command line which makes scripting (think automated build) fairly easy.</p>
| <p>We use SOA, but we also use SVN which is more merging oriented. Maybe consider a different source control system?</p>
| 46,078 |
<p>Is there a c++ equivalent of Java's</p>
<pre><code>try {
...
}
catch (Throwable t) {
...
}
</code></pre>
<p>I am trying to debug Java/jni code that calls native windows functions and the virtual machine keeps crashing. The native code appears fine in unit testing and only seems to crash when called through jni. A generic exception catching mechanism would prove extremely useful.</p>
| <pre><code>try{
// ...
} catch (...) {
// ...
}
</code></pre>
<p>will catch all C++ exceptions, but it should be considered bad design. You can use c++11's new current_exception mechanism, but if you don't have the ability to use c++11 (legacy code systems requiring a rewrite), then you have no named exception pointer to use to get a message or name. You may want to add separate catch clauses for the various exceptions you can catch, and only catch everything at the bottom to record an unexpected exception. E.g.:</p>
<pre><code>try{
// ...
} catch (const std::exception& ex) {
// ...
} catch (const std::string& ex) {
// ...
} catch (...) {
// ...
}
</code></pre>
| <p>Well this really depends on the compiler environment.
gcc does not catch these.
Visual Studio and the last Borland that I used did.</p>
<p>So the conclusion about crashes is that it depends on the quality of your development environment.</p>
<p>The C++
specification says that catch(...) must catch any exceptions, but it doesn't in all cases.</p>
<p>At least from what I tried.</p>
| 40,794 |
<p>I am trying to use an XML-RPC server on my Drupal (PHP) backend to make it easier for my Perl backend to talk to it. However, I've run into an issue and I'm not sure which parts, if any, are bugs. Essentially, some of the variables I need to pass to Drupal are strings that sometimes are strings full of numbers and the Drupal XML-RPC server is returning an error that when a string is full of numbers it is not properly formed.</p>
<p>My Perl code looks something like this at the moment.</p>
<pre><code>use strict;
use warnings;
use XML::RPC;
use Data::Dumper;
my $xmlrpc = XML::RPC->new(URL);
my $result = $xmlrpc->call( FUNCTION, 'hello world', '9876352345');
print Dumper $result;
</code></pre>
<p>The output is:</p>
<pre><code>$VAR1 = {
'faultString' => 'Server error. Invalid method parameters.',
'faultCode' => '-32602'
};
</code></pre>
<p>When I have the Drupal XML-RPC server print out the data it receives, I notice that the second argument is typed as i4:</p>
<pre><code><param>
<value>
<i4>9876352345</i4>
</value>
</code></pre>
<p>I think when Drupal then finishes processing the item, it is typing that variable as an int instead of a string. This means when Drupal later tries to check that the variable value is properly formed for a string, the is_string PHP function returns false.</p>
<pre><code>foreach ($signature as $key => $type) {
$arg = $args[$key];
switch ($type) {
case 'int':
case 'i4':
if (is_array($arg) || !is_int($arg)) {
$ok = FALSE;
}
break;
case 'base64':
case 'string':
if (!is_string($arg)) {
$ok = FALSE;
}
break;
case 'boolean':
if ($arg !== FALSE && $arg !== TRUE) {
$ok = FALSE;
}
break;
case 'float':
case 'double':
if (!is_float($arg)) {
$ok = FALSE;
}
break;
case 'date':
case 'dateTime.iso8601':
if (!$arg->is_date) {
$ok = FALSE;
}
break;
}
if (!$ok) {
return xmlrpc_error(-32602, t('Server error. Invalid method parameters.'));
}
}
</code></pre>
<p>What I'm not sure about is on which side of the divide the issue lies or if there is something else I should be using. Should the request from the Perl side be typing the content as a string instead of i4 or is the Drupal side of the request too stringent for the string type? My guess is that the issue is the latter, but I don't know enough about how an XML-RPC server is supposed to work to know for sure.</p>
| <p>The number <code>9876352345</code> is too big to fit in a 32bit integer. That might cause the problem.</p>
| <p>The number <code>9876352345</code> is too big to fit in a 32bit integer. That might cause the problem.</p>
| 32,510 |
<p>I can't seem to find a nice clean example of using AES 128 bit encryption.</p>
<p>Does anyone have some sample code?</p>
| <p>If you just want to use the built-in crypto provider RijndaelManaged, check out the following help article (it also has a simple code sample):</p>
<blockquote>
<p><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx</a></p>
</blockquote>
<p>And just in case you need the sample in a hurry, here it is in all its plagiarized glory:</p>
<pre><code>using System;
using System.IO;
using System.Security.Cryptography;
namespace RijndaelManaged_Example
{
class RijndaelExample
{
public static void Main()
{
try
{
string original = "Here is some data to encrypt!";
// Create a new instance of the RijndaelManaged
// class. This generates a new key and initialization
// vector (IV).
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
myRijndael.GenerateKey();
myRijndael.GenerateIV();
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);
//Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Round Trip: {0}", roundtrip);
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
</code></pre>
| <p>Try this code, maybe useful.<br>
1.Create New C# Project and add follows code to Form1:</p>
<pre><code>using System;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace ExampleCrypto
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string strOriginalData = string.Empty;
string strEncryptedData = string.Empty;
string strDecryptedData = string.Empty;
strOriginalData = "this is original data 1234567890"; // your original data in here
MessageBox.Show("ORIGINAL DATA:\r\n" + strOriginalData);
clsCrypto aes = new clsCrypto();
aes.IV = "this is your IV"; // your IV
aes.KEY = "this is your KEY"; // your KEY
strEncryptedData = aes.Encrypt(strOriginalData, CipherMode.CBC); // your cipher mode
MessageBox.Show("ENCRYPTED DATA:\r\n" + strEncryptedData);
strDecryptedData = aes.Decrypt(strEncryptedData, CipherMode.CBC);
MessageBox.Show("DECRYPTED DATA:\r\n" + strDecryptedData);
}
}
}
</code></pre>
<p>2.Create clsCrypto.cs and copy paste follows code in your class and run your code. I used MD5 to generated Initial Vector(IV) and KEY of AES.</p>
<pre><code>using System;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
namespace ExampleCrypto
{
public class clsCrypto
{
private string _KEY = string.Empty;
protected internal string KEY
{
get
{
return _KEY;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_KEY = value;
}
}
}
private string _IV = string.Empty;
protected internal string IV
{
get
{
return _IV;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_IV = value;
}
}
}
private string CalcMD5(string strInput)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
StringBuilder strHex = new StringBuilder();
using (MD5 md5 = MD5.Create())
{
byte[] bytArText = Encoding.Default.GetBytes(strInput);
byte[] bytArHash = md5.ComputeHash(bytArText);
for (int i = 0; i < bytArHash.Length; i++)
{
strHex.Append(bytArHash[i].ToString("X2"));
}
strOutput = strHex.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
private byte[] GetBytesFromHexString(string strInput)
{
byte[] bytArOutput = new byte[] { };
if ((!string.IsNullOrEmpty(strInput)) && strInput.Length % 2 == 0)
{
SoapHexBinary hexBinary = null;
try
{
hexBinary = SoapHexBinary.Parse(strInput);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
bytArOutput = hexBinary.Value;
}
return bytArOutput;
}
private byte[] GenerateIV()
{
byte[] bytArOutput = new byte[] { };
try
{
string strIV = CalcMD5(IV);
bytArOutput = GetBytesFromHexString(strIV);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return bytArOutput;
}
private byte[] GenerateKey()
{
byte[] bytArOutput = new byte[] { };
try
{
string strKey = CalcMD5(KEY);
bytArOutput = GetBytesFromHexString(strKey);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return bytArOutput;
}
protected internal string Encrypt(string strInput, CipherMode cipherMode)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
byte[] bytePlainText = Encoding.Default.GetBytes(strInput);
using (RijndaelManaged rijManaged = new RijndaelManaged())
{
rijManaged.Mode = cipherMode;
rijManaged.BlockSize = 128;
rijManaged.KeySize = 128;
rijManaged.IV = GenerateIV();
rijManaged.Key = GenerateKey();
rijManaged.Padding = PaddingMode.Zeros;
ICryptoTransform icpoTransform = rijManaged.CreateEncryptor(rijManaged.Key, rijManaged.IV);
using (MemoryStream memStream = new MemoryStream())
{
using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Write))
{
cpoStream.Write(bytePlainText, 0, bytePlainText.Length);
cpoStream.FlushFinalBlock();
}
strOutput = Encoding.Default.GetString(memStream.ToArray());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
protected internal string Decrypt(string strInput, CipherMode cipherMode)
{
string strOutput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
try
{
byte[] byteCipherText = Encoding.Default.GetBytes(strInput);
byte[] byteBuffer = new byte[strInput.Length];
using (RijndaelManaged rijManaged = new RijndaelManaged())
{
rijManaged.Mode = cipherMode;
rijManaged.BlockSize = 128;
rijManaged.KeySize = 128;
rijManaged.IV = GenerateIV();
rijManaged.Key = GenerateKey();
rijManaged.Padding = PaddingMode.Zeros;
ICryptoTransform icpoTransform = rijManaged.CreateDecryptor(rijManaged.Key, rijManaged.IV);
using (MemoryStream memStream = new MemoryStream(byteCipherText))
{
using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Read))
{
cpoStream.Read(byteBuffer, 0, byteBuffer.Length);
}
strOutput = Encoding.Default.GetString(byteBuffer);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return strOutput;
}
}
}
</code></pre>
| 34,449 |
<p>I'm trying to create a unit test to test the case for when the timezone changes on a machine because it has been incorrectly set and then corrected.</p>
<p>In the test I need to be able to create DateTime objects in a none local time zone to ensure that people running the test can do so successfully irrespective of where they are located.</p>
<p>From what I can see from the DateTime constructor I can set the TimeZone to be either the local timezone, the UTC timezone or not specified.</p>
<p>How do I create a DateTime with a specific timezone like PST?</p>
| <p><a href="https://stackoverflow.com/questions/246498/creating-a-datetime-in-a-specific-time-zone-in-c-fx-35#246512">Jon's answer</a> talks about <a href="http://msdn.microsoft.com/en-us/library/system.timezone.aspx" rel="noreferrer">TimeZone</a>, but I'd suggest using <a href="http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx" rel="noreferrer">TimeZoneInfo</a> instead.</p>
<p>Personally I like keeping things in UTC where possible (at least for the past; <a href="https://codeblog.jonskeet.uk/2019/03/27/storing-utc-is-not-a-silver-bullet/" rel="noreferrer">storing UTC for the <em>future</em> has potential issues</a>), so I'd suggest a structure like this:</p>
<pre><code>public struct DateTimeWithZone
{
private readonly DateTime utcDateTime;
private readonly TimeZoneInfo timeZone;
public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
{
var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone);
this.timeZone = timeZone;
}
public DateTime UniversalTime { get { return utcDateTime; } }
public TimeZoneInfo TimeZone { get { return timeZone; } }
public DateTime LocalTime
{
get
{
return TimeZoneInfo.ConvertTime(utcDateTime, timeZone);
}
}
}
</code></pre>
<p>You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.</p>
| <p>You'll have to create a custom object for that. Your custom object will contain two values:</p>
<ul>
<li>a DateTime value</li>
<li>a <a href="http://msdn.microsoft.com/en-us/library/system.timezone.aspx" rel="nofollow noreferrer">TimeZone</a> object</li>
</ul>
<p>Not sure if there already is a CLR-provided data type that has that, but at least the TimeZone component is already available.</p>
| 30,597 |
<p>I am trying to construct a way to keep certain hard drive partitions/usb drives from being accessed for security reasons (protecting intellectual property). I was thinking that when windows attempts to access the "locked down drive/usb" the attempted is halted and returns something like "drive inaccessible" or something. It's just an idea, anyone thing it is plausible/possible? If so, any pointers?</p>
<p>C/C++</p>
<p>-Thanks</p>
| <p>You will need to write a <a href="http://en.wikipedia.org/wiki/Filter_driver" rel="nofollow noreferrer">filter driver</a> to achieve your goal. You will need to put your driver somewhere in disk driver stack and fail the IRP_MN_START_DEVICE for the drive/partition you want to block. </p>
<p>You will need <a href="http://www.microsoft.com/whdc/ddk/winddk.mspx" rel="nofollow noreferrer">Windows Driver Kit</a> to write drivers. There is a sample of filter driver in the WDK. This <a href="http://www.osronline.com/cf.cfm?PageURL=showlists.CFM?list=NTDEV" rel="nofollow noreferrer">mailing list</a> as a very useful and if you will search the archives you will find a lot of information about disk filter drivers.<br>
A good article about writing filter drivers is <a href="http://www.osronline.com/article.cfm?article=446" rel="nofollow noreferrer">here</a>, i think you will need to register to read, but if you want to write driver you should be registered on this site.<br>
Relevant book list can be found <a href="http://www.amazon.com/Windows-Kernel-Programming-Collection/lm/R1UMVPGFE45T4U" rel="nofollow noreferrer">here</a>.</p>
| <p>You need to encrypt the drives, anything else would allow attackers to just attach the drive to another machine and extract the contents.</p>
<p>You shouldn't implement encryption yourself - it's much better to rely on someone else's reviewed code. I suggest <a href="http://www.truecrypt.org/" rel="nofollow noreferrer">TrueCrypt</a> for encrypting your drives.</p>
<p>Then maybe you want to put a hook in your application to prompt for the password when it wants to access the encrypted data. Or you install TrueCrypt on the machine, and make the user connect the drive when they want to access the data, depending on the precise way of working with the data.</p>
| 25,953 |
<p>I have a C project where all code is organized in <code>*.c</code>/<code>*.h</code> file pairs, and I need to define a constant value in one file, which will be however also be used in other files. How should I declare and define this value?</p>
<p>Should it be as <code>static const ...</code> in the <code>*.h</code> file? As <code>extern const ...</code> in the <code>*.h</code> file and defined in the <code>*.c</code> file? In what way does it matter if the value is not a primitive datatype (<code>int</code>, <code>double</code>, etc), but a <code>char *</code> or a <code>struct</code>? (Though in my case it is a <code>double</code>.)</p>
<p>Defining stuff inside <code>*.h</code> files doesn't seem like a good idea generally; one should declare things in the <code>*.h</code> file, but define them in the <code>*.c</code> file. However, the <code>extern const ...</code> approach seems inefficient, as the compiler wouldn't be able to inline the value, it instead having to be accessed via its address all the time.</p>
<p>I guess the essence of this question is: Should one define <code>static const ...</code> values in <code>*.h</code> files in C, in order to use them in more that one place?</p>
| <p>The rule I follow is to only declare things in H files and define them in C files. You can declare and define in a single C file, assuming it will only be used in that file.</p>
<p>By declaration, I mean notify the compiler of its existence but don't allocate space for it. This includes <code>#define</code>, <code>typedef</code>, <code>extern int x</code>, and so on.</p>
<p>Definitions assign values to declarations and allocate space for them, such as <code>int x</code> and <code>const int x</code>. This includes function definitions; including these in header files frequently lead to wasted code space.</p>
<p>I've seen too many junior programmers get confused when they put <code>const int x = 7;</code> in a header file and then wonder why they get a link error for <code>x</code> being defined more than once. I think at a bare minimum, you would need <code>static const int x</code> so as to avoid this problem.</p>
<p>I wouldn't be too worried about the speed of the code. The main issue with computers (in terms of speed and cost) long ago shifted from execution speed to ease of development.</p>
| <p>I can give you an indirect answer. In C++ (as opposed to C) <code>const</code> implies <code>static</code>. Thatis to say in C++ <code>static const</code> is the same thing as <code>const</code>. So that tells you how that C++ standards body feels about the issue i.e. all <code>const</code>s should be static.</p>
| 46,298 |
<p><strong>Is there a tool out there for visualizing dynamic call graphs?</strong> I saw a reference to one for Visual Basic 6 but I'd like one for .NET.</p>
<p><strong>If I had to build a visualizer myself should I bother with the <em>.NET profiling API</em> or should I do something with <em>Mono.Cecil</em>?</strong> I started writing a CLI runtime with Cecil, but I guess it'd be easier if I just injected call-graph recording calls in the assemblies, although since I don't know the execution route ahead of time and would have to instrument everything.</p>
| <p>Maybe this open source project on CodePlex could help as starting point:</p>
<p><strong>SequenceViz</strong></p>
<p><a href="http://www.codeplex.com/sequenceviz" rel="nofollow noreferrer">http://www.codeplex.com/sequenceviz</a></p>
<p><em>"SequenceViz is a tool to generate sequence diagrams by reverse engineering .NET Assemblies. Although it does a little more than that in the later versions."</em></p>
<p>There is a standalone version and an implementation as reflector-plugin.</p>
<p><a href="http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=sequenceviz&DownloadId=44432" rel="nofollow noreferrer">alt text http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=sequenceviz&DownloadId=44432</a></p>
| <p>You coud use <a href="http://nprof.sourceforge.net/Site/Description.html" rel="nofollow noreferrer"><strong>NProf</strong></a>, an open source project on Sourceforge. It allows you to <strong>extend the default GUI with new visualization tools</strong>.</p>
<p><em>"nprof is designed to be not only a fully-fledged profiler for .NET applications, but also a complete API that can be used to build other profiler front-ends, as well as extend the default GUI with new visualization tools."</em></p>
| 45,394 |
<p>I'm just starting to wean myself from ASP.NET UpdatePanels. I'm using jQuery and jTemplates to bind the results of a web service to a grid, and everything works fine. </p>
<p>Here's the thing: I'm trying to show a spinner GIF while the table is being refreshed (à la UpdateProgress in ASP.NET) I've got it all working, except that the spinner is frozen. To see what's going on, I've tried moving the spinner out from the update progress div and out on the page where I can see it the whole time. It spins and spins until the refresh starts, and stays frozen until the refresh is done, and then starts spinning again. Not really what you want from a 'please wait' spinner!</p>
<p>This is in IE7 - haven't had a chance to test in other browsers yet. Any thoughts? Is the ajax call or the client-side databinding so resource-intensive that the browser is unable to tend to its animated GIFs?</p>
<h3>Update</h3>
<p>Here's the code that refreshes the grid. Not sure if this is synchronous or asynchronous.</p>
<pre><code>updateConcessions = function(e) {
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: "{'Countries':'ga'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
applyTemplate(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
applyTemplate = function(msg) {
$('div#TemplateTarget').setTemplate($('div#TemplateSource').html());
$('div#TemplateTarget').processTemplate(msg);
}
</code></pre>
<h3>Update 2</h3>
<p>I just checked the <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options" rel="noreferrer">jQuery documentation</a> and the <code>$.ajax()</code> method is asynchronous by default. Just for kicks I added this</p>
<pre><code>$.ajax({
async: true,
...
</code></pre>
<p>and it didn't make any difference.</p>
| <p>It's not the Ajax call that's freezing the browser. It's the success handler (applyTemplate). Inserting HTML into a document like that can freeze IE, depending on how much HTML there is. It's because the IE UI is single threaded; if you notice, the actual IE menus are frozen too while this is happening.</p>
<p>As a test, try:</p>
<pre><code>applyTemplate = function(msg) {
return;
}
</code></pre>
| <p>Browsers are single-threaded and multi-threaded.</p>
<p>For any browser :
When you a called a function that contains a nested ajax function</p>
<p>java/servlet/jsp/Controller >
keep Thread.sleep(5000); in servlet to understand the async in ajax when
true or false.</p>
<pre><code> function ajaxFn(){
$('#status').html('WAIT... <img id="theImg" src="page-loader.gif" alt="preload" width="30" height="30"/>');
$('#status').css("color","red");
$.ajax({
url:"MyServlet",
method: "POST",
data: { name: $("textarea").val(),
id : $("input[type=text]").val() },
//async: false,
success:function(response){
//alert(response); //response is "welcome to.."
$("#status").text(response);
$('#status').css("color","green");
},
complete:function(x,y){
//alert(y)
},
error:function(){
$("#status").text("?");
}
});
}
</code></pre>
| 23,248 |
<p>Recent conversations with colleagues have produced varying points of view on this matter. What say you, SO members?</p>
<p>I know, even the concept of scalability can be taken in so many different ways and contexts, but that was part of the discussion when this came up. Everyone seemed to have a different take on what scalability really means. I'm curious to see the varying takes here as well. In fact, I posted a <a href="https://stackoverflow.com/questions/214246/what-does-scalability-mean-to-you">question</a> just for that concept.</p>
| <p>I would guess that the best way to check is by writing benchmarks, but in my opinion LINQ has the possibility for optimizations that hand-writing similar code does not. I don't know how well it takes advantage of those yet.</p>
<p>LINQ lets you express what you want, not how to generate it. One obvious advantage is that LINQ is automatically parallelizable (see <a href="http://msdn.microsoft.com/en-us/magazine/cc163329.aspx" rel="nofollow noreferrer">PLINQ</a>).</p>
<p>Another advantage to LINQ is that it is lazy, so you can perform calculations, drawing from the collection as needed. You could hand-code an equivalent, but it may be much easier to get right in LINQ.</p>
| <p>Linq is scalabile in many ways.</p>
<p>One aspect is Specification implementation behind linq, which allows Expression to be interpreted to run out of process, in a different language (Linq2Sql, Linq2Hibernate), or in a distributed computing invironment such as a map-reduce cluster for that matter (<a href="http://research.microsoft.com/en-us/projects/dryadlinq/" rel="nofollow noreferrer">DryadLINQ</a>)</p>
<p>Another aspect is semantics that linq provides to the language. You can iterate through billions of objects without filling the collection in memory if your provider supports deferred loading or you can paralellize or optimize the query (PLINQ or i4o).</p>
| 26,338 |
<p>I realize this would violate convention, but I'm curious to know if you can do this through configuration.</p>
<p><strong>Edit: I understand why I wouldn't want to do this. BUT, I do want to understand the internals of this time of project.</strong></p>
| <p>No you cannot rename this folder and have it actually contain executable code. The web project system is hard coded to look for code in this folder and will not consider any other folder for raw code. </p>
| <p>I dont think this is posible, but why do you need to change it?</p>
| 31,218 |
<p>I have a bunch of tasks in a MySQL database, and one of the fields is "deadline date". Not every task has to have to a deadline date.</p>
<p>I'd like to use SQL to sort the tasks by deadline date, but put the ones without a deadline date in the back of the result set. As it is now, the null dates show up first, then the rest are sorted by deadline date earliest to latest.</p>
<p>Any ideas on how to do this with SQL alone? (I can do it with PHP if needed, but an SQL-only solution would be great.)</p>
<p>Thanks!</p>
| <p>Here's a solution using only standard SQL, not ISNULL(). That function is not standard SQL, and may not work on other brands of RDBMS.</p>
<pre><code>SELECT * FROM myTable
WHERE ...
ORDER BY CASE WHEN myDate IS NULL THEN 1 ELSE 0 END, myDate;
</code></pre>
| <pre><code>SELECT foo, bar, due_date FROM tablename
ORDER BY CASE ISNULL(due_date, 0)
WHEN 0 THEN 1 ELSE 0 END, due_date
</code></pre>
<p>So you have 2 order by clauses. The first puts all non-nulls in front, then sorts by due date after that</p>
| 18,224 |
<p>I know that lots of web hosting providers are offering FreeBSD, but how good is FreeBSD as a development platform?</p>
<p>Specifically, is Java 1.6 available in it?
Is there somthing specific that it offers with regard to tools that is not available under Linux?</p>
| <p>I've always found FreeBSD a wonderful secure hosting environment, but perhaps not the easiest development platform. You will have to dig a bit to get Java 1.6 up and running, though I think it will be doable. I hope you are familiar with emacs or vi. The ports system will afford you access to many pieces of software, but they will have to be compiled from source code. If you are familiar with standard Unix command line tools and the command line itself, you should have no problems with FreeBSD.</p>
<p>Alan</p>
| <p><a href="https://www.truenas.com/trueos-discontinuation/" rel="nofollow noreferrer">TrueOS</a> has been discontinued. I'm kinda surprised... would have been interesting to have some synergy between TrueNAS and TrueOS.</p>
| 35,630 |
<p>I am making a new concept in searching, I am calling lt as WikiRank,
In this , a extension will be installed on firefox browser. This extension will see watch the user activity, and he will send visiting url and its visit time also user can give ranking to the material also. So in nutshell,. there will not be any change in user interface, User will use his search any engine but we will collect all of searched website.
So, soon I will be having data such as, How many hour the world has spent on a particular idea and combined user rank.
This database will be useful for getting better search result.
How can i make this website?
Is the idea is good or unique?
How can I prevent bots or AI agent to give false rank ? May be one captcha at the end of submission of all links ???</p>
| <p>It seems that you're re-inventing a wheel... again. Did you check any <a href="http://en.wikipedia.org/wiki/Alexa_Internet" rel="nofollow noreferrer">prior art</a> (there are more obviously) on what you're planning to do? From your description it does not sound like a 'new' concept to me at all.</p>
| <p>Mainly I want to collect page visit time per url of user. Also user can send optional rank (1-10) about the content of the page.</p>
| 16,865 |
<p>When C# 4.0 comes out and we have the dynamic keyword as described in this <a href="http://channel9.msdn.com/pdc2008/TL16/" rel="noreferrer">excellent presentation by Anders Hejlsberg</a>, (C# is evolving faster than I can keep up.. I didn't have much time to acquaint myself with the var keyword)</p>
<p>Would I still need the var keyword ? Is there anything that var can do.. that dynamic can't?</p>
<pre><code>var x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x
dynamic x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x
</code></pre>
| <p>No, they're very different.</p>
<p><code>var</code> means "infer the type of the variable at compile-time" - but it's still entirely statically bound.</p>
<p><code>dynamic</code> means "assume I can do anything I want with this variable" - i.e. the compiler doesn't know what operations are available, and the DLR will work out what the calls <em>really</em> mean at execution time.</p>
<p>I expect to use <code>dynamic</code> very rarely - only when I truly want dynamic behaviour:</p>
<ul>
<li><code>var</code> lets you catch typos etc at compile-time</li>
<li>statically bound code is always going to run faster than dynamically bound code (even if the difference becomes reasonably small)</li>
<li>statically bound code gives more compile-time support beyond just errors: you can find call hierarchies, refactoring will work better, Intellisense is available etc</li>
</ul>
| <p>Yes you will still need var:</p>
<p><strong>Var</strong> is a <em>variable</em> whose type will be inferred by the compiler.
<br>
<strong>dynamic</strong> will have its type assigned at runtime</p>
<p>So:</p>
<pre><code>Var i = "Hello World"
</code></pre>
<p>will have its type inferred as a string type in doing so intellisence will give you all the methods that string can use like,</p>
<pre><code>i.Split("/")
</code></pre>
<p>Where as:</p>
<pre><code>dynamic i = "Hello World"
</code></pre>
<p>won't have its type inferred untill runtime because the complier dosn't know what type it is yet, but will still let you do:</p>
<pre><code>i.Split("/")
</code></pre>
<p>but when it calls the method that you need it may fail because the type is wrong and the method isn't there.</p>
| 38,174 |