instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I'm not talking about making something that's outright disproportionate of course. I've been working in Blender and I've use Absolute grid Snap to snap my vertices to the grid. The problem is that it (didn't seem) to always work perfectly for centimeters, and seemed to work better for meters.
(edit: I've learned what the problem was and it was simply the placement of the vertices in side view, being at slightly different elevations. I'm going to emphasize that the difference was very slight. It was just enough to show up in the measurements. When I switched from front view to side view I was able to adjust the elevation to the grid and that fixed the problem.)</p>
|
<p>It depends on what you're working on. If you're producing mechanical/functional parts (even if that just means having to connect to one another or to some non-printed part), 3 mm (0.3 cm) error is almost surely going to prevent them from working. Even 0.3 mm error might be a problem.</p>
<p>If you're doing standalone prints that don't have to interface with anything else, e.g. art, non-articulated figurines, etc., then it becomes just a question of what's visually acceptable, and that's a matter both of scale and of the detail level you want. For typical tabletop-RPG scale, for example, most of the acutal visual features are going to be smaller than 3 mm, so that much error is not going to work out. It might work for large busts, though.</p>
<p>In any case, I would recommend trying to solve the underlying problem. Either change your grid snap, or work at a larger scale and just scale down the final model.</p>
|
<p>Welcome to the SE 3D Printing site. Your questions are also welcome, as well as your answers to your questions, and the questions of others.</p>
<p>I am not a Blender user. I use CAD systems because most of what I do I want to have a certain dimensional precision.</p>
<p>If the problem is as simple as "The overall object is designed to be 7.345 centimeters but I want it to be 7.000 centimeters," you can fix that when you print the model. Use the scaling feature of your slicer to scale by <span class="math-container">$(7.000/7.345)$</span> or <span class="math-container">$95.303\%$</span>. It will print as the size you want.</p>
<p>The problem may be deeper, though, in that you may be having trouble setting points within the model where you want them. In that case, the snap-to-grid feature is distorting your model's appearance and geometry, and there is nothing you can do to fix it.</p>
<p>If it can't be fixed by scaling, I would suggest that you should either turn off the snap-to features or set up a grid that matches the granularity you actually want for your design.</p>
| 1,368
|
<p>I'd like to write Python scripts that drive Visual Studio 2008 and Visual C++ 2008. All the examples I've found so far use <code>win32com.client.Dispatch</code>. This works fine for Excel 2007 and Word 2007 but fails for Visual Studio 2008:</p>
<pre><code>import win32com.client
app1 = win32com.client.Dispatch( 'Excel.Application' ) # ok
app2 = win32com.client.Dispatch( 'Word.Application' ) # ok
app3 = win32com.client.Dispatch( 'MSDev.Application' ) # error
</code></pre>
<p>Any ideas? Does Visual Studio 2008 use a different string to identify itself? Is the above method out-dated?</p>
|
<p>I don't know if this will help you with 2008, but with Visual Studio 2005 and win32com I'm able to do this:</p>
<pre><code>>>> import win32com.client
>>> b = win32com.client.Dispatch('VisualStudio.DTE')
>>> b
<COMObject VisualStudio.DTE>
>>> b.name
u'Microsoft Visual Studio'
>>> b.Version
u'8.0'
</code></pre>
<p>Unfortunately I don't have 2008 to test with though.</p>
|
<p>As of year 2013, better option can be to script <code>Visual Studio</code> via <code>IronPython</code> cause better <code>CLR</code>/<code>COM</code> and other MS stuff integration:</p>
<pre><code>
import clr
import System
t = System.Type.GetTypeFromProgID("AutoItX3.Control")
oAutoItX = System.Activator.CreateInstance(t)
oAutoItX.Opt("WinTitleMatchMode", 2)
width = oAutoItX.WinGetClientSizeWidth("IronPythonApplication1 - Microsoft Visual Studio (Administrator)")
height = oAutoItX.WinGetClientSizeHeight("IronPythonApplication1 - Microsoft Visual Studio (Administrator)")
print width, height
</code></pre>
| 27,442
|
<p>Question says it all, I've got a 500,000 line file that gets generated as part of an automated build process on a Windows box and it's riddled with <strong>^M</strong>'s. When it goes out the door it needs to <strong>*nix</strong> friendly, what's the best approach here, is there a handy snippet of code that could do this for me? Or do I need to write a little C# or Java app?</p>
|
<p>Here is a Perl one-liner, taken from <a href="http://www.technocage.com/~caskey/dos2unix/" rel="noreferrer">http://www.technocage.com/~caskey/dos2unix/</a></p>
<pre><code>#!/usr/bin/perl -pi
s/\r\n/\n/;</code></pre>
<p>You can run it as follows:</p>
<pre><code>perl dos2unix.pl < file.dos > file.unix
</code></pre>
<p>Or, you can run it also in this way (the conversion is done in-place):</p>
<pre><code>perl -pi dos2unix.pl file.dos
</code></pre>
<p>And here is my (naive) C version:</p>
<pre><code>#include <stdio.h>
int main(void)
{
int c;
while( (c = fgetc(stdin)) != EOF )
if(c != '\r')
fputc(c, stdout);
return 0;
}
</code></pre>
<p>You should run it with input and output redirection:</p>
<pre><code>dos2unix.exe < file.dos > file.unix
</code></pre>
|
<p>If it is just one file I use notepad++. Nice because it is free. I have cygwin installed and use a one liner script I wrote for multiple files. If your interest in the script leave a comment. (I don't have it available to me a this moment.)</p>
| 40,372
|
<p>I work in an multi-site environment that's currently using Rational ClearCase for source control and Rational ClearQuest for issue tracking (I accept your condolences ahead of time). As a rough estimate I would say this is supporting 200 engineers.</p>
<p>How would you effectively migrate this SCM methodology to a comparative, all Open Source tool suite? Not only would this save literally hundreds of thousands of dollars but I also believe it would improve developer productivity and very little downtime compared to the current system.</p>
<p>Platforms in use include Windows, Linux, UNIX and Solaris.</p>
|
<p>First, why do you think this would improve developer productivity? I haven't used ClearCase much, and ClearQuest not at all. What about these tools is hindering development?</p>
<p>Once you know what you want, you need to look at various tools. I'm fond of Subversion for SCM, as a general rule, but there are situations it isn't well suited for. I have no strong feelings on specific version tracking systems.</p>
<p>Bear in mind that migration is likely to be a really big project, depending on what you want to bring over from the Rational systems (checking everything out in ClearCase and starting entirely new projects in Subversion will be easy, but any history you want to keep is a lot more work), so there will be no immediate dollar savings. Moreover, switching tools is going to reduce developer productivity for a short time (possibly very short), so this is best seen as a long-term move. Make sure you get the tools you want up front, since you aren't going to want to do migrations very often.</p>
|
<p>Condolences are not required, it seems that if you are working in a large scale development over more than one site, then you have the right tools for the job.</p>
<p>Attempting to make Open Source SCM products work over various sites will be a very interesting challenge - I've not seen something that will work securely, reliably and without a horrendous amount of work (though I'd love to be proved wrong!).</p>
<p>Although your licenses do cost a considerable amount, you also have access to the IBM tech support (who I've found very useful very often). How much would it cost if your open-source environment crashed to it's knees for some reason and your support network consisted of you and your colleagues? 200 developers unable to work effectively? Erk.</p>
<p>I'd be interested to hear why you think it would improve developer productivity. Do they have specific gripes? What do they find is an issue? Could we help you from here work it out with them?</p>
<p>In my humble opinion, Open Source tools are perfect for small to medium sized projects without a relative amount of complexity. I feel what you are attempting to do will be folly.</p>
| 19,201
|
<p>Is this</p>
<pre><code>... T1 join T2 using(ID) where T2.VALUE=42 ...
</code></pre>
<p>the same as</p>
<pre><code>... T1 join T2 on(T1.ID=T2.ID) where T2.VALUE=42 ...
</code></pre>
<p>for all types of joins?</p>
<p>My understanding of <code>using(ID)</code> is that it's just shorthand for <code>on(T1.ID=T2.ID)</code>. Is this true?</p>
<p><br />
Now for another question:</p>
<p>Is the above the same as</p>
<pre><code>... T1 join T2 on(T1.ID=T2.ID and T2.VALUE=42) ...
</code></pre>
<p>This I don't think is true, but why? How does conditions in the on clause interact with the join vs if its in the where clause?</p>
|
<p>I don't use the USING syntax, since </p>
<ol>
<li>most of my joins aren't suited to it (not the same fieldname that is being matched, and/or multiple matches in the join) and</li>
<li>it isn't immediately obvious what it translates to in the case with more than two tables</li>
</ol>
<p>ie assuming 3 tables with 'id' and 'id_2' columns, does</p>
<pre><code>T1 JOIN T2 USING(id) JOIN T3 USING(id_2)
</code></pre>
<p>become</p>
<pre><code>T1 JOIN T2 ON(T1.id=T2.id) JOIN T3 ON(T1.id_2=T3.id_2 AND T2.id_2=T3.id_2)
</code></pre>
<p>or</p>
<pre><code>T1 JOIN T2 ON(T1.id=T2.id) JOIN T3 ON(T2.id_2=T3.id_2)
</code></pre>
<p>or something else again?</p>
<p>Finding this out for a particular database version is a fairly trivial exercise, but I don't have a large amount of confidence that it is consistent across all databases, and I'm not the only person that has to maintain my code (so the other people will also have to be aware of what it is equivalent to).</p>
<p>An obvious difference with the WHERE vs ON is if the join is outer:</p>
<p>Assuming a T1 with a single ID field, one row containing the value 1, and a T2 with an ID and VALUE field (one row, ID=1, VALUE=6), then we get:</p>
<pre><code>SELECT T1.ID, T2.ID, T2.VALUE FROM T1 LEFT OUTER JOIN T2 ON(T1.ID=T2.ID) WHERE T2.VALUE=42
</code></pre>
<p>gives no rows, since the WHERE is required to match, whereas</p>
<pre><code>SELECT T1.ID, T2.ID, T2.VALUE FROM T1 LEFT OUTER JOIN T2 ON(T1.ID=T2.ID AND T2.VALUE=42)
</code></pre>
<p>will give one row with the values</p>
<pre><code>1, NULL, NULL
</code></pre>
<p>since the ON is only required for matching the join, which is optional due to being outer.</p>
|
<p>You got the answers here, I need not add to it. Once I did a performance test on this, and USING consistently and always ran faster than ON. Yes I am talking about 10 to 20 ms :) MySQL I am talking about</p>
| 48,368
|
<p>I tried but I guess Message Box only works with win forms. What is the best alternative to use in web forms?</p>
|
<p>You can use <code>confirm</code> for yes/no questions and <code>alert</code> for "OK" messages in JavaScript.</p>
<p>The other alternative is to use JavaScript to pop up a new window that looks and acts like a message box. Modality in this case varied by browser. In Internet Explorer, the method </p>
<pre><code>window.showModalDialog(url,name,params)
</code></pre>
<p>will display a modal dialog. The Mozilla approach is to still use</p>
<pre><code>window.open(url,name,params)
</code></pre>
<p>but add <code>modal=yes</code> to the <code>params</code> list.</p>
|
<p>JavaScript:</p>
<pre><code>alert("This box has an OK button.");
</code></pre>
| 24,860
|
<p>What is the best way to keep a console application open as long as the CancelKeyPress event has not been fired?</p>
<p>I would prefer to not use Console.Read or Console.ReadLine as I do not want to accept input. I just want to enable the underlying application to print to the console event details as they are fired. Then once the CancelKeyPress event is fired I want to gracefully shut down the application.</p>
|
<p>I'm assuming that "gracefully shut down the application" is the part you are struggling with here. Otherwise your application will automatically exit on ctrl-c. You should change the title.</p>
<p>Here's a quick demo of what I think you need. It could be refined a bit more with use of locking and Monitors for notification. I'm not sure exactly what you need though, so I'll just pose this...</p>
<pre><code>class Program
{
private static volatile bool _s_stop = false;
public static void Main(string[] args)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
while (!_s_stop)
{
/* put real logic here */
Console.WriteLine("still running at {0}", DateTime.Now);
Thread.Sleep(3000);
}
Console.WriteLine("Graceful shut down code here...");
//don't leave this... demonstration purposes only...
Console.ReadLine();
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
//you have 2 options here, leave e.Cancel set to false and just handle any
//graceful shutdown that you can while in here, or set a flag to notify the other
//thread at the next check that it's to shut down. I'll do the 2nd option
e.Cancel = true;
_s_stop = true;
Console.WriteLine("CancelKeyPress fired...");
}
}
</code></pre>
<p>The _s_stop boolean should be declared volatile or an overly-ambitious optimizer might cause the program to loop infinitely.</p>
|
<p>Simply run your program or codes without debugging, on your keyboard key in <kbd>CTRL + f5</kbd> instead of F5(debugging).</p>
| 24,865
|
<p>What is the best OS for Java development? People from Sun are pushing the Solaris, yes Solaris have some extra features included in itself such as (dTrace, possibility for Performance tuning the JVM, etc.. ). Some friends of mine, had port their application on solaris, and they said to me that the performances was brilliant. I'm not happy with switching my OS, and use Solaris instead.</p>
<p>What were your experiences?</p>
|
<p>Of the three I've used (Mac OS X, Linux, Windows), I consider Linux the best place to do Java development.</p>
<p>My primary personal machine is a Mac, and I've done quite a lot of Java development there and been happy with it. Unfortunately, however, Apple lags behind the official JDK releases and you're pretty much limited to the few versions they choose to provide. </p>
<p>My employer-provided machine is an old P4 crate from HP which I use mostly to keep my feet warm. The real work occurs "Oberon", on a 2.6 GHz quad-core running <em>Ubuntu 8.04</em> in 32-bit mode [1]. The two advantages I notice day-to-day compared with Windows are:</p>
<ol>
<li>A powerful command line, which helps me automate the boring little stuff.</li>
<li><strong>Far</strong> superior file system performance. (I'm currently using EXT3 because I'm becoming conservative in my old age. I used ReiserFS previously, which was even faster for the sorts of operations one typically performs on large workspaces checked out of subversion.)</li>
</ol>
<p>You can get those advantages from a mac too, but Linux offers another nice bonus:</p>
<ul>
<li>Remote X11: Before my $EMPLOYER provided e-mail and calendar via web, I had to be on the Windows box to read my mail and see my meetings, so I used Cygwin's X11. This allowed my to run the stuff on Linux but display it on my windows desktop.</li>
</ul>
<hr>
<p>[1] I used to run Ubuntu in 64-bit mode, but I had no end of trouble. (Mixing 64-bit and 32-bit is something Mac OS X does <em>much</em> better.) 7.04 worked fine running 32-bit applications on the 64-bit kernel. 7.10 broke the <code>linux32</code> script and the ability to install new 32-bit applications though old ones continued to (mostly) run. 8.04 killed 32-bit java by making it impossible to connect to the network from a 32-bit JVM (no more updates for Eclipse). Running Eclipse 64-bit didn't work reliably. The then current version of oXygen would only run (grudgingly) under the IBM 64-bit VM which would work for about 10 minutes until it stopped getting keyboard events. I finally gave up in frustration and used my Mac for a few months until I had enough slack time to do a 32-bit install of 8.04 on the linux box. Now everything works again and I'm quite happy. </p>
|
<p>I have had success before doing Java development in Windows with Eclipse. Sounds like you are also asking about deployment/hosting. Whichever OS is best to run your application on should not really predicate what OS you use to develop the application.</p>
| 31,964
|
<p>I have a class on which I want to allow several (~20+) configuration options.
Each option turns on or off a piece of functionality, or otherwise alters operations.
To facilitate this, I coded a separate options class with default values. However, I had to litter my code with guard conditions to determine how methods should behave. I am almost done, but now the code seems to smell.</p>
<p>Is there a preferred method/pattern to implement a class like this?</p>
<p><strong>EDIT:</strong> More specifically, I am working on a parsing class.
Each option configures mutually exclusive portions of the basic parsing algorithm.
For example I have several areas in my class that look like the below:</p>
<pre><code> if (this.Option.UseIdAttribute)
attributeIDs = new Hashtable();
else
attributeIDs = null;
public Element GetElementById(string id)
{
if (string.IsNullOrEmpty (id))
throw new ArgumentNullException("id");
if (attributeIDs == null)
throw new Exception(ExceptionUseIdAttributeFalse);
return attributeIDs[id.ToLower()] as Element;
}
</code></pre>
|
<p>How about the <a href="http://en.wikipedia.org/wiki/Decorator_Pattern" rel="nofollow noreferrer">Decorator pattern</a>? It's designed for dynamically adding behavior to a class.</p>
|
<p>I'm thinking of a <a href="http://www.patterndepot.com/put/8/Behavioral.html" rel="nofollow noreferrer">Command</a> pattern.</p>
<p>It would look something like:</p>
<pre><code> public class MyClass {
interface Command {
void execute(int a);
}
static class DoThisSimpleCommand implements Command {
void execute(int a) {
// do this simple
}
}
static class DoThisAnotherWayCommand implements Command {
void execute(int a) {
// do this another way
}
}
private Command doThisCommand;
MyClass() {
initDoThisCommand();
}
private void initDoThisCommand() {
if (config.getDoThisMethod().equals("simple")) {
doThisCommand = new DoThisSimpleCommand();
} else {
doThisCommand = new DoThisAnotherWayCommand();
}
}
void doThis(int a) {
doThisCommand.execute(a);
}
}
</code></pre>
<p>In other words; you delegate responsibility to an implementation which you instantiate on construction. Now your doThis just delegates and the actual functionality is cleanly stowed away in it's own class. </p>
| 26,414
|
<p>I can't seem to retrieve the AlternateView from System.Net.Mail.AlternateView.</p>
<p>I have an application that is pulling email via POP3. I understand how to create an alternate view for sending, but how does one select the alternate view when looking at the email. I've have the received email as a System.Net.MailMessage object so I can easily pull out the body, encoding, subject line, etc. I can see the AlternateViews, that is, I can see that the count is 2 but want to extract something other than the HTML that is currently returned when I request the body.</p>
<p>Hope this makes some amount of sense and that someone can shed some light on this. In the end, I'm looking to pull the plaintext out, instead of the HTML and would rather not parse it myself.</p>
|
<p>Mightytighty is leading you down the right path, but you shouldn't presume the type of encoding. This should do the trick:</p>
<pre><code>var dataStream = view.ContentStream;
dataStream.Position = 0;
byte[] byteBuffer = new byte[dataStream.Length];
var encoding = Encoding.GetEncoding(view.ContentType.CharSet);
string body = encoding.GetString(byteBuffer, 0,
dataStream.Read(byteBuffer, 0, byteBuffer.Length));
</code></pre>
|
<p>Its not immediately possible to parse an email with the classes available in the System.Net.Mail namespace; you either need to create your own MIME parser, or use a third party library instead.</p>
<p>This great Codeproject article by Peter Huber SG, entitled <a href="http://www.codeproject.com/KB/IP/Pop3MimeClient.aspx" rel="nofollow noreferrer">'POP3 Email Client with full MIME Support (.NET 2.0)'</a> will give you an understanding of how MIME processing can be implemented, and the related RFC specification articles. </p>
<p>You can use the Codeproject article as a start for writing your own parser, or appraise a library like <a href="http://anmar.eu.org/projects/sharpmimetools/" rel="nofollow noreferrer">SharpMimeTools</a>, which is an open source library for parsing and decoding MIME emails.</p>
<p><a href="http://anmar.eu.org/projects/sharpmimetools/" rel="nofollow noreferrer">http://anmar.eu.org/projects/sharpmimetools/</a></p>
<p>Hope this helps!</p>
| 37,202
|
<p>I need to decide on a GUI/Widget toolkit to use with Python for a new project. The target platforms will be Linux with KDE and Windows XP (and probably Vista). What Python GUI toolkit looks best and consistent with the native look and feel of the run time platform?</p>
<p>If possible, cite strengths and weaknesses of the suggested toolkit.</p>
<p>Thank you,</p>
<p>Luis</p>
|
<p>Python binding of Wx is very strong since at least one of the core developer is a python guy itself. WxWdgets is robust, time proven stable, mature, but also bit more than just GUI. Even is a lot is left out in WxPython - because Python itself offers that already - you might find that extra convenient for your project. Wx is the fastest especially on Win, because it lets render the OS and yes WxLicense is de facto LGPL. With XRC you have also a way like Glade to click you to a UI that you can reuse by different projects and languages. What is one major reason for me to use Wx is the fast and helping mailing list, never seen a flamewar, you get even often answers from core developers there, like the notorious vadim zeitlin++. The only thing con to Wx is the API that once grew out of MS MFC and has still its darker(unelegant) corners, but with every version you have some improvements on that as well.</p>
<p>QT done some nice stuff, especially warping the language but under python that don't count. They invented also a lot of extra widgets. In wx you have also combined, more complex widgets like e.g. for config dialog, but that goes not that far as in QT. </p>
<p>And you could of course use GTK. almost no difference under linux to Wx but a bit alien and slower under win. but also free.</p>
|
<p>Like others said, PyQt or wxPython... The technical difference between the two is more or less imaginary - it's a question of your comfort with the toolkit that matters, really.</p>
| 47,060
|
<p>What's the simplest-to-use techonlogy available to save an arbitrary Java object graph as an XML file (and to be able to rehydrate the objects later)?</p>
|
<p>The easiest way here is to serialize the object graph.
Java 1.4 has built in support for serialization as XML.</p>
<p>A solution I have used successfully is XStream (<a href="http://x-stream.github.io/)-" rel="nofollow noreferrer">http://x-stream.github.io/)-</a> it's a small library that will easily allow you to serialize and deserialize to and from XML.</p>
<p>The downside is you can only very limited define the resulting XML; which might not be neccessary in your case.</p>
|
<p>If you are really only interested in serializing your objects to a file and then deserializing them later, then you might check out YAML instead of XML. YAML is much easier to work with than XML and the output files are very human-readable (which may or may not be a requirement). Check out <a href="http://yaml.org/" rel="nofollow noreferrer">yaml.org</a> for more information. I've used <a href="http://jyaml.sourceforge.net/" rel="nofollow noreferrer" title="JYAML">JYAML</a> successfully on a recent project.</p>
| 8,814
|
<p>From the Apple <a href="http://developer.apple.com/internet/safari/faq.html" rel="noreferrer">developer faq</a></p>
<blockquote>
<p>Safari ships with a conservative
cookie policy which limits cookie
writes to only the pages chosen
("navigated to") by the user.</p>
</blockquote>
<p>By default Safari only allows cookies from sites you navigate to directly. (i.e. if you click on links with the url of that domainname).</p>
<p>This means that if you load a page from your own site with an iFrame with a page from another site, that the other site is not able to set cookies. (for instance, a ticketshop). As soon as you have visited the other domain directly, the other site is able to access and change its own cookies. </p>
<p>Without having access to code on the other site, how can i make the user-experience as inobtrusive as possible?</p>
<p>Is there a (javascript?) way to check if the other site's cookies
are already set, and accordingly, show a direct link to the other site first, if needed?</p>
<p>Update:</p>
<p>The HTML5 feature 'window.postmessage' seems to be a nice solution.<br>
There are some jQuery libraries that might help, and compatible with most recent browsers.<br>
In essence, the iFrame document sends messages, with Json, thru the window element.</p>
<p>The very nice <a href="http://postmessage.freebaseapps.com" rel="noreferrer">Postmessage-plugin</a>, by daepark, which i got working.<br>
and another <a href="http://benalman.com/projects/jquery-postmessage-plugin/" rel="noreferrer">jQuery postMessage</a>, by Ben Alman i found, but haven't tested.</p>
|
<p>This is an issue known as Same Origin Policy. Essentially it is a security measure against creating security loopholes. </p>
<p>When you have an iframe that points to a page on your own domain, JavaScript can access both the page you're on and the page within the Iframe. This is an acceptable parent to child and child to parent relationship.</p>
<pre><code> (parent doc) (iframe doc)
HTML --> IFRAME <-- HTML
^--------|---------^
</code></pre>
<p>However, once you have a file pointing to an external page, SOP comes into play and haults any information passing between the parent page and the iframe page.</p>
<pre><code> (parent doc) (iframe doc)
HTML --> IFRAME <-- HTML
X
</code></pre>
<p>Check out this post about iframe communication, it makes a lot of sense!
<a href="https://stackoverflow.com/questions/153152/resizing-an-iframe-based-on-content">Stackoverflow post</a></p>
<p>These links really help too!</p>
<p><strong>1)</strong> <a href="http://msdn.microsoft.com/en-us/library/bb735305.aspx" rel="nofollow noreferrer">Secure Cross-Domain Communication in the Browser</a><br/>
<strong>2)</strong> <a href="http://en.wikipedia.org/wiki/Same_origin_policy" rel="nofollow noreferrer">wiki SOP or Same Origin Policy</a></p>
<p>Good luck!</p>
|
<p><a href="http://saizai.livejournal.com/897522.html" rel="nofollow noreferrer">This page</a> suggests that you place some javascript in your pages which detects the absence of an always-there cookie. When it finds that the cookie has not been set, it posts the required session data to a page which sets the cookie, and redirects you back to the originating page. </p>
<p>Apparently the POST is enough to satisfy Safari's 'have I navigated to this domain' test, so from then on it accepts cookies from that domain.</p>
<p>Of course, it's not the nicest of code, but may well solve your problem.</p>
| 20,759
|
<p>Let's say I have an array of lots of values (C++ syntax, sorry):</p>
<pre><code>vector<double> x(100000);
</code></pre>
<p>This array is sorted such that <code>x[n] > x[n-1]</code>.</p>
<p>I would like a function to retrieve an array of all values in the range [a, b] (that's inclusive). Some interface like:</p>
<pre><code>void subarray(const double a, const double b, vector<double> &sub) {
...
}
</code></pre>
<p>When this function completes, <code>sub</code> will contain the <code>n</code> values that fell in the range [a, b].</p>
<p>Of course a linear search is easy:</p>
<pre><code>void subarray(const double a, const double b, vector<double> &sub) {
for (size_t i = 0; i < data.size(); i++) {
if (a <= data[i] && data[i] <= b) {
sub.push_back(data[i]);
}
}
}
</code></pre>
<p>However, because <code>data</code> is sorted, I should be able to do this much faster using a binary search. Who wants to take a stab at it? Any language is permitted!</p>
|
<p>What you're asking is a bit confusing regarding the the exact range properties and the types. However, you can tweak the following C++ code to suit your needs. The basic intuition is to use lower_bound and upper_bound to find the positions in the array that delineate the range you're looking for.</p>
<pre><code>void subarray(const double a, const double b, vector <double> &sub, vector <int> pn) {
vector <int>::const_iterator begin, end;
begin = lower_bound(pn.begin(), pn.end(), a);
end = upper_bound(pn.begin(), pn.end(), b);
sub.insert(sub.begin(), begin, end);
}
</code></pre>
|
<p>You already appear to know that a binary search can be used to find the range, and implementations of those are easily found.</p>
<p>Everything else is just getting trivial array manipulation.</p>
| 32,657
|
<p>Just a quick question.</p>
<p>I'm looking for a simple strip chart (aka. graphing) control similar to the windows task manager 'Performance' view. And have found a few, but they all rely on MFC or .NET :(</p>
<p>Am hoping that someone here might have or know where to get a simple strip chart Win32 control that is not MFC.</p>
<p>Thanks.</p>
|
<p>If you have to go the roll-your-own route look at the polyline GDI call. That can draw the entire line for you in one call. </p>
<p>I work on a system that draws charts with custom code (no 3rd party controls, all win32 GDI). It sounds really hard, but it isn't that bad.</p>
<p>A little math to map the points from your coordinate space to the device context, drawing gridlines/backgrounds, and Ployline. Done! ;)</p>
<p>Heck you can use GDI mapping modes to make the math easy (but I wouldn't).</p>
|
<p>I don't think there is a standard one in the Win32 common controls library. You'll either have to use someone else's widget library, or roll your own using GDI to draw the graphs. It probably isn't too difficult to roll your own - just create a bitmap control, and set the image every time your data updates to a graph that you draw in memory.</p>
| 16,201
|
<p>I've googled around for this, but I still have trouble relating to what Django defines as "apps". </p>
<p>Should I create a new app for each piece of functionality in a site, even though it uses models from the main project? </p>
<p>Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality together with the "main project" or other apps?</p>
|
<p>James Bennett has a wonderful <a href="http://www.b-list.org/weblog/2008/mar/15/slides/" rel="noreferrer">set of slides</a> on how to organize reusable apps in Django.</p>
|
<p>An 'app' could be many different things, it all really comes down to taste. For example, let's say you are building a blog. Your app could be the entire blog, or you could have an 'admin' app, a 'site' app for all of the public views, an 'rss' app, a 'services' app so developers can interface with the blog in their own ways, etc.</p>
<p>I personally would make the blog itself the app, and break out the functionality within it. The blog could then be reused rather easily in other websites.</p>
<p>The nice thing about Django is that it will recognize any models.py file within any level of your directory tree as a file containing Django models. So breaking your functionality out into smaller 'sub apps' within an 'app' itself won't make anything more difficult.</p>
| 8,976
|
<p>Parsing a text file in vb.net and need to locate the latitude and longitude in these two sections of text. The patter is 6 digits space 7 digits (364800 0953600). The samples are from two different map files and have slightly differing formats.</p>
<pre><code>I 2H02 364800 0953600 ' SEC72 10496300-
I 2H05 360100 0953645 ' ZFW J602 ZME 2A93 10496400-
I 2H06 361215 0952400 ' SEC72 ZME 2A75 10496500-
I 2H07 361715 0951145 ' SEC27/72 ZME 2A78 10496600-
I 2H08 362025 0950100 ' TUL ZME 2A69 10496700-
I 2H10 360800 0952915 ' ZME 2A85 10496800-
I 2H11 362500 0955015 ' SEC62/72 10496900-
I 2H14 364145 0954315 ' TUL 10497000-
I A85A 'AL851 50591 REF 33393944
391500 0831100 ' 50591 REF 33393945
I A85B 'AL851 50591 REF 33393946
374500 0825700 ' 50591 REF 33393947
I A87A 'AL871 111592 REF 33393948
402050 0814420 ' 111592 REF 33393949
I A87B 'AL871 111592 REF 33393950
400449 0814400 ' 111592 REF 33393951
I A87C 'AL872 '030394 GDK 33393952
392000 0810000 ' '030394 GDK 33393953
</code></pre>
<p>Thanks,</p>
<p>Dave</p>
|
<pre><code>Dim matches As MatchCollection
Dim regex As New Regex("\d{6} \d{7}")
matches = regex.Matches(your_text_string)
</code></pre>
|
<p>Do a simple group capture. It appears your RegEx formula will be simple enough to handle both scenarios (be a little lose on the space detection). Then you can access the group properties of the match (either named or just basic index) and get the data you need.</p>
| 38,905
|
<p>I'd like to programatically determine the encoding of a page via JavaScript, or some other API from a browser. The reason I want this information is because I am attempting to fuzz major browsers on what character encodings they support, and obviously just because I sent the appropriate "Content-Type" doesn't mean that the browser will do the right thing with the encoding. Any other possible methods would be welcome, but I would rather not click "Page Info" for 50+ character encodings.</p>
|
<p>Javascript can only report some of the things that are going on. Most browsers won't expose enough useful settings to you for you to base any hardcore tests on. </p>
<p>There are things such as <code>document.inputEncoding</code>, <code>document.characterSet</code> (non IE), <code>document.charset</code>, and <code>document.defaultCharset</code> (IE) which might get you some of the way there. But these might be as flaky as the actual support. That is, if a browser "thinks" it supports an encoding but really doesn't, isn't that something you want to know?</p>
<p>I think your best bet is to set up a dynamic test page with some fairly difficult characters on it (or a really large test set), load test in a browser, have the browser report back browser id string, encoding settings, original encoding request, and contents of <code>testElement.innerHTML</code> which you can then verify against expected results. </p>
|
<p>The original answer is quite old now and support for <code>document.characterSet</code> has improved greatly.</p>
<pre><code>>>> document.characterSet
</code></pre>
<p>IE 11:</p>
<pre><code>"utf-8"
</code></pre>
<p>Firefox 52, Chrome 55 and Chrome on Android, Safari 10:</p>
<pre><code>"UTF-8"
</code></pre>
<p>So it seems that for most purposes you can rely on this information, fixing the different case. In my case it was useful to gather this info for tracking purposes.</p>
| 41,216
|
<p>In a .net 2 winforms application, what's a good way to set the culture for the entire application?<br>
Setting CurrentThread.CurrentCulture for every new thread is repetitive and error-prone.<br>
Ideally I'd like to set it when the app starts and forget about it.</p>
|
<p>The culture for a thread in .NET is the culture for the system (as viewed by a single application/process). There is no way to override that in .NET, you'll have to continue setting the CurrentCulture for each new thread.</p>
|
<p>You can set application current culture this way:</p>
<pre><code>static void Main()
{
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("fi-FI");
Application.CurrentCulture = cultureInfo;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
</code></pre>
<p>I'm not sure if it helps, because I have never tested it with threads.</p>
<p>edit: it doesn't work. I think you have to set current culture in every thread.</p>
| 11,865
|
<p>I am working on ASP.NET MVC.</p>
<p>in order to use AjaxHelper, I inserted two javascript files in the site.master as following.</p>
<pre><code><script src="../../Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
</code></pre>
<p>then I used AjaxHelper in view pages, but it did not work.</p>
<p>so, I changed order of javascript file as following.</p>
<pre><code><script src="../../Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
</code></pre>
<p>Then it worked :(</p>
<p>So, my question is that the order of JavaScript file effects to use AjaxHelper class?</p>
|
<p>Absolutely. The MVCAjax classes will need to reference the more generic Ajax classes. Therefore, the generic ones get referenced first</p>
|
<p>The MicrosoftMvcAjax.debug.jss file has code in it that references code in MicrosoftAjax.debug.js. Hence the order in which they are declared matters.</p>
| 49,773
|
<p>What does the pink color in Slic3r preview mean? Yellow is my model, green is support, and pink is..?</p>
<p>If the pink color is some kind of warning, how do I fix it?</p>
<p><a href="https://i.stack.imgur.com/2PIRU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2PIRU.jpg" alt="Illustration from preview"></a></p>
|
<p>In slic3r preview, salmon (pink) represents infill, yellow represents perimeters, and green represents support material, including skirt and brim.</p>
|
<p>Having had direct experience with Slic3r, I can offer up this information. Your model is composed of bottom layers, top layers, outside layers, infill, rafts, brims and perhaps something I've missed.</p>
<p>The program provides for color coding of these features. In the case of your image, the pink represents a top layer, but may also represent a type of infill, depending on "context."</p>
<p>Consider to slice the model, select the preview tab, which you have showing here, then using the slider control to the right of the image window. As you move it from bottom to top, you can observe the construction of the model and each feature as it appears, layer by layer.</p>
| 569
|
<p>I have a VB6 legacy program which I need to change. I am unable to run the program from the IDE. When I activate one of the forms in the IDE I get an error which refers me to an error log file. The log file has the following in it</p>
<p>"Cannot load control SSPanel; license not found"</p>
<p>The SSPanel is part the Sheridan 3D controls (THREED32.ocx) and the component is selected.</p>
<p>How can I fix the error?</p>
|
<p>The solution that worked for me was to execute the file VBCTRLS.REG on the installation disc (common/tools/VB/controls). It registered the control. I stopped getting the error and I was able to run the program from the IDE</p>
|
<p>If you have "Cannot load control <strong>SysInfo</strong>; license not found."</p>
<p>This reg fix the problem:</p>
<pre><code>[HKEY_CLASSES_ROOT\Licenses\E32E2733-1BC5-11d0-B8C3-00A0C90DCA10]
@="kmhfimlflmmfpffmsgfmhmimngtghmoflhsg"
</code></pre>
| 47,789
|
<p>Consider the following code in VB9:</p>
<pre><code>Dim text = "Line1<br/>Line2"
Dim markup = <span><%= text %></span>.ToString
</code></pre>
<p>While I was hoping markup would end up being <code><span>Line1<br/>Line2</span></code>, it actually evaluates to <code><span>Line1&lt;br/&gt;Line2</span></code>.</p>
<p>Is there any way to get the value of the variable not to be HTML encoded?</p>
<p>P.S.: This is an oversimplified example of what I'm trying to do. I know this could be rewritten a number of ways to make it work, but the way my code is constructed, un-encoding the variable would be optimal. If that's not possible, then I'll go down a different road.</p>
<p>More detail: The "text" is coming from a database, where a user can enter free-form text, with carriage returns. The output is HTML, so somehow I need to get the value from the database and convert the carriage returns to line breaks.</p>
|
<p>This behavior is "By Design." When embedding a string expression inside an XML literal the value will be escaped to be a legal string value. </p>
<p>To get the behavior you are looking for you'll need to be embedding an XElement/XNode within an XML literal. Take the following example. It will correctly keep the <code><br/></code> tag as an XElement.</p>
<pre><code>Dim text2 = <a>Line<br/>Line</a>
Dim markup2 = <span><%= text2 %></span>.ToString
</code></pre>
<p>One way to achieve this is to fake an XElement. To make the text a valid string, simply wrap it on both ends with a normal tag, <code><a></code> for example. This is now a parsable XML fragment. Once you have an XElement, it's easy to get the embedded behavior you are looking for</p>
<pre><code>Dim text = "Line1<br/>Line2"
Dim text2 = XElement.Parse("<a>" + text + "</a>")
Dim markup = <span><%= text2.Nodes %></span>.ToString
</code></pre>
|
<p>It can be done using XElementRaw.</p>
<pre><code>Dim markup = <span><%= text %></span>.ToHTML()
</code></pre>
<p>Here's the ToHTML() extension:</p>
<pre><code>''' <summary>
''' Convert an XElement to a string. Differences between this and .ToString():<br />
''' 1) Will not throw errors on invalid characters<br />
''' 2) Will not escape characters, such as &amp;<br />
''' 3) Will not include &lt;![CDATA[ ]]&gt; wrappers around text<br />
''' 4) Works with .XElementRaw( ) extension to add a "raw" string (i.e. malformed HTML) directly into the flow
''' </summary>
''' <param name="myElement"></param>
''' <returns></returns>
<Extension()>
Public Function ToHTML(ByVal myElement As XElement, Optional OmitXmlDeclaration As Boolean = True) As String
'set up XSL transform, set checkCharacters to false
Static firstTime As Boolean = True
Static xslt As Xsl.XslCompiledTransform = New Xsl.XslCompiledTransform()
Static settings As XmlWriterSettings
'if element is null then it cannot contain any HTML
If myElement Is Nothing Then Return ""
If firstTime Then
SyncLock xslt
If firstTime Then
Dim xslDefinition As XElement = <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output media-type="text/html" method="html" omit-xml-declaration="yes"/>
<xsl:template match="/|*|@*|comment()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="processing-instruction('pcr1Raw')">
<xsl:value-of select="." disable-output-escaping="yes"/>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="." disable-output-escaping="no"/>
</xsl:template>
</xsl:stylesheet>
xslt.Load(xslDefinition.CreateReader())
settings = xslt.OutputSettings.Clone() 'need clone or else most properties are readonly
settings.CheckCharacters = False
settings.DoNotEscapeUriAttributes = True
settings.NewLineOnAttributes = False
settings.NewLineHandling = NewLineHandling.None
settings.Indent = False
settings.WriteEndDocumentOnClose = False
settings.ConformanceLevel = ConformanceLevel.Fragment
firstTime = False
End If
End SyncLock
End If
'now run the actual transform
Dim sb = New Text.StringBuilder()
Using w = XmlWriter.Create(sb, settings)
xslt.Transform(myElement.CreateReader(), w)
End Using
If OmitXmlDeclaration = False Then
Dim decl As New XDeclaration("1.0", "utf-8", "yes")
Return decl.ToString() & vbCrLf & sb.ToString()
Else
Return sb.ToString()
End If
End Function
</code></pre>
| 37,824
|
<p>I have been looking at a few options for enabling localization and internationalization of a dynamic php application. There appears to be a variety of tools available such as gettext and Yahoo's R3 and I am interested in hearing from both developers and translators about which tools are good to use and what functionality is important in easing the task of implementation and translation.</p>
|
<p>PHP gettext implementation works very smoothly. And po files with po edit and gettext are about as good a way as you can get to deal with localization bearing in mind that no solution of this kind can completely handle the complexities of the various languages. For example, the gettext method is very good on plural forms, but nothing I've seen can handle things like conjugation.</p>
<p>For more info see my post here: <a href="https://stackoverflow.com/questions/39562/how-do-you-build-a-multi-language-web-site#41379">How do you build a multi-language web site?</a></p>
|
<p>Xataface can be used to quite easily internationalize an arbitrary PHP/MySQL application. It support translation of both your static text, and your database data. All you have to do is add a line or 2 of code to a couple of places in your application and it's good to go.</p>
<p><a href="http://xataface.com/documentation/tutorial/internationalization-with-dataface-0.6" rel="nofollow noreferrer"><a href="http://xataface.com/documentation/tutorial/internationalization-with-dataface-0.6" rel="nofollow noreferrer">http://xataface.com/documentation/tutorial/internationalization-with-dataface-0.6</a></a></p>
| 18,834
|
<p>I want to check if a given date is more than a month earlier than today's date using LINQ.</p>
<p>What is the syntax for this?</p>
<p>Thanks in advance.</p>
|
<p>I assume that you're talking about in the where clause. It's basically the same way you would compare two DateTime objects elsewhere.</p>
<pre><code>using (DataContext context = new DataContext()) {
var query = from t in context.table
where t.CreateDate.Date < DateTime.Today.AddMonths(-1)
select t;
}
</code></pre>
|
<p>If you don't want your code to throw </p>
<pre><code>LINQ to Entities does not recognize the method 'System.DateTime AddYears(Int32)' method, and this method cannot be translated into a store expression.
</code></pre>
<p>I would suggest using DbFunctions.AddYears. Also, if you are concerned only about dates and not the times, you could use DbFunctions.TruncateTime</p>
<p>Something like this-</p>
<pre><code>DbFunctions.TruncateTime(x.date) ==
DbFunctions.TruncateTime(DbFunctions.AddYears(DateTime.Today, 1))
</code></pre>
| 26,358
|
<p>I am working on an object factory to keep track of a small collection of objects. The objects can be of different types, but they will all respond to <code>createInstance</code> and <code>reset</code>. The objects can not be derived from a common base class because some of them will have to derive from built-in cocoa classes like <code>NSView</code> and <code>NSWindowController</code>.</p>
<p>I would like to be able to create instances of any suitable object by simply passing the desired classname to my factory as follows:</p>
<pre><code>myClass * variable = [factory makeObjectOfClass:myClass];</code></pre>
<p>The <code>makeObjectOfClass:</code> method would look something like this:</p>
<pre><code>- (id)makeObjectOfClass:(CLASSNAME)className
{
assert([className instancesRespondToSelector:@selector(reset)]);
id newInstance = [className createInstance];
[managedObjects addObject:newInstance];
return newInstance;
}</code></pre>
<p>Is there a way to pass a class name to a method, as I have done with the <code>(CLASSNAME)className</code> argument to <code>makeObjectOfClass:</code> above?</p>
<p>For the sake of completeness, here is why I want to manage all of the objects. I want to be able to reset the complete set of objects in one shot, by calling <code>[factory reset];</code>.</p>
<pre><code>- (void)reset
{
[managedObjects makeObjectsPerformSelector:@selector(reset)];
}</code></pre>
|
<p>You can convert a string to a class using the function: NSClassFromString</p>
<pre><code>Class classFromString = NSClassFromString(@"MyClass");
</code></pre>
<p>In your case though, you'd be better off using the Class objects directly.</p>
<pre><code>MyClass * variable = [factory makeObjectOfClass:[MyClass class]];
- (id)makeObjectOfClass:(Class)aClass
{
assert([aClass instancesRespondToSelector:@selector(reset)]);
id newInstance = [aClass createInstance];
[managedObjects addObject:newInstance];
return newInstance;
}
</code></pre>
|
<p>It sounds like you want something like:</p>
<pre><code>- (id)makeObjectOfClassNamed:(NSString *)className
{
Class klass = NSClassFromString(className);
assert([klass instancesRespondToSelector:@selector(reset)]);
id newInstance = [klass createInstance];
[managedObjects addObject:newInstance];
return newInstance;
}
</code></pre>
<p>This would assume a class method named <code>+createInstance</code>. Or you could just use <code>[[klass alloc] init]</code>.</p>
<p>To call it:</p>
<pre><code>MyClass *variable = [factory makeObjectOfClassNamed:@"MyClass"];
</code></pre>
<p>Depending on what you're trying to do, it might be better to pass around class objects than strings, e.g.:</p>
<pre><code>MyClass *variable = [factory makeObjectOfClass:[MyClass class]];
</code></pre>
| 40,743
|
<p>Have you ever been in a situation where a menu function you really really want to use but can't cause it's disabled or worse gone all together?</p>
<p>There is an argument for always leaving menus enabled and then display a message to a user explaining why a menu function can not be activated when they click on it. I think there is merit in this but maybe there is a cleverer way of addressing this issue. </p>
<p>I would be interested to hear what others think.</p>
|
<p>If you're refering to Joel's post <a href="http://www.joelonsoftware.com/items/2008/07/01.html" rel="noreferrer">Don't hide or disable menu items</a>, he <a href="https://stackoverflow.fogbugz.com/default.asp?W13086" rel="noreferrer">clarified in the StackOverflow podcast</a> that he intended that there be information - not a dialog - telling you why a menu item wouldn't do anything:</p>
<blockquote>
<p>So, the use-case I was thinking of was, you had mentioned that in the Windows Media Player, you can play things faster when you're listening to podcasts and so forth, and it'll speed them up. And when I looked in there, that was disabled. And I couldn't figure out how to enable it. And obviously the help file is no help--not that anybody reads help files, but even if you did you couldn't find the answer to that. And that was kind of frustrating, and I'd rather have that menu item be enabled and have it just tell me "I'm not going to do this right now because of the following reason. I refuse to do this." </p>
</blockquote>
|
<p>I've always believed that you should hide as much as you can. (Your application shouldn't be any more complex than what the user can/should do.)</p>
<p>If you display a menu option that a user shouldn't be using, they may click on it, but think your application is broken because nothing happens.</p>
<p>That's what I think at least...</p>
| 10,444
|
<p>I'm using C# and Microsoft.Jet.OLEDB.4.0 provider to insert rows into an Access mdb.</p>
<p>Yes, I know Access sucks. It's a huge legacy app, and everything else works OK.</p>
<p>The table has an autonumber column. I insert the rows, but the autonumber column is set to zero.</p>
<p>I Googled the question and read all the articles I could find on this subject. One suggested inserting -1 for the autonumber column, but this didn't work. None of the other suggestions I could find worked.</p>
<p>I am using OleDbParameter's, not concatenating a big SQL text string.</p>
<p>I've tried the insert with and without a transaction. No difference.</p>
<p>How do I get this insert to work (i.e. set the autonumber column contents correctly)?</p>
<p>Thanks very much in advance,</p>
<p>Adam Leffert</p>
|
<p>In Access it is possible to INSERT an explicit value into an IDENTITY (a.k.a. Automnumber) column. If you (or your middleware) is writing the value zero to the IDENTITY column and there is no unique constraint on the IDENTITY column then that might explain it. </p>
<p>Just to be clear you should be using the syntax </p>
<pre><code>INSERT INTO (<column list>) ...
</code></pre>
<p>and the column list should omit the IDENTITY column. Jet SQL will allow you to omit the entire column list but then implicitly <em>include</em> the IDENTITY column. Therefore you should use the INSERT INTO () syntax to explicitly omit the IDENTITY column.</p>
<p>In Access/Jet, you can write explicit values to the IDENTITY column, in which case the value will obviously not be auto-generated. Therefore, ensure both you and your middleware (ADO.NET etc) are not explicitly writing a zero value to the IDENTITY column.</p>
<p>BTW just for the IDENTITY column in the below table will auto-generate the value zero every second INSERT:</p>
<pre><code>CREATE Table Test1
(
ID INTEGER IDENTITY(0, -2147483648) NOT NULL,
data_col INTEGER
);
</code></pre>
|
<p>When doing the insert, you need to be sure that you are NOT specifying a value for the AutoNumber column. Just like in SQL Server you don't insert a value for an identity column.</p>
| 18,461
|
<p><strong>This isn't a holy war, this isn't a question of "which is better".</strong></p>
<p>What are the pros of using the following format for single statement if blocks.</p>
<pre><code>if (x) print "x is true";
if(x)
print "x is true";
</code></pre>
<p>As opposed to</p>
<pre><code>if (x) { print "x is true"; }
if(x) {
print "x is true";
}
</code></pre>
<p><strong>If you format your single statement ifs without brackets</strong> or know a programmer that does, what led you/them to adopt this style in the first place? I'm specifically interested in what benefits this has brought you.</p>
<p><strong>Update</strong>: As the most popular answer ignores the actual question (even if it presents the most sane advice), here's a roundup of the bracket-less pros.</p>
<ol>
<li>Compactness</li>
<li>More readable to some</li>
<li>Brackets invoke scope, which has a theoretical overhead in some cases</li>
</ol>
|
<p>I find this:</p>
<pre><code>if( true ) {
DoSomething();
} else {
DoSomethingElse();
}
</code></pre>
<p>better than this:</p>
<pre><code>if( true )
DoSomething();
else
DoSomethingElse();
</code></pre>
<p>This way, if I (or someone else) comes back to this code later to add more code to one of the branches, I won't have to worry about forgetting to surround the code in braces. Our eyes will visually see the indenting as clues to what we're trying to do, but most languages won't.</p>
|
<p>For me, braces make it easier to see the flow of the program. It also makes it easier to add a statement to the body of the if statement. When there aren't braces, you have to add braces to add another statement.</p>
<p>I guess the pros of not using braces would be that it looks cleaner and you don't waste a line with a closing brace.</p>
| 12,300
|
<p>I was working on my printer when something metallic came into contact with the pcb. I smelled smoke and quickly unplugged the printer. Anyway, this is the result and, of course, the heat bed won't heat. </p>
<p>Can this be salvaged or should I toss it and buy a new one? </p>
<p><a href="https://i.stack.imgur.com/WhRPu.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/WhRPu.jpg" alt="shorted"></a></p>
<p><strong>update</strong> the heat bed was not hot at the time. I had the heat bed unscrewed from the chassis but had forgotten to unplug the printer. I am not exactly sure how it shorted but I think it shorted between the power lead connection and the thermistor. </p>
|
<p>What happend was short circuit of course. There is no doubt you overheated HB so copper detached from HB base plate. Because you wrote it doesn't work it means copper tracks are broken.</p>
<p>There is very low chance to fix it. I mean it - near to zero.</p>
<p>What you could do is:</p>
<ol>
<li>Detach HB from arduino</li>
<li>Find a place where track is broken (which needs to uncover it from protective layer)</li>
<li>Connect it with a wire</li>
</ol>
<p>Unfortunately even if you do it and your HB will work (electrically) your fixed HB which won't be flat anymore.</p>
<p>So definitely it's to be thrown away.</p>
<p><strong>[edit]</strong></p>
<p>I just realised you have double power HB, which means your HB has 2 heaters... which gives a bit hope.</p>
<p>take a look here</p>
<p><a href="https://i.stack.imgur.com/GZMZc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GZMZc.jpg" alt="enter image description here"></a></p>
<p><a href="http://reprap.org/mediawiki/images/thumb/6/62/Heated-bed-schematic.png/800px-Heated-bed-schematic.png" rel="nofollow noreferrer">here is schematics</a> which could give you an idea</p>
<p>You could check if your second heater works ok</p>
<p>If yes then you are salvaged! :)</p>
<p><strong>[edit2]</strong>
I really suppose the schematics of HB is more or less like this</p>
<p><a href="https://i.stack.imgur.com/AS2I1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AS2I1.png" alt="enter image description here"></a></p>
<p>So if H1 is broken there is a chance to use H2 connecting pins respectively</p>
|
<p>Yes, it should be possible to fix, although you might choose to replace anyway on the basis that the repaired bed might give you concerns about how long it will be before your repair fails.</p>
<p>You will need to carefully remove the protective layer to expose the heating element (assuming you can identify where it is likely to have broken). Then carefully solder across the break (maybe with a short fragment of wire).</p>
<p>After making the repair, you should cover the exposed track. This provides both electrical and thermal insulation. In the absence of any suitable high-temperature paintable covering, you could try using kapton tape.</p>
| 264
|
<p>How can I get Direct3D to work over a Remote Desktop connection? I am using Windows XP Professional.</p>
|
<p>3D acceleration does not work on Remote Desktop or in Virtual PC/Server.
Software-rendered OpenGL works on both Remote Desktop and Virtual PC/Server. </p>
|
<p>According to this article Direct3D is possible (but dog slow) when the box you're remoting into is running Vista.</p>
<p><a href="http://www.virtualdub.org/blog/pivot/entry.php?id=208" rel="nofollow noreferrer">http://www.virtualdub.org/blog/pivot/entry.php?id=208</a></p>
<p>I haven't verified this and cannot personally vouch for whether or not it REALLY works.</p>
| 34,307
|
<p>To be able to upload large files from a HTML page to a FTP server, I am looking for a Java/Flash FTP upload applet.</p>
<p>I really like the way <a href="http://www.dhtmlx.com/docs/products/dhtmlxVault/index.shtml" rel="noreferrer">dhtmlxVault</a> works, but I need it to upload to a FTP server instead of a HTTP file upload.</p>
<p>It would be really nice if the applet has no GUI of it's own, but instead is fully scriptable using Javascript so I can use HTML/CSS for it's appearance.</p>
<p>I hopefully looked into <a href="http://developer.yahoo.com/yui/uploader/" rel="noreferrer">Yahoo!'s YUI Uploader</a> since it requires Flash, but the documentation only mentions HTTP upload and no FTP upload.</p>
|
<p>This is exactly what <a href="http://www.enterprisedt.com/products/integralftp/overview.html" rel="nofollow noreferrer">IntegralFTP</a> is - a Java applet wrapped by Javascript. The GUI is all implemented in Javascript, and so you can change it how you like. </p>
<p>It supports SFTP, FTP and FTPS.</p>
<p>You can use IntegralFTP from <a href="http://www.integralftp.com" rel="nofollow noreferrer">http://www.integralftp.com</a>, or purchase from <a href="http://www.enterprisedt.com/products/integralftp/purchase.html" rel="nofollow noreferrer">here</a>.</p>
|
<p>Technically, any swing app would work with only small modifications if you have access to the code. If your ready to offer an applet, maybe you could even use java web start (would require even less changes).</p>
| 36,206
|
<h2>I've actually solved this, but I'm posting it for posterity.</h2>
<p>I ran into a very odd issue with the DataGridView on my dual-monitor system. The issue manifests itself as an EXTREMELY slow repaint of the control (<em>like 30 seconds for a full repaint</em>), but only when it is on one of my screens. When on the other, the repaint speed is fine.</p>
<p>I have an Nvidia 8800 GT with the latest non-beta drivers (175. something). Is it a driver bug? I'll leave that up in the air, since I have to live with this particular configuration. (It does not happen on ATI cards, though...)</p>
<p>The paint speed has nothing to do with the cell contents, and custom drawing doesn't improve the performance at all - even when just painting a solid rectangle.</p>
<p>I later find out that placing a ElementHost (from the System.Windows.Forms.Integration namespace) on the form corrects the problem. It doesn't have to be messed with; it just needs to be a child of the form the DataGridView is also on. It can be resized to (0, 0) as long as the <em>Visible</em> property is true.</p>
<p>I don't want to explicitly add the .NET 3/3.5 dependency to my application; I make a method to create this control at runtime (if it can) using reflection. It works, and at least it fails gracefully on machines that don't have the required library - it just goes back to being slow.</p>
<p>This method also lets me apply to fix while the app is running, making it easier to see what the WPF libraries are changing on my form (using Spy++).</p>
<p>After a lot of trial and error, I notice that enabling double buffering on the control itself (as opposed to just the form) corrects the issue!</p>
<hr>
<p>So, you just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it!</p>
<pre><code>class CustomDataGridView: DataGridView
{
public CustomDataGridView()
{
DoubleBuffered = true;
}
}
</code></pre>
<p>As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) (<em>although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency</em>).</p>
<p>It is sad that such a trivially simple thing ate up so much of my time...</p>
|
<p>You just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it!</p>
<pre><code>
class CustomDataGridView: DataGridView
{
public CustomDataGridView()
{
DoubleBuffered = true;
}
}
</code></pre>
<p>As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) (although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency).</p>
<p>It is sad that such a trivially simple thing ate up so much of my time...</p>
<p>Note: Making the answer an answer so the question can be marked as answered</p>
|
<p>We've experienced a similar problem using .NET 3.0 and DataGridView on a dual monitor system.</p>
<p>Our application would display the grid with a gray background, indicating that the cells could not be changed. Upon selecting a "change settings" button, the program would change the background color of the cells white to indicate to the user that the cell text could be changed. A "cancel" button would change the background color of the aforementioned cells back to gray.</p>
<p>As the background color changed there would be a flicker, a brief impression of a default sized grid with the same number of rows and columns. This problem would only occur on the primary monitor (never the secondary) and it would not occur on a single monitor system.</p>
<p>Double buffering the control, using the above example, solved our problem. We greatly appreciated your help.</p>
| 14,428
|
<p>What is the best way to secure the use/loading of a DLL with a license file?</p>
|
<p>A couple of things you might want to consider:</p>
<p>Check sum the DLL. Using a <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function" rel="nofollow noreferrer">cryptographic hash function</a>, you can store this inside the license file or inside the DLL. This provides a verification method to determined if my original DLL file is unhacked, or if it is the license file for this DLL. A few simple byte swapping techniques can quickly take your hash function off the beaten track (and thus not easy to reproduce).</p>
<p>Don't store you hash as a string, split it into unsigned shorts in different places.</p>
<p>As Larry said, a MAC address is fairly common. There are lots of examples of how to get that on <a href="http://en.wikipedia.org/wiki/The_Code_Project" rel="nofollow noreferrer">The Code Project</a>, but be aware it's easy to fake these days.</p>
<p>My suggestion, should be use <a href="http://en.wikipedia.org/wiki/Public-key_cryptography" rel="nofollow noreferrer">private/public</a> keys for license generation.</p>
<p>In short, modes of attack will be binary (modify the instructions of your DLL file) so protect against this, or key generation so make each license user, machine, and even the install specific. </p>
|
<p>You can check for a license inside of DllMain() and die if it's not found.</p>
| 13,182
|
<p>I'm having a Prusa i3 derivative printer with a capacitive sensor for the z-axis. It switches a tiny bit before the nozzle hits the print bed and hence needs a z-offset to be configured.</p>
<p>In Slic3r I have configured the z-offset to <code>-0.1</code> on the <em>General</em> page of the <em>Printer Settings</em>, but currently I'm evaluating Cura and can't find such a setting. Slic3r seems to apply this setting directly to the generated z-values in the g-code, so it does not use a short version at the beginning of the g-code. My current (except of the auto-bed-leveling part default) g-code:</p>
<pre><code>G28 ;Home
G29 ; auto-bed-leveling
G1 Z15.0 F6000 ;Move the platform down 15mm
G92 E0
G1 F200 E3
G92 E0
</code></pre>
<p>Is there a way to configure Cura, e.g. using the <em>Start Gcode</em> options, to apply the z-offset?</p>
|
<p>You can trick the printer into applying an offset using the <code>G92</code> command:</p>
<pre><code>G0 Z0
G92 Z0.1
</code></pre>
<p>First, we move the nozzle to <code>Z=0</code>. Next, through the <code>G92</code> command, we tell the printer to, from now on, treat the current position as <code>Z=0.1</code>. This effectively applies an offset of <code>-0.1</code> to the Z-axis, since if we now executed <code>G0 Z0</code> again, the nozzle would move down <code>0.1mm</code>.</p>
<p>Note that this needs to be done after homing and leveling to be effective.</p>
<p>Of course, you don't necessarily need to move the nozzle to <code>Z=0</code> for this to work. You could also just insert <code>G92 Z15.1</code> after <code>G0 Z15</code> to get the same effect.</p>
|
<p>I built my printer five years ago with a similar issue and I strongly suggest that the physical 0 will be the actual 0 instead of tweeking it into the system. Especially if you are exploring and testing new methods, i.e. Cura vs Slic3r settings. In Marlin, you can insert a z adjustment for the endstops but it can create future complications if you decide to upgrade the machine.</p>
<p>Keep it as simple as possible, if a sensor is misplaced don't try to reverse calculate it, the pressure of the motors will nudge it and after a while you'll have the same problem...</p>
| 701
|
<p>I am using a third party application and would like to change one of its files. The file is stored in XML but with an invalid doctype.</p>
<p>When I try to read use a it errors out becuase the doctype contains "file:///ReportWiz.dtd"
(as shown, with quotes) and I get an exception for cannot find file. Is there a way to tell the docbuilder to ignore this? I have tried setValidate to false and setNamespaceAware to false for the DocumentBuilderFactory. </p>
<p>The only solutions I can think of are</p>
<ul>
<li>copy file line by line into a new file, omitting the offending line, doing what i need to do, then copying into another new file and inserting the offending line back in, or </li>
<li>doing mostly the same above but working with a FileStream of some sort (though I am not clear on how I could do this..help?)</li>
</ul>
<pre>DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
docFactory.setValidating(false);
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(file);</pre>
|
<p>Tell your DocumentBuilderFactory to ignore the DTD declaration like this:</p>
<pre><code>docFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
</code></pre>
<p>See <a href="http://xerces.apache.org/xerces2-j/features.html" rel="nofollow noreferrer">here</a> for a list of available features.</p>
<p>You also might find JDOM a lot easier to work with than org.w3c.dom:</p>
<pre><code>org.jdom.input.SAXBuilder builder = new SAXBuilder();
builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
org.jdom.Document doc = builder.build(file);
</code></pre>
|
<p>Another thing I was debating was storing all of the file in a string, then doing my manipulations and wiring the String out to a file.None of these seem clean or easy, but what is the best way to do this?</p>
| 46,689
|
<p>I'm using jmockit with my tests and with one class I wish to test, uses <code>InitialContext</code> directly. So I have the following:</p>
<pre><code>public class MyClass {
public void myMethod() {
InitialContext ic = new InitialContext();
javax.mail.Session mailSession = ic.lookup("my.mail.session");
// rest of method follows.....
}
</code></pre>
<p>In my test case, I call this to use my "mocked" <code>InitialContext</code> class:</p>
<pre><code>Mockit.redefineMethods(InitialContext.class, MockInitialContext.class);
</code></pre>
<p>What is the best way to mock the <code>InitialContext</code> class with jmockit.</p>
<p>I've already tried a few ways (such as using my own <code>MockInitialContextFactory</code>), but keeping stumbling into the same error:</p>
<pre><code>NoClassDefFoundError: my.class.MockInitialContext
</code></pre>
<p>From what I can see on Google, mocking with JNDI is quite nasty. Please can anyone provide me with some guidance, or point me to a solution? That would be much appreciated. Thank you.</p>
|
<p>In general, to mock JNDI, you will need to use a framework, such as EJBMock, that can provide a mock container in which to deploy your beans.</p>
<p>The other alternative is to refactor creating the context out of your code so that it is passed in (this is dependency injection refactoring), and then you should be able to substitute a mock at will.</p>
|
<p>You're getting the NoClassDefFoundError because my.class.MockInitialContext doesn't exist. You need to create that class if you're going to pass it as an argument to Mockit.redefineMethods(). Your MockInitialContext class would just need a method named lookup() that accepts a String parameter and returns a javax.mail.Session.</p>
<p>I like <a href="https://jmockit.dev.java.net/#annotations" rel="nofollow noreferrer">JMockit annotations</a>, but you can look through the rest of that page for other examples of how to use JMockit.</p>
| 21,085
|
<p>I'm trying to get Unicode working properly in rails using MySQL. Now, Rails displays the text correctly, but it shows up as ??? in MySQL. Additionally, I am not able to filter the text.</p>
<p>My MySQL database has been configured with the utf8 character set. My client character is also UTF8. Likewise, rails is set to use UTF8. </p>
<p>If I enter the Unicode string directly from the MySQL client, it is stored properly in the table, but Rails does not correctly display it.</p>
<p>How do I get the data in, properly formatted in the database?</p>
|
<p>Have you tried adding this to your database.yml under your environment?</p>
<p><code>encoding: utf8</code></p>
|
<p>Perhaps whatever you're using to view your database isn't configured properly for unicode. For instance, if you're using a terminal in some linux distro: the terminal shell may not be configured correctly to display unicode characters.</p>
| 45,811
|
<p>One of the things I'd like to do in my browser-based application is allow the user to select some text (not in a <textarea>, just plain ol' text!), and have my application pop up a small toolbar that then can interact with the next (in my case, add annotations).</p>
<p>I've found a lot of stuff on google that seems to be focused on writing WYSIWYG editors, <strong>but that isn't what I want</strong>, and most of it worked in IE but not in FF2 or 3. Ideally, I'd like some function that can return the currently selected text in the browser window that works in <strong>IE7 (and 6 if possible), FireFox 2 & 3 and Safari 2</strong>. If it works in Opera, that'd be a bonus, but it's not a requirement.</p>
<p>Anyone have a function that does this? Or an idea of where to start?</p>
|
<p>Have a look at <a href="http://jquery.com" rel="noreferrer">jQuery</a> and the <a href="http://plugins.jquery.com/project/wrapSelection" rel="noreferrer">wrapSelection plugin</a>. It may be what you are looking for.</p>
|
<p>The behaviour of individual browsers with regard to selection is <a href="http://quirksmode.org/dom/w3c_range.html" rel="nofollow noreferrer">outlined here</a>.</p>
| 3,167
|
<p>Does TCP/IP prevent multiple copies of the same packet from reaching the destination? Or is it up to the endpoint to layer idempotency logic above it?</p>
<p>Please reference specific paragraphs from the TCP/IP specification if possible.</p>
|
<p>It's the TCP stack's job to recover from duplicate packets:</p>
<blockquote>
<p>The TCP must recover from data that is
damaged, lost, duplicated, or
delivered out of order by the internet communication system. This
is achieved by assigning a sequence number to each octet
transmitted, and requiring a positive acknowledgment (ACK) from the
receiving TCP. If the ACK is not received within a timeout
interval, the data is retransmitted. At the receiver, the
sequence
numbers are used to correctly order segments that may be received
out of order and to eliminate duplicates. Damage is handled by
adding a checksum to each segment transmitted, checking it at the
receiver, and discarding damaged segments.</p>
</blockquote>
<p>-- <a href="http://www.faqs.org/rfcs/rfc793.html" rel="nofollow noreferrer">RFC 793</a> - Transmission Control Protocol, Section 1.5</p>
<p>However, if they're the same packets with new sequence numbers, then no.</p>
|
<p>You don't fully understand the problem.
See this link:
<a href="http://en.wikipedia.org/wiki/Transmission_Control_Protocol" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Transmission_Control_Protocol</a></p>
<p>On this page is write:</p>
<p>"TCP timestamps, defined in RFC 1323, help TCP compute the round-trip time between the sender and receiver. Timestamp options include a 4-byte timestamp value, where the sender inserts its current value of its timestamp clock, and a 4-byte echo reply timestamp value, where the receiver generally inserts the most recent timestamp value that it has received. The sender uses the echo reply timestamp in an acknowledgment to compute the total elapsed time since the acknowledged segment was sent.[2]</p>
<p>TCP timestamps are also used to help in the case where TCP sequence numbers encounter their 2^32 bound and "wrap around" the sequence number space. This scheme is known as Protect Against Wrapped Sequence numbers, or PAWS (see RFC 1323 for details)."</p>
<p>Regards,
Joint (Poland)</p>
| 17,045
|
<p>Is there a static analysis tool for PHP source files?</p>
<p>The binary itself can check for syntax errors, but I'm looking for something that does more, like:</p>
<ul>
<li>unused variable assignments</li>
<li>arrays that are assigned into without being initialized first</li>
<li>and possibly code style warnings</li>
<li>...</li>
</ul>
|
<p>Run <code>php</code> in lint mode from the command line to validate syntax without execution:</p>
<p><code>php -l FILENAME</code></p>
<p>Higher-level static analyzers include:</p>
<ul>
<li><a href="http://www.program-transformation.org/PHP/PhpSat" rel="noreferrer">php-sat</a> - Requires <a href="http://strategoxt.org/" rel="noreferrer">http://strategoxt.org/</a></li>
<li><a href="http://pdepend.org/" rel="noreferrer">PHP_Depend</a></li>
<li><a href="http://pear.php.net/package/PHP_CodeSniffer" rel="noreferrer">PHP_CodeSniffer</a></li>
<li><a href="http://phpmd.org/" rel="noreferrer">PHP Mess Detector</a></li>
<li><a href="https://github.com/phpstan/phpstan" rel="noreferrer">PHPStan</a></li>
<li><a href="https://github.com/FriendsOfPHP/PHP-CS-Fixer" rel="noreferrer">PHP-CS-Fixer</a></li>
<li><a href="https://github.com/phan/phan" rel="noreferrer">phan</a></li>
</ul>
<p>Lower-level analyzers include:</p>
<ul>
<li><a href="http://pear.php.net/package/PHP_Parser" rel="noreferrer">PHP_Parser</a></li>
<li><a href="http://docs.php.net/manual/en/function.token-get-all.php" rel="noreferrer">token_get_all</a> (primitive function)</li>
</ul>
<p>Runtime analyzers, which are more useful for some things due to PHP's dynamic nature, include:</p>
<ul>
<li><a href="http://www.xdebug.org/" rel="noreferrer">Xdebug</a> has <a href="http://www.xdebug.org/docs/code_coverage" rel="noreferrer">code coverage</a> and <a href="http://www.xdebug.org/docs/execution_trace" rel="noreferrer">function traces</a>.</li>
<li>My <a href="http://github.com/troelskn/php-tracer-weaver/tree/master" rel="noreferrer">PHP Tracer Tool</a> uses a combined static/dynamic approach, building on Xdebug's function traces.</li>
</ul>
<p>The documentation libraries <a href="http://www.phpdoc.org/" rel="noreferrer">phpdoc</a> and <a href="http://www.doxygen.org/" rel="noreferrer">Doxygen</a> perform a kind of code analysis. Doxygen, for example, can be configured to render nice inheritance graphs with <a href="http://www.graphviz.org/" rel="noreferrer">Graphviz</a>.</p>
<p>Another option is <a href="http://pecl.php.net/package/xhprof" rel="noreferrer">xhprof</a>, which is similar to Xdebug, but lighter, making it suitable for production servers. The tool includes a PHP-based interface.</p>
|
<p>There is a tool for static code analysis called <a href="https://github.com/scrutinizer-ci/php-analyzer" rel="nofollow noreferrer">PHP Analyzer</a>. PHP Analyzer is now a deprecated project, but you still can access it on the legacy branch.</p>
<p>Among many types of static analysis it also provides basic auto-fixing functionality, see <a href="https://scrutinizer-ci.com/docs/tools/php/php-analyzer/" rel="nofollow noreferrer">the documentation</a>.</p>
| 49,644
|
<p>We are currently working on a new version of our main application. one thing that I really wish to work on is providing support for multiple monitors. Increasingly, our target users are adding second screens to their desktops and I think our product could leverage this extra space to improve user performance.</p>
<p>Our application is a financial package that supports leasing and fleet companies - a very specialised market. That being said, I am sure that many people with multiple monitors have a favourite bit of software that they think would be improved if it supported those extra screens better.</p>
<p>I'm looking for some opinions on those niggles that you have with current software, and how you think they could be improved to support multi-monitor setups. My aim is to then review these and decide how I can implement them and, hopefully, provide an even better environment for my users.</p>
<p>Your help is appreciated.
Thankyou.</p>
|
<p>Few random tips:</p>
<ul>
<li>If multiple windows can be open at one time, allow users to have them on separate screens. Seems obvious, but some very popular apps (e.g. Visual Studio) fail miserably at this.</li>
<li>Remember the position of the last opened window, and open new windows on the same screen as before. However, sometimes users switch between multiple and single-display (e.g. docking a laptop with an external CRT), so watch cover this case as well.</li>
<li>Consider how your particular users work, and how having two maximized windows simultaneously might help. Often, there is a (fairly passive) window for reference (e.g. a web browser/help) and an active window for data entry (e.g. editor/database) that users switch between. </li>
<li>Do <strong>not</strong> put toolboxes/toolbars on a different window than objects they operate on (it's inconvenient to move the mouse so far).</li>
</ul>
|
<p>One thing to keep in mind is that the user may have more than two monitors. My main system has six monitors, and I've run 4+ monitors on Linux, Windows, and Mac OS. Many applications--even multi-monitor utilities--will support 2 monitors but freak out over more than 2.</p>
<p>Applications work best when they know about where their windows are and relate to the locations of those windows. And as someone else mentioned, if you're going to remember where a window was, make sure that geometry still makes sense when the user comes back.</p>
<p>If the OS/window system dispatches an event related to the change of screen geometry, handle it if you're doing anything funky.</p>
<p>I think most applications that are well coded generally work these days.</p>
| 3,429
|
<p>I've been searching around for a Continuous Integration solution for Ruby on Rails, but haven't been too pleased with the results. I came from a .NET shop that used CruiseControl.NET and was really spoiled with its ease of use and rich status/reporting.</p>
<p>Ideally I'm looking for:</p>
<ul>
<li><p>The obvious Git/SVN and Test::Unit
integration</p></li>
<li><p>Integration with Rake and/or
Capistrano</p></li>
<li><p>A web interface showing the status
of the build</p></li>
<li><p>Email notification of failed builds.</p></li>
<li><p>Desktop notification (potentially
through Growl)</p></li>
<li><p>REST API for build statuses</p></li>
<li><p>Plugin framework for running other code analysis tools and reporting results in the UI</p></li>
</ul>
|
<p>I just went through the options here and thought I'd roll them up as of late 2011.</p>
<h2><a href="https://github.com/integrity/integrity" rel="noreferrer">Integrity</a></h2>
<p>After a <strong>near-death experience</strong> that left the still-linked-to <a href="http://integrityapp.com/" rel="noreferrer">website</a> with <strong>outdated information</strong> and downed the demo site, this project has a spark of life again. But the documentation hasn't moved on, and lots and lots of the <strong>steps in the tutorial are just plain broken</strong>; I had to change references to gems, build some things out of band, and then <strong>I still couldn't get it working</strong>.</p>
<h2><a href="http://cruisecontrolrb.thoughtworks.com/" rel="noreferrer">Cruise Control.rb</a></h2>
<p><strong>Dead simple</strong>: you just download it, run a command line to add your project (there is <strong>no UI</strong> for doing so), and run the Rails app. But there's no UI for editing your project, either, and there's <strong>no real integration with build artifacts</strong> aside from displaying links to them: you get no graphs of tests run, no trend lines, etc. I also had to adjust the <code>routes.rb</code> file to get the code linking working (the <code>resources :projects</code> line needs to move below all the other non-default routes).</p>
<h2><a href="http://www.jetbrains.com/teamcity/" rel="noreferrer">TeamCity</a></h2>
<p>This <strong>looks awesome</strong>, but the pay scale seems out of whack. 3 agents free and then when you're dependent you need to dole out hundreds of dollars. <strong>Personal Builds</strong> looks great, but <strong>don't have the budget</strong>.</p>
<h2><a href="http://jenkins-ci.org/" rel="noreferrer">Jenkins</a> (née <a href="http://hudson-ci.org/" rel="noreferrer">Hudson</a>)</h2>
<p>This is a Java stalwart and it is <strong>loaded up with a thousand options</strong>, so the <strong>UI is confusing</strong> and it's a <strong>chore to set up your projects</strong>. But once you set it up you get a <strong>whole lot of plugins</strong> that can pull from most anywhere, run most anything, and report most everything. The OS X Installer points Jenkins at <code>/Users/Shared/Jenkins/Home</code> but fails to create that directory or <code>chown</code> it to <code>daemon</code> (which is uses by default, and you should change to a new <code>jenkins</code> user so you can set up GitHub integration).</p>
<h2>Others</h2>
<p>I didn't really try these, but thought I'd mention why:</p>
<ul>
<li><a href="https://github.com/defunkt/cijoe" rel="noreferrer">CI Joe</a> wants to own the GitHub repo more than I want it, and its creators aren't even using it; they're on Jenkins.</li>
<li><a href="http://cerberus.rubyforge.org/" rel="noreferrer">Cerberus</a> seems neatly small but doesn't have a UI and doesn't automatically publish build artifacts where others can see them.</li>
<li><a href="http://bigtuna.appelier.com/" rel="noreferrer">BigTuna</a> seems to be a CruiseControl.rb clone without the (already minimal) community support.</li>
<li><a href="http://www.atlassian.com/software/bamboo" rel="noreferrer">Bamboo</a> looks really neat if you use JIRA and BitBucket, but we use neither. It does deploys but we already have those set up in Capistrano.</li>
</ul>
<h2>The Choice</h2>
<p>We went with <a href="http://jenkins-ci.org/" rel="noreferrer">Jenkins</a>, but I really wish one of the lighter-weight solutions had worked out.</p>
|
<p>I just published a very simple Continuous Integration App for RubyOnRails + SVN/GIT. Maybe you should give it a try:</p>
<p><a href="http://github.com/felipegiotto/Inotegration/tree/master" rel="nofollow noreferrer">http://github.com/felipegiotto/Inotegration/tree/master</a></p>
<p>I took some ideas of measurement and testing tools and, after trying some CI tools and not liking anyone of them, I decided to build my own, without needing to build big XML files or any other configuration. Just the way Rails was made to be.</p>
<p>If you like, please send me some feedback..</p>
<p>Best regards,</p>
<p>Felipe Giotto.</p>
| 27,175
|
<p>What is their use if when you call the method, it might not exist?</p>
<p>Does that mean that you would be able to dynamically create a method on a dynamic object?</p>
<p>What are the practical use of this?</p>
|
<p>You won't really be able to dynamically create the method - but you can get an implementation of <code>IDynamicMetaObject</code> (often by extending <code>DynamicObject</code>) to respond <em>as if the method existed</em>.</p>
<p>Uses:</p>
<ul>
<li>Programming against COM objects with a weak API (e.g. office)</li>
<li>Calling into dynamic languages such as Ruby/Python</li>
<li>Potentially making "explorable" objects - imagine an XPath-like query but via a method/property calls e.g. <code>document.RootElement.Person[5].Name["Attribute"]</code></li>
<li>No doubt many more we have yet to think of :)</li>
</ul>
|
<p>I see several dynamic ORM frameworks being written. Or heck write one yourself.</p>
<p>I agree with Jon Skeet, you might see some interesting ways of exploring objects.
Maybe with selectors like jQuery.</p>
<p>Calling COM and calling Dynamic Languages.</p>
<p>I'm looking forward to seeing if there is a way to do a Ruby-like missing_method.</p>
| 31,595
|
<p>I have a Panel and I am adding controls inside this panel. But there is a specific control that I would like to float. How would I go about doing that?</p>
<p>pnlOverheadDetails is the panel name</p>
<pre><code>pnlOverheadDetails.Controls.Add(lnkCalcOverhead);
</code></pre>
<p>The control named lnkCalcOverhead is the control I'd like to float.</p>
<p>Thanks in advance</p>
<p>EDIT: By float I meant the css style not anything fancy :)</p>
|
<p>If you have a CSS class defined for the control, you could do this before calling the <code>Controls.Add</code> method:</p>
<pre><code>lnkCalcOverhead.CssClass = "MyClass";
</code></pre>
<p>If you want to use the style attribute directly, try this:</p>
<pre><code>lnkCalcOverhead.Style.Add("float", "left");
</code></pre>
|
<p>IF you are talking about System.Windows.Forms here (and not WPF or ASP.NET):</p>
<p>When you are talking about float, do you mean you want to position it anywhere you want by code? If so, just set the .Location property of the control.</p>
<p>If you are talking about letting a control be moved around inside the panel by the user of your program, you will have to code that. That means capturing mouse events and moving the control accordingly?</p>
<p>Alternatively you can instead of letting the control reside within the Panel, make it as a single control occupying a new form (hence you dont have to code all the mouse event handling). Just make sure that the window is limited to be moved within the boundaries of the "parent panel" (just check on the move event of the form if its within the boundariesm and force it to stay inside).</p>
| 36,970
|
<p>Could someone compare and contrast on WCF Rest services vs. ADO.NET Data Services? What is the difference and when to use which?</p>
<p>Thanks,</p>
<p>Ray.</p>
<p><strong>Edit</strong>: thanks for the first answer, just to give a bit of background on what I'm looking to do: I have a web app I plan to put in the cloud (someday), and the DAL is built with ADO.NET Entity Framework. And, I need to figure out which web service data access technology would best fit my case.</p>
|
<p>Not sure I can give a complete answer here but I spent a lot of time at PDC trying to figure this out myself so here’s a go...</p>
<p>The short answer here is that ADO.Net Data Services are meant to provide an interface to the ADO.Net framework (DataContext, Datasets, DataTables etc…) that is seamlessly integrated with the web, using URIs and well-known data to point to your Data. ADO.Net Data Services are also meant for programming ADO.Net in the cloud. Microsoft's Cloud services, "Azure", is a new cloud programming platform that will be release in the near future. For more info on Cloud Services go <a href="http://msdn.microsoft.com/en-us/azure/default.aspx" rel="noreferrer">here</a>. </p>
<p>One cool thing I found out about ADO.Net Data Services and the cloud is that the underlying DataContext that acts as the provider to your data source can be easily configured to point your resource in the cloud, <strong><em>or</em></strong>, an on premise database. This allows you to switch your DataContext without changing any code!!! (I was impressed by that if you couldn't tell) </p>
<p>WCF Rest Services are just normal WCF Services that have added functionality so that they can be consumed in a RESTful manner (URI vs URL, Usage of HTTTP Verbs, Usage of Different Data Transfer Formats like JSON, YAML, etc...). So for example, if you had a stock ticker web service that you built in WCF, instead of requiring the caller to use a heavy WSDL implementation and ASMX, you could just use the WCF Rest functionality to publish that service as a JSON service instead and have it consumed via AJAX without having to point to an ASMX resource. For more info on WCF using rest check out the <a href="http://channel9.msdn.com/pdc2008/TL35/" rel="noreferrer">PDC Presentation</a></p>
|
<p>WCF Data Services (previously known as ADO.NET Data Services),
<a href="http://msdn.microsoft.com/en-us/data/aa937697.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/data/aa937697.aspx</a></p>
| 43,389
|
<p>Is it possible to use a flash document embedded in HTML as a link?</p>
<p>I tried just wrapping the <code>object</code> element with an <code>a</code> like this:</p>
<pre><code><a href="http://whatever.com">
<object ...>
<embed ... />
</object>
</a>
</code></pre>
<p>In Internet Explorer, that made it show the location in the status bar like a link, but it doesn't do anything.</p>
<p>I just have the .swf file, so I can't add a click handler in ActionScript.</p>
|
<p>Though the object really should respond to being wrapped in an a href tag, you could open the swf in vim and just throw in an <code>_root.onPress=function(){getURL("http://yes.no/");};</code> or if it's AS3, something like <code>_root.addEventHandler(MouseEvent.PRESS, function (e:event) {getURL("http://yes.no/");});</code> But if editing the swf is your route, you'd likely have more success with <a href="http://www.buraks.com/uae/1.html" rel="nofollow noreferrer">a tool for the purpose</a>.</p>
|
<p>As an addition to dlamblin's answer it is often best to use the clickTAG technique to open URLS from a flash movie.</p>
<p>More information can be found here:</p>
<p><a href="http://www.adobe.com/resources/richmedia/tracking/designers_guide/" rel="nofollow noreferrer">http://www.adobe.com/resources/richmedia/tracking/designers_guide/</a></p>
<p>The advantage of using the clickTAG technique is that you can set the URL to jump to in the HTML page.</p>
<p>This means that you can set the flash movie to link to different places without modifying the flash file (beyond adding the initial clickTAG code). You can use link tracking on the URL as well.</p>
| 5,350
|
<p>It seems that it is impossible to capture the keyboard event normally used for copy when running a Flex application in the browser or as an AIR app, presumably because the browser or OS is intercepting it first.</p>
<p>Is there a way to tell the browser or OS to let the event through?</p>
<p>For example, on an AdvancedDataGrid I have set the keyUp event to handleCaseListKeyUp(event), which calls the following function:</p>
<pre><code> private function handleCaseListKeyUp(event:KeyboardEvent):void
{
var char:String = String.fromCharCode(event.charCode).toUpperCase();
if (event.ctrlKey && char == "C")
{
trace("Ctrl-C");
copyCasesToClipboard();
return;
}
if (!event.ctrlKey && char == "C")
{
trace("C");
copyCasesToClipboard();
return;
}
// Didn't match event to capture, just drop out.
trace("charCode: " + event.charCode);
trace("char: " + char);
trace("keyCode: " + event.keyCode);
trace("ctrlKey: " + event.ctrlKey);
trace("altKey: " + event.altKey);
trace("shiftKey: " + event.shiftKey);
}
</code></pre>
<p>When run, I can never get the release of the "C" key while also pressing the command key (which shows up as KeyboardEvent.ctrlKey). I get the following trace results:</p>
<pre><code>charCode: 0
char:
keyCode: 17
ctrlKey: false
altKey: false
shiftKey: false
</code></pre>
<p>As you can see, the only event I can capture is the release of the command key, the release of the "C" key while holding the command key isn't even sent.</p>
<p>Has anyone successfully implemented standard copy and paste keyboard handling?</p>
<p>Am I destined to just use the "C" key on it's own (as shown in the code example) or make a copy button available?</p>
<p>Or do I need to create the listener manually at a higher level and pass the event down into my modular application's guts?</p>
|
<p>I did a test where I listened for key up events on the stage and noticed that (on my Mac) I could capture control-c, control-v, etc. just fine, but anything involving command (the key) wasn't captured until I released the command key, and then ctrlKey was false (even though the docs says that ctrlKey should be true for the command key on the Mac), and the charCode was 0. Pretty useless, in short.</p>
|
<p>Another incredibly annoying thing that I just realized is that ctrl-c can't be captured by <code>event.ctrlKey && event.keyCode = Keyboard.C</code> (or ...<code>event.charCode == 67</code>), instead you have to test for <code>charCode</code> or <code>keyCode</code> being <code>3</code>. It kind of makes sense for <code>charCode</code> since ctrl-c is <code>3</code> in the ASCII table, but it doesn't make sense for <code>keyCode</code>, which is supposed to represent the key on the keyboard, not the typed character. The same goes for all other key combos (because every ctrl combo has an ASCII equivalent).</p>
<p><em>Edit</em> Found a bug in the Flex bug system about this: <a href="https://bugs.adobe.com/jira/browse/FP-375" rel="nofollow noreferrer">https://bugs.adobe.com/jira/browse/FP-375</a></p>
| 5,175
|
<p><a href="https://stackoverflow.com/users/9931/ryan-delucchi">Ryan Delucchi</a> asked <a href="https://stackoverflow.com/questions/194698/how-to-load-a-jar-file-at-runtime#194712">here</a> in comment #3 to <a href="https://stackoverflow.com/users/4725/tom-hawtin-tackline">Tom Hawtin</a>'s answer:</p>
<blockquote>
<p>why is Class.newInstance() "evil"?</p>
</blockquote>
<p>this in response to the code sample:</p>
<pre><code>// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
</code></pre>
<p>so, why is it Evil?</p>
|
<p>The Java API documentation explains why (<a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()" rel="noreferrer">http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()</a>):</p>
<blockquote>
<p>Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The <code>Constructor.newInstance</code> method avoids this problem by wrapping any exception thrown by the constructor in a (checked) <code>InvocationTargetException</code>.</p>
</blockquote>
<p>In other words, it can defeat the checked exceptions system.</p>
|
<p>I don't know why no one provided a simple example based explanation to this, as compared to <code>Constructor::newInstance</code> for example, since <em>finally</em> <code>Class::newInstance</code> was deprecated since java-9.</p>
<p>Suppose you have this very simple class (does not matter that it is broken):</p>
<pre><code>static class Foo {
public Foo() throws IOException {
throw new IOException();
}
}
</code></pre>
<p>And you try to create an instance of it via reflection. First <code>Class::newInstance</code>:</p>
<pre><code> Class<Foo> clazz = ...
try {
clazz.newInstance();
} catch (InstantiationException e) {
// handle 1
} catch (IllegalAccessException e) {
// handle 2
}
</code></pre>
<p>Calling this will result in a <code>IOException</code> being thrown - problem is that your code does not handle it, neither <code>handle 1</code> nor <code>handle 2</code> will catch it.</p>
<p>In contrast when doing it via a <code>Constructor</code>:</p>
<pre><code> Constructor<Foo> constructor = null;
try {
constructor = clazz.getConstructor();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
Foo foo = constructor.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
System.out.println("handle 3 called");
e.printStackTrace();
}
</code></pre>
<p>that handle 3 will be called, thus you will handle it.</p>
<p>Effectively, <code>Class::newInstance</code> bypasses the exception handling - which you really don't want.</p>
| 23,725
|
<p>Say you have something like an ASP.NET ASP:DetailsView to show and edit a single record in a database.</p>
<p>It's simple to record the error cases... you add validation and a validation summary. When your update form fails validation it naturally makes noise: it shows the validation message and/or the validation summary. Not a single code behind is required.</p>
<p>But then, you pass validation, and it makes your update completely silently. There's no sense that anything happened, and there doesn't seem to be any default settings to make a success message without code-behinds.</p>
<p>But, even code-behinds are confusing. What event should show the success message? onItemUpdate, right? Fine, but then let's say you make another change and get a validation error? Your success message stays. I wasn't able to find an event that would reliably turn off an existing success message if there were a validation error. </p>
<p>This should be web development 101! Why is it so hard?</p>
<p><strong>EDIT:</strong></p>
<p>Someone suggested using the ItemCommand event... I tried this and many other events, but that success message just won't disappear. Here's some code.</p>
<p>My message in ASP.NET</p>
<pre><code><label id="successMessage" class="successMessage" runat="server"></label>
</code></pre>
<p>And my DataView tag (simplified):</p>
<pre><code> <asp:DetailsView
Id="EditClient"
DataKeyNames="LicenseID"
DataSourceID="MySource"
runat="server"
OnItemUpdated="SuccessfulClientUpdate"
OnItemCommand="ClearMessages">
</code></pre>
<p>And, my code-behind:</p>
<pre><code>protected void SuccessfulClientUpdate(object sender, DetailsViewUpdatedEventArgs e)
{
successMessage.InnerText = string.Format("Your changes were saved.");
successMessage.Visible = true;
}
protected void ClearMessages(object sender, DetailsViewCommandEventArgs e)
{
successMessage.InnerText = string.Empty;
successMessage.Visible = false;
}
</code></pre>
<p>Once I do a successful update, however, nothing seems to make that message disappear, not even failed validation.</p>
<p><strong>2nd EDIT:</strong></p>
<p>Just want to be clear that I did try putting the ClearMessages code in Page_Load. However, nothing seems to make that successMessage label disappear when I hit update a 2nd time WITH a validation error. Can anyone suggest any other troubleshooting tips?</p>
|
<p>As far as I know, there is no native way of doing this. You may rant about it, maybe Microsoft will hear it :).</p>
<p>Resetting the "success message" on Page_Load, or wherever in your code-behind, won't work. This is because ASP.NET validation is usually done both client and server-side. This means for every validation control you put on the page, ASP.NET generates some client-side Javascript that does the validation and renders the error on the client, <strong>without</strong> going back to the server. So you're stuck with both the success message and the error message at the same time.</p>
<p>What you can do about it:</p>
<ul>
<li>place a <code><div></code> control on your page, that would show up the success message (as already suggested by others above). Whenever you update something (in server-side code), show up the control and set a meaningful "Successful!" message text.</li>
<li>register a custom Javascript function that would lookup the <code><div></code> and hide it on every page submit. Be aware that the function needs to be called before the autogenerated client script that does the validation.</li>
</ul>
<p>If you look at the client source of an ASP.NET page (with validators on it), here's what you can find:</p>
<p><code><form name="aspnetForm" method="post" action="MyPage.aspx" onsubmit="javascript:return WebForm_OnSubmit();id="aspnetForm"></code></p>
<p>The WebForm_OnSubmit is generated by ASP.NET and calls the javascript that does the validation. Sample:</p>
<pre><code>function WebForm_OnSubmit() {
if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false)
return false;
return true;
}
</code></pre>
<p>To register your custom code that hides the success message, you should place (in your code-behind) something along these lines:</p>
<pre><code>if (!Page.ClientScript.IsOnSubmitStatementRegistered("ClearMessage"))
{
string script = @"document.getElementById('" +
yourDivControl.ClientID + "').style.display='none'";
Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "ClearMessage", script);
}
</code></pre>
<p>This will turn your page's autogenerated WebForm_OnSubmit into the following:</p>
<pre><code>function WebForm_OnSubmit() {
document.getElementById('ctl00_yourDivControl').style.display='none';
if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false)
return false;
return true;
}
</code></pre>
<p>The effect:
On every postback (e.g. when ItemCommand is triggered, or when some Save button is clicked, or anything else), you will show up the div control with the "success" message. On the next postback, just before submitting the page to the server, this message is cleared. Of course, if this postback also triggers a "success", the message is shown again by the code-behind on the server. And so on and so forth.</p>
<p>I hope the above is helpful. It's not the full-blown solution, but it gives sufficient hints to point you in the right direction.</p>
|
<p>Why not turn the validation message off in the Page_Load. I assume that if a post back occurs you'd want to get rid of the message so make sure it's always off. Or disable view state for the control by setting EnableViewState="False" in the markup (aspx page).</p>
<p>So:</p>
<pre><code>protected void ClearMessages(object sender, DetailsViewCommandEventArgs e)
{
successMessage.InnerText = string.Empty;
successMessage.Visible = false;
}
</code></pre>
<p>becomes:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
successMessage.InnerText = string.Empty;
successMessage.Visible = false;
}
</code></pre>
<p>Also as a side note if you buiding .net sites you need to get comftorble with code behinds IMHO:-) </p>
| 47,235
|
<p>Is there something special about Safari for Windows and AJAX?<br>
In other words: Are there some common pitfalls I should keep in mind?</p>
|
<p>Safari is really standards compliant. Unless you're using some really esoteric browser features, in general if something works in Firefox, I've found it works without modification in Windows Safari.</p>
<p>Apple has <a href="http://developer.apple.com/internet/safari/" rel="nofollow noreferrer">a developer center for web developers</a>, but I didn't find anything too useful there.</p>
|
<p>One word of warning: Safari on Windows does not support XSLT.</p>
| 8,258
|
<p>I have used "traditional" version control systems to maintain source code repositories on past projects. I am starting a new project with a distributed team and I can see advantages to using a distributed system. Given that I understand SourceSafe, CVS, and Subversion; what suggestions do you have for a Git newbie?</p>
|
<p>The <a href="http://git.or.cz/course/svn.html" rel="noreferrer">Git - SVN Crash Course</a> is a good read for getting going.</p>
|
<p>I tried git in my company.
We used CVS and wanted to move to a better VC tool.
We have chosen git as a best tool for files versioning (Linus on GIT).
Its performance is just the best and it is a really great tools for a developer who understands version control in-depth but It is a nightmare for a regular developers who uses version control in background and don't want learn how to use for more than few hours (and they do need to learn a lot)</p>
<p>Also it's integration with existing IDEs is far away for being complete.
The whole usability is pretty big issue for a regular developer.</p>
<p>After a pilot with 4 developers we switched to Subversion as simplest although not so superior tool.</p>
<p>There is also commercial solution for Subversion MultiSite (which we didn't try yet but will try shortly) - <a href="http://www.wandisco.com/" rel="nofollow noreferrer">WANDisco</a></p>
| 15,429
|
<p>I've been trying to solve this, and have been getting stuck, so I thought I'd ask.</p>
<p>Imagine two ActionBeans, A and B.</p>
<p><code>A.jsp</code> has this section in it:</p>
<pre><code>...
<jsp:include page="/B.action">
<jsp:param name="ponies" value="on"/>
</jsp:include>
<jsp:include page="/B.action">
<jsp:param name="ponies" value="off"/>
</jsp:include>
...
</code></pre>
<p>Take it as read that the B ActionBean does some terribly interesting stuff depending on whether the "ponies" parameter is set to either on or off.</p>
<p>The parameter string "ponies=on" <em>is</em> visible when you debug into the request, but it's not what's getting bound into the B ActionBean. Instead what's getting bound are the parameters to the original A.action.</p>
<p>Is there some way of getting the behaviour I want, or have I missed something fundamental?</p>
|
<p><a href="http://jqueryui.com/demos/slider/" rel="noreferrer">jQuery UI Slider</a> (<a href="http://docs.jquery.com/UI/Slider" rel="noreferrer">API docs</a>)</p>
|
<p>The code below should be enough to get you started. Tested in Opera, IE and Chrome.</p>
<pre><code><script>
var l=0;
function f(i){
im = 'i' + l;
d=document.all[im];
d.height=99;
document.all.f1.t1.value=i;
im = 'i' + i;
d=document.all[im];
d.height=1;
l=i;
}
</script>
<center>
<form id='f1'>
<input type=text value=0 id='t1'>
</form>
<script>
for (i=0;i<=50;i++)
{
s = "<img src='j.jpg' height=99 width=9 onMouseOver='f(" + i + ")' id='i" + i + "'>";
document.write(s);
}
</script>
</code></pre>
| 20,851
|
<p>on some Windows PC, when I have both easyPHP and a standalone apache service configured on another network port and with a specific service name, I have a problem : when I stop easyphp, the other apache is stopped too.</p>
<p>The problem do not occur on all PC I have, but seems very strange to me.
Any idea?</p>
<p>more information after answer from Radar : my process have a special name (ecapache), but easyphp does not seems to use process but rather lauch directly the servers.</p>
<p>Thanks
Cédric</p>
|
<p>Maybe how it's killing it is that it's finding all processes called "apache" or similar and just killing them, regardless of if it 'owns' it or not.</p>
|
<p>i think Both are integrated together, i was not occur in all PC because of port number.</p>
| 11,638
|
<p>I need to update a record in a database with the following fields </p>
<pre><code>[ID] int (AutoIncr. PK)
[ScorerID] int
[Score] int
[DateCreated] smalldatetime
</code></pre>
<p>If a record exists for todays date (only the date portion should be checked, not the time) and a given scorer, I'd like to update the score value for this guy and this day. If the scorer doesn't have a record for today, I'd like to create a new one.</p>
<p>I'm getting grey hair trying to figure how to put this into a single (is this possible?) sql statement. By the way I'm using an MSSQl database and the <code>ExecuteNonQuery()</code> method to issue the query.</p>
|
<pre><code>IF EXISTS (SELECT NULL FROM MyTable WHERE ScorerID = @Blah AND CONVERT(VARCHAR, DateCreated, 101) = CONVERT(VARCHAR, GETDATE(), 101))
UPDATE MyTable SET blah blah blah
ELSE
INSERT INTO MyTable blah blah blah
</code></pre>
|
<pre><code>CREATE PROCEDURE InsertOrUpdateScorer(@ScorerID INT, @Score INT)
AS
BEGIN
IF EXISTS (
SELECT 1
FROM Scorer
WHERE ScorerID = @ScorerID AND DATEDIFF(dd, GETDATE(), DateCreated) = 0
)
BEGIN
UPDATE
Scorer
SET
Score = @Score
WHERE
ScorerID = @ScorerID
RETURN @ScorerID
END
ELSE
BEGIN
INSERT
Scorer
(ScorerID, Score, DateCreated)
VALUES
(@ScorerID, @Score, GETDATE())
RETURN SCOPE_IDENTITY()
END
END
</code></pre>
<p>Use the return value of the procedure to grab the new ScorerId.</p>
<pre><code>SqlCommand UpdateScorer = New SqlCommand("InsertOrUpdateScorer", DbConn);
UpdateScorer.CommandType = CommandType.StoredProcedure;
SqlParameter RetValue = UpdateScorer.Parameters.Add("RetValue", SqlDbType.Int);
RetValue.Direction = ParameterDirection.ReturnValue;
SqlParameter Score = UpdateScorer.Parameters.Add("@Score", SqlDbType.Int);
Score.Direction = ParameterDirection.Input;
SqlParameter ScorerId = UpdateScorer.Parameters.Add("@ScorerID", SqlDbType.Int);
ScorerId.Direction = ParameterDirection.Input;
Score.Value = 15; // whatever
ScorerId.Value = 15; // whatever
UpdateScorer.ExecuteNonQuery();
Console.WriteLine(RetValue.Value);
</code></pre>
| 44,223
|
<p>How can I consistently get the absolute, fully-qualified root or base url of the site regardless of whether the site is in a virtual directory and regardless of where my code is in the directory structure? I've tried every variable and function I can think of and haven't found a good way.</p>
<p>I want to be able to get the url of the current site, i.e. <a href="http://www.example.com" rel="nofollow noreferrer">http://www.example.com</a> or if it's a virtual directory, <a href="http://www.example.com/DNN/" rel="nofollow noreferrer">http://www.example.com/DNN/</a></p>
<hr>
<p>Here's some of the things I've tried and the result. The only one that includes the whole piece that I want (<a href="http://localhost:4471/DNN441" rel="nofollow noreferrer">http://localhost:4471/DNN441</a>) is Request.URI.AbsoluteURI:</p>
<ul>
<li>Request.PhysicalPath: C:\WebSites\DNN441\Default.aspx</li>
<li>Request.ApplicationPath: /DNN441</li>
<li>Request.PhysicalApplicationPath: C:\WebSites\DNN441\</li>
<li>MapPath:
C:\WebSites\DNN441\DesktopModules\Articles\Templates\Default.aspx</li>
<li>RawURL:
/DNN441/ModuleTesting/Articles/tabid/56/ctl/Details/mid/374/ItemID/1/Default.aspx</li>
<li>Request.Url.AbsoluteUri: <a href="http://localhost:4471/DNN441/Default.aspx" rel="nofollow noreferrer">http://localhost:4471/DNN441/Default.aspx</a></li>
<li>Request.Url.AbsolutePath: /DNN441/Default.aspx</li>
<li>Request.Url.LocalPath: /DNN441/Default.aspx Request.Url.Host: localhost</li>
<li>Request.Url.PathAndQuery:
/DNN441/Default.aspx?TabId=56&ctl=Details&mid=374&ItemID=1</li>
</ul>
|
<p>In reading through the answer provided in Rick Strahl's Blog I found what I really needed was quite simple. First you need to determine the relative path (which for me was the easy part), and pass that into the function defined below:</p>
<p>VB.NET</p>
<pre><code>Public Shared Function GetFullyQualifiedURL(ByVal s as string) As String
Dim Result as URI = New URI(HttpContext.Current.Request.Url, s)
Return Result.ToString
End Function
</code></pre>
<p>C#</p>
<pre><code>public static string GetFullyQualifiedURL(string s) {
Uri Result = new Uri(HttpContext.Current.Request.Url, s);
return Result.ToString();
}
</code></pre>
|
<p>Have you tried AppSettings.RootUrl which is usually configured in the web.config file?</p>
| 14,829
|
<p>We have a 50 projects solution in VS 2005. </p>
<p>Is any way to get incremental build if nothing was changed? </p>
<p>It is kind of doing it now, but it executes all prebuild and post build events for each project. </p>
<p>The compiling itself is not happenning, but it iterates through all projects and executes all prebuild and post build events for each project. </p>
<p>Is any way to prevent it?</p>
|
<p><a href="https://stackoverflow.com/questions/227991/build-incrementally-in-vs-2005#231867">See my answer in the other question</a>.</p>
|
<p>You could setup a separate project config, like Debug_INC, and no pre or post build events in those configs, then just run them when needed.</p>
| 28,678
|
<p>I am looking to create a search engine that will be based on 5 columns in a SQL 2000 DB. I have looked into Lucene.NET and read the documentation on it, but wondering if anyone has any previous experience with this?</p>
<p>Thanks</p>
|
<p>IMHO it's not so much about performance, but about maintainability. In order to index your content using Lucene.NET you'll have to create some mechanism (service of triggered) which will add new rows (and remove deleted rows) from the Lucene index. </p>
<p>From a beginner's perspective I think it's probably easier to use the SQL Server built-in full text search engine.</p>
|
<p>i haven't dealt with Lucene yet but a friend of mine has and he said that their performance was 4 to 5 times better with lucene than full text indexing.</p>
| 43,545
|
<p>I have to work on several VB6 legacy projects and despite some good VB6 plugins (CodeSMART for example) I hate the IDE more and more, especially now where I have the opportunity to work with Java/Netbeans on a new project. Unfortunatly it will stay that way at least the next few years.</p>
<p>So I'm asking myself: Can the Netbeans IDE be extended via plugins to support VB6 projects? </p>
<p>This is what I dream of:</p>
<ul>
<li>Better code navigation (Ctrl+Click for example)</li>
<li>Better code highlighting</li>
<li>Code folding</li>
<li>Simple refactoring </li>
<li>Organizing the source files in a hierarchy</li>
<li>My own VB6 specific warnings ("Missing <code>option explicit</code> for example")</li>
<li>Code generators (like in Java for getters and setters)</li>
<li>Integrated debugging (But I assume this is virtually impossible)</li>
<li>Auto-formatting of code</li>
</ul>
<p>Can it be done? Has someone experience with Netbeans and a custom language? What's the best way to start?</p>
<p>EDIT: I want to do this myself as I'm aware that this is a highly specialized feature request :)</p>
|
<p>I did a quick search to see if there is an available plugin to support Visual Basic on Netbeans, but was not able to find any.</p>
<p>As you've mentioned that you are willing to write VB support for Netbeans, you may want to take a look at <a href="http://www.netbeans.org/community/magazine/html/03/schliemann/" rel="nofollow noreferrer">Schliemann - Easy Integration of Scripting Languages in NetBeans IDE 6.0</a>. This article provides information on how langauge support works in Netbeans 6 along with a how-to on adding new languages.</p>
<p>You may also want to check out the <a href="http://wiki.netbeans.org/Gsf" rel="nofollow noreferrer">General Scripting Framework</a>, which is used to provide support for Ruby, HTML, CSS and JavaScript. The advantage over Project Schliemann is that it will allow compilation of new languages as well, however, the downside is that you will have to provide the lexer and parser for the new language to support.</p>
<p>Here are some additional some resources which may come handy on your quest:</p>
<ul>
<li><a href="http://www.netbeans.org/community/contribute/modules.html" rel="nofollow noreferrer">Contributing Modules</a> - First, check to be sure that there are no other plugins that will suite your needs.</li>
<li><a href="http://platform.netbeans.org/tutorials/60/nbm-google.html" rel="nofollow noreferrer">NetBeans Plugin Quick Start</a> - Introduction to adding features to the IDE.</li>
<li><a href="http://wiki.netbeans.org/Schliemann" rel="nofollow noreferrer">Generic Languages Framework (Project Schliemann)</a> - This information may be outdated as it references the current version of Netbeans as a "future" version.</li>
<li><a href="http://languages.netbeans.org/" rel="nofollow noreferrer">languages.netbeans.org</a> - This site is listed as the official page for Project Schliemann.</li>
</ul>
<p>Good luck!</p>
|
<p>No. Netbeans is primarily a Java IDE. Although it supports a lot of languages besides Java, there is no much interested for VB6 in the Java community.</p>
| 40,517
|
<p>I'd really like to handle this without monkey-patching but I haven't been able to find another option yet.</p>
<p>I have an array (in Ruby) that I need to sort by multiple conditions. I know how to use the sort method and I've used the trick on sorting using an array of options to sort by multiple conditions. However, in this case I need the first condition to sort ascending and the second to sort descending. For example:</p>
<pre><code>ordered_list = [[1, 2], [1, 1], [2, 1]]
</code></pre>
<p>Any suggestions?</p>
<p>Edit: Just realized I should mention that I can't easily compare the first and second values (I'm actually working with object attributes here). So for a simple example it's more like:</p>
<pre><code>ordered_list = [[1, "b"], [1, "a"], [2, "a"]]
</code></pre>
|
<p>How about:</p>
<pre>
<code>
ordered_list = [[1, "b"], [1, "a"], [2, "a"]]
ordered_list.sort! do |a,b|
[a[0],b[1]] <=> [b[0], a[1]]
end
</code>
</pre>
|
<p>I had this same basic problem, and solved it by adding this:</p>
<pre><code>class Inverter
attr_reader :o
def initialize(o)
@o = o
end
def <=>(other)
if @o.is && other.o.is
-(@o <=> other.o)
else
@o <=> other.o
end
end
end
</code></pre>
<p>This is a wrapper that simply inverts the <=> function, which then allows you to do things like this:</p>
<pre><code>your_objects.sort_by {|y| [y.prop1,Inverter.new(y.prop2)]}
</code></pre>
| 9,867
|
<p>Imagine this directory structure:</p>
<pre><code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code></pre>
<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p>
<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>
<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p>
<hr>
<p>Edit: all my <code>__init__.py</code>'s are currently empty </p>
<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>
<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/" rel="noreferrer">PEP 366</a> (thanks John B)</p>
|
<p>Everyone seems to want to tell you what you should be doing rather than just answering the question.</p>
<p>The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.</p>
<p>From <a href="http://www.python.org/dev/peps/pep-0328/" rel="noreferrer">PEP 328</a>:</p>
<blockquote>
<p>Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.</p>
</blockquote>
<p>In Python 2.6, they're adding the ability to reference modules relative to the main module. <a href="http://python.org/dev/peps/pep-0366/" rel="noreferrer">PEP 366</a> describes the change.</p>
<p><strong>Update</strong>: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.</p>
|
<p>This method queries and auto populates the path:</p>
<pre class="lang-py prettyprint-override"><code>import os
import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
os.sys.path.insert(1, parentdir)
# print("currentdir = ", currentdir)
# print("parentdir=", parentdir)
</code></pre>
| 9,845
|
<p>Is there an elegantish way in Swing to find out if there are any tooltips currently being displayed in my frame?</p>
<p>I'm using custom tooltips, so it would be very easy to set a flag in my <code>createToolTip()</code> method, but I can't see a way to find out when the tooltip is gone.</p>
<p><code>ToolTipManager</code> has a nice flag for this, tipShowing, but of course it's <code>private</code> and they don't seem to offer a way to get to it. <code>hideWindow()</code> doesn't call out to the tooltip component (that I can tell), so I don't see a way there.</p>
<p>Anyone have any good ideas?</p>
<p>Update: I went with reflection. You can see the code here:</p>
<pre><code>private boolean isToolTipVisible() {
// Going to do some nasty reflection to get at this private field. Don't try this at home!
ToolTipManager ttManager = ToolTipManager.sharedInstance();
try {
Field f = ttManager.getClass().getDeclaredField("tipShowing");
f.setAccessible(true);
boolean tipShowing = f.getBoolean(ttManager);
return tipShowing;
} catch (Exception e) {
// We'll keep silent about this for now, but obviously we don't want to hit this
// e.printStackTrace();
return false;
}
}
</code></pre>
|
<p>It appears that the isEnabled() property of the hideTipAction is directly tied to the tipShowing boolean. You could try this:</p>
<pre><code>public boolean isTooltipShowing(JComponent component) {
AbstractAction hideTipAction = (AbstractAction) component.getActionMap().get("hideTip");
return hideTipAction.isEnabled();
}
</code></pre>
<p>You probably want to do some sanity checking for nulls, etc. But this should get you pretty close.</p>
<p>EDIT, to your responses:</p>
<p>Short of some ugly reflection code, I don't think you have much choice. You cannot subclass <code>ToolTipManager</code> because of the package private constructor, and the <code>showTipWindow()</code> and <code>hideTipWindow()</code> are also package private, so the Adapter pattern is out as well.</p>
|
<p>It looks like that is going to require looping over all of the components to see if they have a tooltip. I'm looking for a global value. It may be that a loop is doable, but it seems inefficient.</p>
| 42,949
|
<p>I have a PHP script that can encode a PNG image to a Base64 string.</p>
<p>I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.</p>
|
<p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa" rel="noreferrer"><code>btoa()</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/atob" rel="noreferrer"><code>atob()</code></a> to convert to and from base64 encoding.</p>
<p>There appears to be some confusion in the comments regarding what these functions accept/return, so…</p>
<ul>
<li><p><code>btoa()</code> accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.btoa#Unicode_Strings" rel="noreferrer">it will probably break</a>. This isn’t a problem <em>if</em> you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.</p>
</li>
<li><p><code>atob()</code> returns a “string” where each character represents an 8-bit byte – that is, its value will be between <code>0</code> and <code>0xff</code>. This does <em>not</em> mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.</p>
</li>
</ul>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/1095102/how-do-i-load-binary-image-data-using-javascript-and-xmlhttprequest">How do I load binary image data using Javascript and XMLHttpRequest?</a></li>
</ul>
<hr />
<p>Most comments here are outdated. You can probably use both <code>btoa()</code> and <code>atob()</code>, unless you support really outdated browsers.</p>
<p>Check here:</p>
<ul>
<li><a href="https://caniuse.com/?search=atob" rel="noreferrer">https://caniuse.com/?search=atob</a></li>
<li><a href="https://caniuse.com/?search=btoa" rel="noreferrer">https://caniuse.com/?search=btoa</a></li>
</ul>
|
<p><strong>Incase anyone wants to encode a string to base64 in Typescript</strong></p>
<p>I tweaked <a href="https://stackoverflow.com/a/26514148/8885582">Peter Mortensen's answer</a> and added types ( where needed )</p>
<pre><code>const Base64 = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// added type string to input
encode: function(input: string) {
let output = "";
let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
let i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// added type string to input
_utf8_encode: function(input: string) {
input= input.replace(/\r\n/g, "\n");
let utftext = "";
for (let n = 0; n < input.length; n++) {
let c = input.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
}
// function that consumes that Base64.encode function
const encode = ( cipher : string) => {
const encodedString: string = Base64.encode(cipher)
return encodedString;
}
console.log(encode('Hello World!'))
</code></pre>
<p><a href="https://jsfiddle.net/brianwachira/tp2xz3r6/2/" rel="nofollow noreferrer">jsfiddle link</a></p>
| 30,637
|
<p>With SQL Server 2005 and transactional replication, can I remove the primary key constraints on the subscriber, while leaving the primary key constraints on the publisher?</p>
<p>Primary I want to do this because I want to cluster on different columns than the existing clustered constraints. I don't think I can convert a constraint from clustered to nonclustered without dropping it first, and replication is already occurring.</p>
|
<p>Why don't you leave the primary key and create additional non clustered indexes on the subscriber or will this not resolve your problem? If the reason to have other columns indexed on the subscriber is performance then this should be a solution. </p>
|
<p>I did my own homework, and came to the conclusion that you <em>can</em> drop the constraints on the subscriber.</p>
<p>I set up a simple transactional replication scenario, dropped the primary key on the subscriber, and then did some inserts, deletes and updates, and verified that the changes were replicated to the subscriber.</p>
<p>I guess I should have done that to begin with. I didn't know it was going to be that easy :).</p>
| 44,065
|
<p>I have the following xml that's sent to me from a web service. I'm using .NET to deserialize it, but I'm getting an exception saying that its formatted wrong. <code>There is an error in XML document (2, 2)</code> Now, if I understand that correctly, it's not liking that it's finding the first <code><error></code> node.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<messages xmlns="http://www.w3.org/1999/xml">
<error>error text</error>
<message>message text</message>
</messages>
</code></pre>
<p>my code looks like this, data being the <code>String</code> version of the XML above:</p>
<pre><code>Dim resp As cResponseMessage
Dim sr As New StringReader(data)
Dim xs As New XmlReaderSettings()
Dim xd As New XmlSerializer(GetType(cResponseMessage))
resp = xd.Deserialize(XmlTextReader.Create(sr, xs))
</code></pre>
<p>and <code>cResponseMessage</code> is simply a class with an <code>XMLRoot</code> attribute and 2 properties with <code>XMLElement</code> attributes. Nothing fancy here, but it doesn't want to work.</p>
<p>Any help would be great.</p>
|
<p>This class works for me:</p>
<pre><code><XmlRoot(Namespace:="http://www.w3.org/1999/xml", ElementName:="messages")> _
Public Class cResponseMessage
<XmlElement> _
Public Property [error] As String
Get
Set(ByVal value As String)
End Property
<XmlElement> _
Public Property message As String
Get
Set(ByVal value As String)
End Property
End Class
</code></pre>
|
<p>There is an error in XML document (2, 2) looks to me like it would be the m in <messages>.</p>
<p>Perhaps you don't have your XmlRoot set up correctly in cResponseMessage?</p>
| 39,000
|
<p>What is the best way to write bytes in the middle of a file using Java?</p>
|
<p>Reading and Writing in the middle of a file is as simple as using a <a href="http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html" rel="noreferrer"><code>RandomAccessFile</code></a> in Java.</p>
<p><a href="http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html" rel="noreferrer"><code>RandomAccessFile</code></a>, despite its name, is more like an <code>InputStream</code> and <code>OutputStream</code> and less like a <code>File</code>. It allows you to read or seek through <code>bytes</code> in a file and then begin writing over whichever bytes you care to stop at.</p>
<p>Once you discover this class, it is very easy to use if you have a basic understanding of regular file i/o.</p>
<p>A small example:</p>
<pre><code>public static void aMethod(){
RandomAccessFile f = new RandomAccessFile(new File("whereDidIPutTHatFile"), "rw");
long aPositionWhereIWantToGo = 99;
f.seek(aPositionWhereIWantToGo); // this basically reads n bytes in the file
f.write("Im in teh fil, writn bites".getBytes());
f.close();
}
</code></pre>
|
<p>Open the file in write mode without truncating it, seek to the desired offset, and write the desired data. Just be careful about text/binary mode.</p>
| 21,896
|
<p>I'm using caml query to select all documents which were modified or added by user. Query runs recursively on all subsites of specified site collection.</p>
<p>Now problem is I can't get rid of folders which are also part of result set. For now I'm filtering them from result datatable. But I'm wondering: Is it possible to filter out folders from result set just by using caml?</p>
|
<p>This CAML actually does the trick:</p>
<pre><code><Where>
<Eq>
<FieldRef Name='FSObjType' />
<Value Type='Integer'>0</Value>
</Eq>
</Where>
</code></pre>
<p>that will not give you any folders.</p>
|
<p>This is what worked for me</p>
<pre><code> <Where>
<Eq>
<FieldRef Name='FSObjType' />
<Value Type='Number'>1</Value>
</Eq>
</Where>
</code></pre>
| 43,204
|
<p>What would be the best way to fill an array from user input?</p>
<p>Would a solution be showing a prompt message and then get the values from from the user?</p>
|
<pre><code>string []answer = new string[10];
for(int i = 0;i<answer.length;i++)
{
answer[i]= Console.ReadLine();
}
</code></pre>
|
<p>Add the input values to a List and when you are done use List.ToArray() to get an array with the values.</p>
| 28,531
|
<p>Is there anything in the header of an HTTP request that would allow me to differentiate between an AJAX call and a direct browser request from a given client? Are the user agent strings usually the same regardless?</p>
|
<p>If you use Prototype, jQuery, Mootools or YUI you should find a <strong>X-Requested-With:XMLHttpRequest</strong> header which will do the trick for you. It should be possible to insert whatever header you like with other libraries.</p>
<p>At the lowest level, given a <a href="http://www.w3.org/TR/XMLHttpRequest" rel="noreferrer">XMLHttpRequest</a> or XMLHTTP object, you can set this header with the <a href="http://www.w3.org/TR/XMLHttpRequest/#setrequestheader" rel="noreferrer">setRequestHeader</a> method as follows:</p>
<pre><code>xmlHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
</code></pre>
|
<p>After some research, it looks like the best approach would be to simply specify a custom user agent string when making AJAX calls and then checking for this custom user agent string on the server.</p>
| 26,577
|
<p>I am a C# developer. Still learning. I had not learn all the features of C# 2.0 and now the new version of c# is being released. how do we cope up with this.what is the best option to cope up with the latest programming skills.</p>
|
<p>As Steve M said: Read. But don't stop there. You also have to write. </p>
<p>First: Write Code. Try out the stuff you read about. Look at open source software and how things are done by others. Try those new techniques out.</p>
<p>Second: Write text. Write a blog post or whatever on how to do something. You had a problem and you solved it, now write down what the problem was, what ideas for solutions you had and what solution you picked for which reasons. Get people to comment, get peer review of your own thinking that way.</p>
|
<p>Read, read and when you're done reading, read some more. Reading also helps.</p>
<p>But seriously, sign up to relevant mailing lists and RSS feeds so that you can be updated as things happen.</p>
| 14,578
|
<p>I've got an application that is very graphics intensive and built on DirectX and Windows Forms. It has an automation and replay framework around which is built an automated testing system. Unfortunately, when the tests run unattended during a nightly build, the display is inactive or tied up with the screensaver, and our IT security policies don't allow us to disable that.</p>
<p>So my question: is there a way to do a "screen" capture of an application that is running without the display? I'd like to ensure that the graphics card is engaged so that my rendering pipeline is the same, but the testing framework shouldn't need to care about the state of the display.</p>
<p>Any help wildly appreciated!</p>
|
<p>Since you're mentioned rendering pipeline, so I'm assuming you're using Direct3d, if so, you can save the backbuffer of the frame. I did that when I was still using VB.Net + MDX</p>
<pre><code>Dim tempSurface As Direct3D.Surface
tempSurface = device.GetBackBuffer(0, 0, Direct3D.BackBufferType.Mono)
Direct3D.SurfaceLoader.Save(tempFilename, Direct3D.ImageFileFormat.Png, tempSurface)
</code></pre>
<p>You can easily converted that do any programming language of you choice, it's basically calling Direct3d's API. Though, you need to configure you backbuffer and Present parameters as</p>
<pre><code>' Need to use flip to enable screen capture
presentParams.SwapEffect = Direct3D.SwapEffect.Flip
presentParams.PresentationInterval = Direct3D.PresentInterval.One
</code></pre>
|
<p>Install a VM and run the application in that. If you're running a screen saver I doubt your video card is even generating the GUI for the application.</p>
| 22,138
|
<p>I am trying to figure out the best way to model a spreadsheet (from the database point of view), taking into account :</p>
<ul>
<li>The spreadsheet can contain a variable number of rows.</li>
<li>The spreadsheet can contain a variable number of columns.</li>
<li>Each column can contain one single value, but its type is unknown (integer, date, string).</li>
<li>It has to be easy (and performant) to generate a CSV file containing the data.</li>
</ul>
<p>I am thinking about something like :</p>
<pre><code>class Cell(models.Model):
column = models.ForeignKey(Column)
row_number = models.IntegerField()
value = models.CharField(max_length=100)
class Column(models.Model):
spreadsheet = models.ForeignKey(Spreadsheet)
name = models.CharField(max_length=100)
type = models.CharField(max_length=100)
class Spreadsheet(models.Model):
name = models.CharField(max_length=100)
creation_date = models.DateField()
</code></pre>
<p>Can you think about a better way to model a spreadsheet ? My approach allows to store the data as a String. I am worried about it being too slow to generate the CSV file.</p>
|
<p>You may want to study EAV (Entity-attribute-value) data models, as they are trying to solve a similar problem.</p>
<p><a href="http://en.wikipedia.org/wiki/Entity-Attribute-Value_model" rel="nofollow noreferrer">Entity-Attribute-Value - Wikipedia</a></p>
|
<p>That is a good question that calls for many answers, depending how you approach it, I'd love to share an opinion with you.
This topic is one the various we searched about at Zenkit, we even wrote an article about, we'd love your opinion on it: <a href="https://zenkit.com/en/blog/spreadsheets-vs-databases/" rel="nofollow noreferrer">https://zenkit.com/en/blog/spreadsheets-vs-databases/</a></p>
| 29,471
|
<p>I am trying to write a C# client to a server that is written in Java. The server expects a 4 byte (DataInputStread readInt() in Java) message header followed by the actual message.</p>
<p>I am absolutely new to C#, how can I send this message header over to the Java Server? I tried it several ways (mostly trial and error without getting too deep into the C# language), and nothing worked. The Java side ended up with the incorrect (very large) message length.</p>
|
<p>It is, as other posters have pointed out, down to endianness.</p>
<p>The Java <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/io/DataInputStream.html" rel="noreferrer">DataInputStream</a> expects the data to be <a href="http://en.wikipedia.org/wiki/Endianness" rel="noreferrer">big-endian</a> (network byte order). Judging from the Mono documentation (for equivalents like <a href="http://www.go-mono.com/docs/monodoc.ashx?link=T%3aSystem.IO.BinaryWriter" rel="noreferrer">BinaryWriter</a>), C# tends toward being little-endian (the default for Win32/x86).</p>
<p>So, when you use the standard class library to change the 32bit int '1' to bytes, they produce different results:</p>
<pre><code>//byte hex values
Java: 00 00 00 01
C#: 01 00 00 00
</code></pre>
<p>You can alter the way you write ints in C#:</p>
<pre><code>private static void WriteInt(Stream stream, int n) {
for(int i=3; i>=0; i--)
{
int shift = i * 8; //bits to shift
byte b = (byte) (n >> shift);
stream.WriteByte(b);
}
}
</code></pre>
<p>EDIT:</p>
<p>A safer way of doing this would be:</p>
<pre><code>private static void WriteToNetwork(System.IO.BinaryWriter stream, int n) {
n = System.Net.IPAddress.HostToNetworkOrder(n);
stream.Write(n);
}
</code></pre>
|
<p>I dont know C# but you just need to do the equivalent of this:</p>
<pre><code>out.write((len >>> 24) & 0xFF);
out.write((len >>> 16) & 0xFF);
out.write((len >>> 8) & 0xFF);
out.write((len >>> 0) & 0xFF);
</code></pre>
| 11,772
|
<p>All,</p>
<p>So I've got all my select queries in LINQ-to-SQL converted to using CompiledQueries to speed things up. Works great so far for select statements, but I haven't been able to figure out how to pre-compile insert, update, or delete statements.</p>
<p>Granted, when you're inserting, deleting or updating in LINQ-to-SQL, you have to use the object model. But obviously somewhere along the way it generates a query, which would be nice to pre-compile and store in a static member.</p>
<p>Is this possible? What is LINQ performance like for updates, deletes and inserts when its not pre-compiled? I could see it being a lot faster than the selects, because what they do underneath is a lot simpler and less "dynamic"...</p>
|
<p>There is a big difference. Linq-To-SQL select queries can be large complex expressions trees. Its these that may take sometime 'compiling'. In this case coalescing to some T-SQL that can be run against a SQL Server. So it makes sense to cache the result of an operation so that it can be re-used.</p>
<p>However other Delete, Update, and Insert are simple operations that do not require an expression tree to be converted to T-SQL (LINQ itself is all about querying). Its just unfortunate that we've been trained to think of SQL code that performs these other operations as 'queries', we're not actuall asking for any info.</p>
<p>These operations are only defined by the DataContext not by LINQ hence the code to perform these functions is already compiled.</p>
|
<p>L2S uses "sp_executeSQL" so after you run it the first time it will be in the stored procedure execution plan cache. Subsequent runs (of the same query - not same params) will reuse the compiled plan from the cache. So what you are asking for is automagically handled by SQL Server 'behind the scenes'.</p>
| 46,148
|
<p>I've been struggling with this check constraint for a few hours and was hoping someone would be kind enough to explain why this check constraint isn't doing what I think it should be doing.</p>
<pre><code>ALTER TABLE CLIENTS
add CONSTRAINT CHK_DISABILITY_INCOME_TYPE_ID CHECK ((IS_DISABLED IS NULL AND DISABILITY_INCOME_TYPE_ID IS NULL) OR (IS_DISABLED = 0 AND DISABILITY_INCOME_TYPE_ID IS NULL) OR (IS_DISABLED = 1));
</code></pre>
<p>Essentially, you must be disabled to collect disability income. It appears as though the first part of this check constraint <code>(IS_DISABLED IS NULL AND DISABILITY_INCOME_TYPE_ID IS NULL)</code> is not enforced (see below).</p>
<p>The available values for <code>DISABILITY_INCOME_TYPE_ID</code> are 1 and 2, which is enforced via foreign key. Both <code>IS_DISABLED</code> and <code>DISABILITY_INCOME_TYPE_ID</code> can be null.</p>
<pre><code>-- incorrectly succeeds (Why?)
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (null, 1);
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (null, 2);
-- correctly fails
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (0, 1);
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (0, 2);
-- correctly succeeds
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (0, null);
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (1, 1);
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (1, 2);
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (1, null);
INSERT INTO CLIENTS (IS_DISABLED, DISABILITY_INCOME_TYPE_ID) VALUES (null, null);
</code></pre>
<p>Thanks for your help,
Michael</p>
|
<p>While I do not have Oracle, I did a quick test with PostgreSQL and your first example (<code>IS_DISABLED</code> being <code>NULL</code> and <code>DISABILITY_INCOME_TYPE_ID</code> being 1):</p>
<pre><code>postgres=> select (null is null and 1 is null);
?column?
----------
f
(1 registro)
postgres=> select (null is null and 1 is null) or (null = 0 and 1 is null);
?column?
----------
f
(1 registro)
postgres=> select (null is null and 1 is null) or (null = 0 and 1 is null) or (null = 1);
?column?
----------
(1 registro)
</code></pre>
<p>Here we see clearly that, in this case, your expression (at least on PostgreSQL) returns NULL. From <a href="http://www.postgresql.org/docs/8.3/interactive/sql-createtable.html" rel="noreferrer">the manual</a>,</p>
<blockquote>
<p>[...] Expressions evaluating to TRUE or UNKNOWN succeed. Should any row of an insert or update operation produce a FALSE result an error exception is raised and the insert or update does not alter the database. [...]</p>
</blockquote>
<p>So, if Oracle behaves the same as PostgreSQL, the check constraint would <em>pass</em>.</p>
<p>To see if this is the case, avoid the NULL shenanigans by explicily checking for it and see if it works:</p>
<pre><code>CHECK ((IS_DISABLED IS NULL AND DISABILITY_INCOME_TYPE_ID IS NULL)
OR (IS_DISABLED IS NOT NULL AND IS_DISABLED = 0 AND DISABILITY_INCOME_TYPE_ID IS NULL)
OR (IS_DISABLED IS NOT NULL AND IS_DISABLED = 1));
</code></pre>
|
<p>This solution works.</p>
<pre><code>CHECK
((IS_DISABLED IS NULL AND NVL(DISABILITY_INCOME_TYPE_ID, 0) = 0)
OR (IS_DISABLED = 0 AND NVL(DISABILITY_INCOME_TYPE_ID, 0) = 0)
OR (IS_DISABLED IS NOT NULL AND IS_DISABLED = 1));
</code></pre>
| 37,177
|
<p>I have made some changes to a site and need to re-host it as the current host is ceasing to exist. My client has received the following from the current host:</p>
<p>"The best thing to tell them is that, due to the fact that we are withdrawing our service completely, we would look to fully transfer the web site address across to them rather than just "point" the web address at them. If you can forward this Email to them and ask them to
confirm their "IPS tag" (they'll know what that is), I can then arrange for it to be transferred as and when they confirm it's all ready to go."</p>
<p>Can anyone help me out here as i'm not too sure what they mean, nor do I know what an IPS tag is? ?</p>
|
<p>an IPSTAG is a .uk only designation of the domain's registrar. basically, the webhost is asking you to transfer the domain name registration away from them to a new provider.</p>
<p>i would suggest you (or your client) find a new registrar, get their IPSTAG, and then send that to your old host, who will then be able to initiate the change.</p>
<p>once the IPSTAG has been updated (you can check WHOIS information for that), then your new registrar will be able to get the domain name (and thus the old host will have relinquished "control" of it)</p>
<p>here's an example from amazon.co.uk's WHOIS:</p>
<pre><code>Domain name:
amazon.co.uk
Registrant:
Amazon Europe Holding Technologies SCS
Registrant type:
Unknown
Registrant's address:
65 boulevard G-D. Charlotte
Luxembourg City
Luxembourg
LU-1311
LU
Registrar:
Amazon.com [Tag = AMAZON-COM]
</code></pre>
<p>the IPSTAG in this case is "AMAZON-COM"</p>
|
<p>A quick Google search turns up </p>
<blockquote>
<p>Each Domain Name registration agent is identified by a unique IPSTAG assigned by the UK Governing body for UK Domain Names, Nominet. If you want to move a UK domain name to another Internet Service Provider, you will need to know the Tag Name of your new ISP.</p>
</blockquote>
| 38,971
|
<p>I am trying to link to a file that has the '#' character in via a window.open() call. The file does exist and can be linked to just fine using a normal anchor tag.</p>
<p>I have tried escaping the '#' character with '%23' but when the window.open(myurl) gets processed, the '%23' becomes '%2523'. This tells me that my url string is being escapped by the window.open call changing the '%' to the '%25'.</p>
<p>Are there ways to work around this extra escaping.</p>
<p>Sample code:</p>
<pre><code><script language="javascript">
function escapePound(url)
{
// original attempt
newUrl = url.replace("#", "%23");
// first answer attempt - doesn't work
// newUrl = url.replace("#", "\\#");
return newUrl;
}
</script>
<a href="#top" onclick="url = '\\\\MyUNCPath\\PropertyRushRefi-Add#1-ABCDEF.RTF'; window.open(escapePound(url)); return true;">Some Doc</a>
</code></pre>
<p>URL that yells says "file://MyUNCPath/PropertyRushRefi-Add%25231-ABCDEF.RTF" cannot be found</p>
|
<p>You seek the dark magicks of <a href="http://www.w3schools.com/jsref/jsref_encodeURI.asp" rel="nofollow noreferrer">encodeURI</a>:</p>
<pre><code>window.open("http://your-url.com/" + encodeURIComponent("foo#123.jpg"));
</code></pre>
|
<p>Did you try using the standard text escape char "\"?</p>
<pre><code>\#
</code></pre>
| 28,961
|
<p>Something i've never really done before, but what is the best way to make sure that any external assemblies/dll's that my application uses are available, and possibly the correct version.</p>
<p>I wrote an app that relies on the System.Data.SQLite.dll, i went to test it on a machine where that dll was missing, and my app just threw up a runtime exception because the dll was missing. How can i trap this error?</p>
|
<p>What you want to do is use reflection to check and see if the assembly can be loaded into memory. Wrap that up in a try..catch block and handle any of the specific exceptions that come from it.</p>
<pre><code>Try
Assembly.Load("System.Data.SQLite, Version=1.0.22.0, Culture=neutral, PublicKeyToken=DB937BC2D44FF139");
Catch ex As FileNotFoundException
//do something here
End Try
</code></pre>
|
<p>You should trap the error outside of your main loop.<br>
Or if you want to ship/locate your own assemblies you can try overriding the assembly probing: <a href="https://blogs.msdn.com/junfeng/archive/2006/03/27/561775.aspx" rel="nofollow noreferrer">Link</a>.</p>
| 13,371
|
<p>I'm looking for a good JavaScript RegEx to convert names to proper cases. For example:</p>
<pre><code>John SMITH = John Smith
Mary O'SMITH = Mary O'Smith
E.t MCHYPHEN-SMITH = E.T McHyphen-Smith
John Middlename SMITH = John Middlename SMITH
</code></pre>
<p>Well you get the idea.</p>
<p>Anyone come up with a comprehensive solution?</p>
|
<p>Something like this?</p>
<pre><code>function fix_name(name) {
var replacer = function (whole,prefix,word) {
ret = [];
if (prefix) {
ret.push(prefix.charAt(0).toUpperCase());
ret.push(prefix.substr(1).toLowerCase());
}
ret.push(word.charAt(0).toUpperCase());
ret.push(word.substr(1).toLowerCase());
return ret.join('');
}
var pattern = /\b(ma?c)?([a-z]+)/ig;
return name.replace(pattern, replacer);
}
</code></pre>
|
<p>Unfortunately there are too many different name formats to do this correctly. John-Joe MacDonald is always going to be a nuisance!</p>
| 31,198
|
<p>I have several properties that are dependent on the environment the application is running. For example, there are links to another application that is being developed concurrantly that get displayed in the header and footer. I want those links to be different depending on what environment they are in. </p>
<p>This is slightly different than the way we use the out of box enviornment configuration files because our system administrator has mongrel running in 'Production' mode even on the development server. I only run mongrel in 'Development' mode on my laptop. </p>
<p>Is there a standard way for handling situations like this? Or should we run mongrel in "Development" mode on the dev server and so on up the line. In that case, what happens if have an extra level in our env hierarchy. (Dev, Test, UAT, Production)</p>
|
<p>You can go with a custom config file. Check out <a href="https://stackoverflow.com/questions/110078/what-is-the-best-way-to-store-app-specific-configuration-in-rails#110834">this thread</a>.</p>
|
<p>Running in production mode on UAT is definitely correct, you want that to work as closely to production as possible.</p>
<p>I assume the test server is not a server where you run CI on the project test suite but more some kind of integration server where people from inside the team can test new features before the users get their hands on it: this is more of a mixed case, but I would probably have it run in dev mode actually if only for the clearer error messages and improved logging (a lot of bugs are bound to be found there and you will want maximum information)</p>
<p>I guesse the dev server is some kind of integration server for the devs themselves,here again, running it in dev mode would probably be more beneficial with regard to the errors raised and logs.</p>
<p>As for the answer to your specific question I would definitely have a look at the thread mentionned by @webmat since you should find your answer there and you could also have a look <a href="http://kpumuk.info/ruby-on-rails/flexible-application-configuration-in-ruby-on-rails/" rel="nofollow noreferrer">here</a></p>
| 14,854
|
<p>Hi i would to know how to se up a svn server? Now, i'm using VisualSVN a TortoiseSVN, but i don't know what are the directories "branch" "trunk" "tags".
Can anyone explain me how it works?
I read the svn book and many sites articles about it but i don't understand.</p>
|
<p>How to setup a SVN server is a very different question than what "branch", "trunk" and "tags" are used for.</p>
<p>A SVN server can be setup using a lot of different methods: Apache (with dav_svn), svnserve over SSH or countless others.</p>
<p>Take a look at the <a href="http://svnbook.red-bean.com/en/1.5/svn.serverconfig.html" rel="nofollow noreferrer">svn-book's chapter on server setup</a> for more information.</p>
<p>If you need more information on SVN in general, <a href="http://svnbook.red-bean.com/en/1.5/index.html" rel="nofollow noreferrer">the entire book</a> might be of use to you.</p>
<p>To get a quick overview of SVN, branching and tagging, take a look at the following Wikipedia articles:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Subversion_(software)" rel="nofollow noreferrer">Subversion</a>, with the section on <a href="http://en.wikipedia.org/wiki/Subversion_(software)#Branching_and_tagging" rel="nofollow noreferrer">branching and tagging</a>.</li>
<li><a href="http://en.wikipedia.org/wiki/Branching_(software)" rel="nofollow noreferrer">Branching</a></li>
<li><a href="http://en.wikipedia.org/wiki/Revision_tag" rel="nofollow noreferrer">Tagging</a></li>
</ul>
|
<p>I am a little uncertain whether your question concerns setting up an SVN server or whether you are more concerned with the structure of your project's evolution (setting up your trunk and various branches).</p>
<p>However, consider the possibility that you might <em>not</em> want to expend the time and energy needed to master SVN server management - especially if you still have this many questions after reading the documentation. After considering various options for our source control management strategy, we decided to use a third-party SVN-hosting service. We ended up using BeanStalk (<a href="http://www.beanstalkapp.com" rel="nofollow noreferrer">http://www.beanstalkapp.com</a>) along with Tortoise SVN and Visual SVN. I am not associated with BeanStalk but I can tell you that, for $15 a month, we've been very happy with the results. Note that we manage a web server farm so server availability was not at all an issue - only time and expertise - and we still decided to go to an outside vendor.</p>
| 46,871
|
<p>Convert.ToString() only allows base values of 2, 8, 10, and 16 for some odd reason; is there some obscure way of providing any base between 2 and 16?</p>
|
<p>Probably to eliminate someone typing a 7 instead of an 8, since the uses for arbitrary bases are few (But not non-existent).</p>
<p>Here is an example method that can do arbitrary base conversions. You can use it if you like, no restrictions.</p>
<pre><code>string ConvertToBase(int value, int toBase)
{
if (toBase < 2 || toBase > 36) throw new ArgumentException("toBase");
if (value < 0) throw new ArgumentException("value");
if (value == 0) return "0"; //0 would skip while loop
string AlphaCodes = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string retVal = "";
while (value > 0)
{
retVal = AlphaCodes[value % toBase] + retVal;
value /= toBase;
}
return retVal;
}
</code></pre>
<p>Untested, but you should be able to figure it out from here.</p>
|
<pre><code>string foo = Convert.ToString(myint,base);
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/14kwkz77.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/14kwkz77.aspx</a></p>
<p><strong>EDIT</strong>: My bad, this will throw an argument exception unless you pass in the specified bases (2, 8, 10, and 16)</p>
<p>Your probably SOL if you want to use a different base (but why???).</p>
| 12,073
|
<p>I'm trying to create a map application similar to <a href="http://flashden.net/item/zoom-pan-controls-with-dynamic-image-settings/15713" rel="nofollow noreferrer">this</a>. Click the SWF Preview tab on the left of the image. Specifically, noticed how you can pan around, and the clickable buttons on the map move with it. Basically, how do they do that?</p>
<p>My application has a map that you can click and pan around using a startDrag() function. I have a separate layer with other, clickable movie clips that I'd like to follow the pans of the map layer. Unfortunately, Flash limits you to dragging only <a href="http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary681.html" rel="nofollow noreferrer">one movie clip at a time</a>. Somebody proposed a solution using a <a href="http://proto.layer51.com/d.aspx?f=845" rel="nofollow noreferrer">prototype</a>, but I can't get that working correctly, and I'm not sure if it's because I'm using ActionScript 3.0 or not.</p>
<p>Can anybody outline a better way for me to accomplish what I'm trying to do, or a better way to do what I'm currently doing? Appreciate it.</p>
|
<p>Simple. Put your map <strong>and</strong> the clickable buttons into a new MovieClip, you could call it <em>interactiveMapContainer</em> or something similar, then call your startDrag method on <em>interactiveMapContainer</em> and you'll still be able to click the buttons once you've dragged it about.</p>
<p>Jakub Kotrla's method will also work very well, although it is slightly more complicated.</p>
|
<p>can you add the movieclips to a parent clip and have the event handler drag the parent?</p>
| 13,004
|
<p>One for the mathematicians. This has gone around the office and we want to see who can come up with a better optimised version.</p>
<pre><code>(((a+p) <= b) && (a == 0 || a > 1) && (b >= p)) &&
((b - (a + p) == 0) || (b - (a + p) > 1))
</code></pre>
<p><strong>Edit</strong>: all data is positive int's</p>
<p><strong>Edit</strong>: Better == simpler</p>
|
<pre><code>(a + p <= b) && (a != 1) && (b - a - p != 1);
</code></pre>
|
<pre><code>(((a+p) <= b) && (a == 0 || a > 1) && (b >= p)) && ((b - (a + p) == 0) || (b - (a + p) > 1))
</code></pre>
<p>since a >=0 (positive integers), the term (a == 0 || a > 1) is always true</p>
<p>if ((a+p) <= b) then (b >= p) is true when a,b,p are >=0</p>
<p>therefore ((a+p) <= b) && (a == 0 || a > 1) && (b >= p)) && ((b - (a + p) == 0) reduces to</p>
<pre><code>b>=(a+p)
</code></pre>
<p>(b - (a + p) == 0) || (b - (a + p) > 1) is equivalent to b>=(a+p)</p>
<p>therefore the whole equation reduces to</p>
<pre><code>**b>= (a+p)**
</code></pre>
| 49,913
|
<pre><code>void some_func(int param = get_default_param_value());
</code></pre>
|
<p>Default parameter can be a subset of the full set of expressions. It must be bound at compile time and at the place of declaration of the default parameter. This means that it can be a function call or a static method call, and it can take any number of arguments as far as they are constants and/or global variables or static class variables, but not member attributes. </p>
<p>The fact that it is bound at compile time and in the place where the function is declared also means that if it makes use of a variable, that variable will be used even if a different variable shadows the original at the place of the function call.</p>
<pre><code>// Code 1: Valid and invalid default parameters
int global = 0;
int free_function( int x );
class Test
{
public:
static int static_member_function();
int member_function();
// Valid default parameters
void valid1( int x = free_function( 5 ) );
void valid2( int x = free_function( global ) );
void valid3( int x = free_function( static_int ) );
void valid4( int x = static_member_function() );
// Invalid default parameters
void invalid1( int x = free_function( member_attribute ) );
void invalid2( int x = member_function() );
private:
int member_attribute;
static int static_int;
};
int Test::static_int = 0;
// Code 2: Variable scope
int x = 5;
void f( int a );
void g( int a = f( x ) ); // x is bound to the previously defined x
void h()
{
int x = 10; // shadows ::x
g(); // g( 5 ) is called: even if local x values 10, global x is 5.
}
</code></pre>
|
<p><code>David Rodríguez - dribeas</code> answear is great, but doesn't provide a solution.<br>
It may look like there is no solution.</p>
<p>Solution is quite simple: repalce default parameter with <strong>function/method overload</strong>.</p>
<pre><code>void some_func(int param);
void some_func() {
some_func(get_default_param_value());
}
</code></pre>
| 43,431
|
<p>I've got a button that I'm adding as a subview of a table view's tableHeaderView. The button appears fine, and tap-and-holding on it works intermittently - for the most part, though, it's unresponsive. I've tried adding it as a subview of the table itself; the effect is about the same. I thought the problem might be with the scroll view's touch interception, but disabling scrolling on the table has no effect either. </p>
<p>Am I doing something wrong? Has anyone else encountered this?</p>
<p>edit - to clarify, I'm talking about the main table header, not a section header, in a grouped-style table; think basically modeled after the "Contact" screen.</p>
|
<p>I had the same problem. In my case I had a container view instantiated in IB (that was applied as the table view header in code), with a UIImageView occupying the entire frame of that container. The misbehaving button resided in the image view.</p>
<p>Turns out I needed to have sizing struts in IB set as follows...</p>
<p>Container View: exterior anchors all on, interior resizing - all off</p>
<p>Sub Image View: all struts on (interior and exterior)</p>
<p>I had several different table views, all using header views. Some would respond to touch events correctly, some were flaky. This solved my problem</p>
|
<p>You should consider that this is not the intended sue of the headerView and that an implementation such as that might result in rejection from the AppStore as a result of a HIG violation. Given that the dimensions of a header are intended to be small, it is probably better to consider a restructuring of your view. Having said that, there is no easy way to do it short of hand detecting touch events and determining the geometry yourself, then executing a selector based on the geometry - in short, rolling your own button class.</p>
| 38,033
|
<p>What's the difference between</p>
<pre><code>var A = function () {
this.x = function () {
//do something
};
};
</code></pre>
<p>and</p>
<pre><code>var A = function () { };
A.prototype.x = function () {
//do something
};
</code></pre>
|
<p>The examples have very different outcomes.</p>
<p>Before looking at the differences, the following should be noted:</p>
<ul>
<li>A constructor's <em>prototype</em> provides a way to share methods and values among instances via the instance's private <code>[[Prototype]]</code> property.</li>
<li>A function's <em>this</em> is set by how the function is called or by the use of <em>bind</em> (not discussed here). Where a function is called on an object (e.g. <code>myObj.method()</code>) then <em>this</em> within the method references the object. Where <em>this</em> is not set by the call or by the use of <em>bind</em>, it defaults to the global object (window in a browser) or in strict mode, remains undefined.</li>
<li>JavaScript is an object-oriented language, i.e. most values are objects, including functions. (Strings, numbers, and booleans are <em>not</em> objects.)</li>
</ul>
<p>So here are the snippets in question:</p>
<pre><code>var A = function () {
this.x = function () {
//do something
};
};
</code></pre>
<p>In this case, variable <code>A</code> is assigned a value that is a reference to a function. When that function is called using <code>A()</code>, the function's <em>this</em> isn't set by the call so it defaults to the global object and the expression <code>this.x</code> is effective <code>window.x</code>. The result is that a reference to the function expression on the right-hand side is assigned to <code>window.x</code>.</p>
<p>In the case of:</p>
<pre><code>var A = function () { };
A.prototype.x = function () {
//do something
};
</code></pre>
<p>something very different occurs. In the first line, variable <code>A</code> is assigned a reference to a function. In JavaScript, all functions objects have a <em>prototype</em> property by default so there is no separate code to create an <em>A.prototype</em> object.</p>
<p>In the second line, <em>A.prototype.x</em> is assigned a reference to a function. This will create an <em>x</em> property if it doesn't exist, or assign a new value if it does. So the difference with the first example in which object's <em>x</em> property is involved in the expression.</p>
<p>Another example is below. It's similar to the first one (and maybe what you meant to ask about):</p>
<pre><code>var A = new function () {
this.x = function () {
//do something
};
};
</code></pre>
<p>In this example, the <code>new</code> operator has been added before the function expression so that the function is called as a constructor. When called with <code>new</code>, the function's <em>this</em> is set to reference a new Object whose private <code>[[Prototype]]</code> property is set to reference the constructor's public <em>prototype</em>. So in the assignment statement, the <code>x</code> property will be created on this new object. When called as a constructor, a function returns its <em>this</em> object by default, so there is no need for a separate <code>return this;</code> statement.</p>
<p>To check that <em>A</em> has an <em>x</em> property:</p>
<pre><code>console.log(A.x) // function () {
// //do something
// };
</code></pre>
<p>This is an uncommon use of <em>new</em> since the only way to reference the constructor is via <em>A.constructor</em>. It would be much more common to do:</p>
<pre><code>var A = function () {
this.x = function () {
//do something
};
};
var a = new A();
</code></pre>
<p>Another way of achieving a similar result is to use an immediately invoked function expression:</p>
<pre><code>var A = (function () {
this.x = function () {
//do something
};
}());
</code></pre>
<p>In this case, <code>A</code> assigned the return value of calling the function on the right-hand side. Here again, since <em>this</em> is not set in the call, it will reference the global object and <code>this.x</code> is effective <code>window.x</code>. Since the function doesn't return anything, <code>A</code> will have a value of <code>undefined</code>.</p>
<p>These differences between the two approaches also manifest if you're serializing and de-serializing your Javascript objects to/from JSON. Methods defined on an object's prototype are not serialized when you serialize the object, which can be convenient when for example you want to serialize just the data portions of an object, but not it's methods:</p>
<pre><code>var A = function () {
this.objectsOwnProperties = "are serialized";
};
A.prototype.prototypeProperties = "are NOT serialized";
var instance = new A();
console.log(instance.prototypeProperties); // "are NOT serialized"
console.log(JSON.stringify(instance));
// {"objectsOwnProperties":"are serialized"}
</code></pre>
<p><strong>Related questions</strong>:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/186244/what-does-it-mean-that-javascript-is-a-prototype-based-language"><strong>What does it mean that JavaScript is a prototypal language?</strong></a></li>
<li><a href="https://stackoverflow.com/questions/235360/what-is-the-scope-of-a-function-in-javascriptecmascript"><strong>What is the scope of a function in JavaScript?</strong></a></li>
<li><strong><a href="https://stackoverflow.com/questions/3127429/javascript-this-keyword">How does the "this" keyword work?</a></strong></li>
</ul>
<p><strong>Sidenote:</strong> There may not be any significant memory savings between the two approaches, however using the prototype to share methods and properties will likely use less memory than each instance having its own copy.</p>
<p>JavaScript isn't a low-level language. It may not be very valuable to think of prototyping or other inheritance patterns as a way to explicitly change the way memory is allocated.</p>
|
<p>When you use prototype, the function will only be loaded only once into memory (independently on the amount of objects you create) and you can override the function whenever you want.</p>
| 40,061
|
<p>I have a RDLC report which has a table, calling a subreport N times. This works perfectly in the control viewer and when I export to PDF. Yet when I export to Excel, I get the following error:</p>
<blockquote>
<p>Subreports within table/matrix cells
are ignored.</p>
</blockquote>
<p>Does anyone know why this occurs only within the Excel export? And is there a workaround?</p>
|
<p>See MSDN forum link below...looks like this is not supported in 2000/2005, but there also seem to be some kludgey workarounds (nested lists). A Microsoft moderator claims that reporting services 2008 will export everything.</p>
<p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1520229&SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1520229&SiteID=1</a></p>
|
<p>Drop the table control from rdlc and Put your main report data into matrix control and put your sub reports below to maix control.
Run your report and export again.It will be solved.</p>
| 15,721
|
<p>I'm using <code>Microsoft's DSOFramer</code> control to allow me to embed an Excel file in my dialog so the user can choose his sheet, then select his range of cells; it's used with an import button on my dialog.</p>
<p>The problem is that when I call the <code>DSOFramer's OPEN</code> function, if I have Excel open in another window, it closes the Excel document (but leaves Excel running). If the document it tries to close has unsaved data, I get a dialog boxclosing Excel doc in another window. If unsaved data in file, <code>dsoframer</code> fails to open with a messagebox: <code>Attempt to access invalid address</code>. </p>
<p>I built the source, and stepped through, and its making a call in its <code>CDsoDocObject::CreateFromFile</code> function, calling <code>BindToObject</code> on an object of class IMoniker. The <code>HR</code> is <code>0x8001010a</code> <code>The message filter indicated that the application is busy</code>. On that failure, it tries to <code>InstantiateDocObjectServer</code> by <code>classid</code> of <code>CLSID</code> Microsoft Excel Worksheet... this fails with an <code>HRESULT</code> of <code>0x80040154</code> <code>Class not registered</code>. The <code>InstantiateDocObjectServer</code> just calls <code>CoCreateInstance</code> on the <code>classid</code>, first with <code>CLSCTX_LOCAL_SERVER</code>, then (if that fails) with <code>CLSCTX_INPROC_SERVER</code>.</p>
<p>I know <code>DSOFramer</code> is a popular sample project for embedding Office apps in various dialog and forms. I'm hoping someone else has had this problem and might have some insight on how I can solve this. I really don't want it to close any other open Excel documents, and I really don't want it to error-out if it can't close the document due to unsaved data.</p>
<p>Update 1: I've tried changing the <code>classid</code> that's passed in to <code>Excel.Application</code> (I know that class will resolve), but that didn't work. In <code>CDsoDocObject</code>, it tries to open key <code>HKEY_CLASSES_ROOT\CLSID\{00024500-0000-0000-C000-000000000046}\DocObject</code>, but fails. I've visually confirmed that the key is not present in my registry; The key is present for the guide, but there's no <code>DocObject</code> subkey. It then produces an error message box: <code>The associated COM server does not support ActiveX document embedding</code>. I get similar (different key, of course) results when I try to use the <code>Excel.Workbook programid</code>.</p>
<p><strong>Update 2: I tried starting a 2nd instance of Excel, hoping that my automation would bind to it (being the most recently invoked) instead of the problem Excel instance, but it didn't seem to do that. Results were the same. My problem seems to have boiled down to this: I'm calling the <code>BindToObject</code> on an object of class <code>IMoniker</code>, and receiving <code>0x8001010A (RPC_E_SERVERCALL_RETRYLATER)</code> <code>The message filter indicated that the application is busy</code>. I've tried playing with the flags passed to the <code>BindToObject</code> (via the <code>SetBindOptions</code>), but nothing seems to make any difference.</strong></p>
<p><strong>Update 3: It first tries to bind using an IMoniker class. If that fails, it calls <code>CoCreateInstance</code> for the <code>clsid</code> as a <code>fallback</code> method. This may work for other MS Office objects, but when it's Excel, the class is for the Worksheet. I modified the sample to <code>CoCreateInstance _Application</code>, then got the workbooks, then called the <code>Workbooks::Open</code> for the target file, which returns a Worksheet object. I then returned that pointer and merged back with the original sample code path. All working now.</strong></p>
|
<pre><code>C-u M-! date
</code></pre>
|
<p>Here's my take on it. </p>
<pre class="lang-el prettyprint-override"><code>(defun modi/insert-time-stamp (option)
"Insert date, time, user name - DWIM.
If the point is NOT in a comment/string, the time stamp is inserted prefixed
with `comment-start' characters.
If the point is IN a comment/string, the time stamp is inserted without the
`comment-start' characters. If the time stamp is not being inserted immediately
after the `comment-start' characters (followed by optional space),
the time stamp is inserted with “--” prefix.
If the buffer is in a major mode where `comment-start' var is nil, no prefix is
added regardless.
Additional control:
C-u -> Only `comment-start'/`--' prefixes are NOT inserted
C-u C-u -> Only user name is NOT inserted
C-u C-u C-u -> Both prefix and user name are not inserted."
(interactive "P")
(let ((current-date-time-format "%a %b %d %H:%M:%S %Z %Y"))
;; Insert a space if there is no space to the left of the current point
;; and it's not at the beginning of a line
(when (and (not (looking-back "^ *"))
(not (looking-back " ")))
(insert " "))
;; Insert prefix only if `comment-start' is defined for the major mode
(when (stringp comment-start)
(if (or (nth 3 (syntax-ppss)) ; string
(nth 4 (syntax-ppss))) ; comment
;; If the point is already in a comment/string
(progn
;; If the point is not immediately after `comment-start' chars
;; (followed by optional space)
(when (and (not (or (equal option '(4)) ; C-u or C-u C-u C-u
(equal option '(64))))
(not (looking-back (concat comment-start " *")))
(not (looking-back "^ *")))
(insert "--")))
;; If the point is NOT in a comment
(progn
(when (not (or (equal option '(4)) ; C-u or C-u C-u C-u
(equal option '(64))))
(insert comment-start)))))
;; Insert a space if there is no space to the left of the current point
;; and it's not at the beginning of a line
(when (and (not (looking-back "^ *"))
(not (looking-back " ")))
(insert " "))
(insert (format-time-string current-date-time-format (current-time)))
(when (not (equal option '(16))) ; C-u C-u
(insert (concat " - " (getenv "USER"))))
;; Insert a space after the time stamp if not at the end of the line
(when (not (looking-at " *$"))
(insert " "))))
</code></pre>
<p>I prefer to bind this to <code>C-c d</code>.</p>
| 31,387
|
<p>I've always been mystified how software vendors can ship their application or game, and then later provide a different set of executables that change the behaviors of the previous build. How is this done? Do the original application and the patch have to adhere to some kind of rule? Or does the patch crawl into the original executable and change its assembly information? Would that require knowledge of the binary file to the byte level?</p>
|
<p>There are two main methods I have seen. Many programs are composed of a number of smaller parts that are dynamically loaded at runtime, often these files are simply replaced with newer versions. Since updates often only affect a relatively small number of these files the patch may be a small subset of the entire application. The other method, which I've seen used with larger monolithic applications, is to actually change the executable code using a sort of "binary diff". One of the drawbacks with this approach is that it is more difficult to support upgrading to a new version from a version several revisions prior without having to perform each incremental update.</p>
|
<p>I suspect that most of the time, "patches" are just some replacement files.</p>
<p>It is, however, possible to compare two binary files, determine their differences, and create a set of edit commands that will change one into the other. The Unix utility "diff" can do this for text files, for example.</p>
| 29,375
|
<p><b>Executive Summary:</b> When assertion errors are thrown in the threads, the unit test doesn't die. This makes sense, since one thread shouldn't be allowed to crash another thread. The question is how do I either 1) make the whole test fail when the first of the helper threads crashes or 2) loop through and determine the state of each thread after they have all completed (see code below). One way of doing the latter is by having a per thread status variable, e.g., "boolean[] statuses" and have "statuses[i] == false" mean that the thread failed (this could be extended to capture more information). However, that is not what I want: I want it to fail just like any other unit test when the assertion errors are thrown. Is this even possible? Is it desirable?</p>
<p>I got bored and I decided to spawn a bunch of threads in my unit test and then have them call a service method, just for the heck of it. The code looks approximately like:</p>
<pre><code>Thread[] threads = new Thread[MAX_THREADS];
for( int i = 0; i < threads.length; i++ ) {
threads[i] = new Thread( new Runnable() {
private final int ID = threadIdSequenceNumber++;
public void run() {
try {
resultRefs[ID] = runTest( Integer.toString( ID ) ); // returns an object
}
catch( Throwable t ) {
// this code is EVIL - it catches even
// Errors - don't copy it - more on this below
final String message = "error testing thread with id => "
+ ID;
logger.debug( message, t );
throw new IllegalStateException( message, t );
// need to wrap throwable in a
// run time exception so it will compile
}
}
} );
}
</code></pre>
<p>After this, we will loop through the array of threads and start each one. After that we will wait for them all to finish. Finally, we will perform some checks on the result references.</p>
<pre><code>for( Thread thread : threads )
thread.start();
logger.debug( "waiting for threads to finish ..." );
boolean done = false;
while( !done ) {
done = true;
for( Thread thread : threads )
if( thread.isAlive() )
done = false;
}
for( int i = 0; i < resultRefs.length; i++ ) {
assertTrue( "you've got the world messed, dawg!",
myCondition(resultRefs[i]) );
</code></pre>
<p>Here's the problem. Did you notice that nasty try-catch-throwable block? I just added that as a temporary hack so I could see what was going on. In runTest( String ) a few assertions are made, e.g., assertNotNull( null ), but since it is in a different thread, it doesn't cause the unit test to fail!!!!</p>
<p>My guess is that we will need to somehow iterate over the threads array, check the status of each, and manually cause an assertion error if the thread terminated in a nasty way. What's the name of the method that gives this information (the stack trace of the dead thread).</p>
|
<p>Concurrency is one of those things that are very difficult to unit test. If you are just trying to test that the code inside each thread is doing what it is supposed to test, may be you should just test this code isolated of the context.
If in this example the threads collaborate to reach a result, may be you can test that collaboration without using threads. That would be done by executing all the collaborative parts sequentially.
If you want to test for race conditions and these kind of things, unit testing is not the best way. You will get tests that sometimes fail and sometimes don´t fail.
To summarize, I think that may be your problem is that you are unit testing in a level too high.
Hope this helps</p>
|
<p>Another popular option for Junit concurrent thread testing is Matthieu Carbou's method using a custom JunitRunner and a simple annotation.</p>
<p><a href="http://www.junit.org/node/589" rel="nofollow">See the full documentation</a></p>
| 40,595
|
<p>I am building an enclosure for an Ender 3 Pro printer, and am planning on the power supply and LCD unit being outside the enclosure. How important is it to move the printer controller (where the SD card is inserted) outside the enclosure?
Would leaving it in place affect its longevity?</p>
<p>Answers to the first round of comments/questions:</p>
<ul>
<li>I expect to be primarily printing in the 200C-270C range.</li>
<li>I'm not worried about losing heat from opening the doors - I'll be putting the SD card in prior to initiating printing.</li>
<li>I'm thinking the stepper motors are somewhat of a moot point, there's no way I could move them outside of the enclosure.</li>
<li>My printer is all stock.</li>
</ul>
|
<p>It depends on what kinds of prints you make, and especially what kind of materials you want to use.</p>
<p>Certain materials (ABS especially, but also PETG to some degree) will print <em>much better</em> if the entire build area, which usually includes the printer chassis and controls, is enclosed to protect from drafts and allow a much higher ambient temperature.</p>
<p>If you print often with these materials, and the control board is included in that enclosed area, you <em><strong>will</strong></em> significantly reduce the life of the electronic components, <a href="https://en.wikipedia.org/wiki/Capacitor_plague" rel="nofollow noreferrer">especially the capacitors on the board</a><sup>1</sup>.</p>
<p>On the other hand, if you print mainly with PLA, which is not as susceptible to issues requiring an enclosure, and prints better with an ambient temperature closer to room temperature, you can put the electronic controls wherever you want.</p>
<hr />
<p><sub>1 See especially this excerpt from the section on "Premature Failure":</p>
<blockquote>
<p>Electrolytic capacitors that operate at a lower temperature can have a considerably longer lifespan.
</sub></p>
</blockquote>
|
<p>This guy placed the whole Ender in a 100C environment but he emphasises how important it is to leave the electronics cool:</p>
<p><div class="youtube-embed"><div>
<iframe width="640px" height="395px" src="https://www.youtube.com/embed/79r5D9nCQfM?start=1216"></iframe>
</div></div></p>
| 1,716
|
<p>Is it possible to reach the individual columns of table2 using HQL with a configuration like this?</p>
<pre><code><hibernate-mapping>
<class table="table1">
<set name="table2" table="table2" lazy="true" cascade="all">
<key column="result_id"/>
<many-to-many column="group_id"/>
</set>
</class>
</hibernate-mapping>
</code></pre>
|
<p>They're just properties of table1's table2 property.</p>
<pre><code>select t1.table2.property1, t1.table2.property2, ... from table1 as t1
</code></pre>
<p>You might have to join, like so</p>
<pre><code>select t2.property1, t2.property2, ...
from table1 as t1
inner join t1.table2 as t2
</code></pre>
<p>Here's the relevant part of the <a href="http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html#queryhql-select" rel="nofollow noreferrer">hibernate doc</a>.</p>
|
<p>Let's say table2 has a column "<code>color varchar(128)</code>" and this column is properly mapped to Hibernate.</p>
<p>You should be able to do something like this:</p>
<pre><code>from table1 where table2.color = 'red'
</code></pre>
<p>This will return all <code>table1</code> rows that are linked to a <code>table2</code> row whose <code>color</code> column is 'red'. Note that in your Hibernate mapping, your <code>set</code> has the same name as the table it references. The above query uses the name of the <em>set</em>, <strong>not</strong> the name of the table.</p>
| 10,086
|
<p>We have a few projects that involve building an application that is composed of maybe 50% custom functionality, but then pulls in, say, a wiki, a forum, and other components that are "wheels" that have already been invented that we do not wish to re-write from scratch.</p>
<p>These third-party applications usually have their own databases, themes, and authentication systems. Getting things to work like a single-sign-on, or a common theme, or tagging/searching across entities in multiple sub-apps are pretty challenging problems, in my experience. What are some of the best practices for this kind of integration project?</p>
<p>Our approach, so far, has been to try and pick your components carefully, choosing ones that have a clearly defined API, preferably via HTTP (like REST or SOAP), though that isn't always possible (we haven't found a decent forum that works that way). Are there suggestions folks can give to anyone trying to do this, as I suspect many of us are more and more frequently these days?</p>
|
<p>Make sure that the interface between your application and the third-party application or library is such that you can replace it easily with something else just in case. In some cases the third-party software may just be an implementation of an standard API (Java does this a lot with JDBC, JMS, JNDI, ...). In other cases this means wrapping the third-party library in some API that you come up with. </p>
<p>Of course there are times to throw that idea out the window and have things tightly integrated with the third-party software. Just be sure that you REALLY want to bind your application to that third-party. Once you go down this road it's REALLY hard to go back and change your mind. </p>
|
<p>Donald Knuth said that even better then reusable code is modifiable code, so if there is no API, you should seek for an open source app that is written well and therefore possible to customize. </p>
<p>As for databases and login systems and other programming parts (i don't see how e.g. theming could benefit), you can also try, depending on circumstances wrapping stuff so that module believes it's on it's own, but actually talks to your code.</p>
| 7,074
|
<p>I'm trying to create a function which takes an array as an argument, adds values to it (increasing its size if necessary) and returns the count of items.
So far I have:</p>
<pre><code>int main(int argc, char** argv) {
int mSize = 10;
ent a[mSize];
int n;
n = addValues(a,mSize);
for(i=0;i<n;i++) {
//Print values from a
}
}
int addValues(ent *a, int mSize) {
int size = mSize;
i = 0;
while(....) { //Loop to add items to array
if(i>=size-1) {
size = size*2;
a = realloc(a, (size)*sizeof(ent));
}
//Add to array
i++;
}
return i;
}
</code></pre>
<p>This works if mSize is large enough to hold all the potential elements of the array, but if it needs resizing, I get a Segmentation Fault.</p>
<p>I have also tried:</p>
<pre><code>int main(int argc, char** argv) {
...
ent *a;
...
}
int addValues(ent *a, int mSize) {
...
a = calloc(1, sizeof(ent);
//usual loop
...
}
</code></pre>
<p>To no avail.</p>
<p>I assume this is because when I call realloc, the copy of 'a' is pointed elsewhere - how is it possible to modify this so that 'a' always points to the same location?</p>
<p>Am I going about this correctly? Are there better ways to deal with dynamic structures in C? Should I be implementing a linked list to deal with these?</p>
|
<p>The main problem here is that you're trying to use realloc with a stack-allocated array. You have:</p>
<pre><code>ent a[mSize];
</code></pre>
<p>That's automatic allocation on the stack. If you wanted to use realloc() on this later, you would create the array on the heap using malloc(), like this:</p>
<pre><code>ent *a = (ent*)malloc(mSize * sizeof(ent));
</code></pre>
<p>So that the malloc library (and thus realloc(), etc.) knows about your array. From the looks of this, you may be confusing <a href="http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html" rel="nofollow noreferrer">C99 variable-length arrays</a> with true <a href="http://en.wikipedia.org/wiki/Dynamic_array" rel="nofollow noreferrer">dynamic arrays</a>, so be sure you understand the difference there before trying to fix this.</p>
<p>Really, though, if you are writing dynamic arrays in C, you should try to use OOP-ish design to encapsulate information about your arrays and hide it from the user. You want to consolidate information (e.g. pointer and size) about your array into a struct and operations (e.g. allocation, adding elements, removing elements, freeing, etc.) into special functions that work with your struct. So you might have:</p>
<pre><code>typedef struct dynarray {
elt *data;
int size;
} dynarray;
</code></pre>
<p>And you might define some functions to work with dynarrays:</p>
<pre><code>// malloc a dynarray and its data and returns a pointer to the dynarray
dynarray *dynarray_create();
// add an element to dynarray and adjust its size if necessary
void dynarray_add_elt(dynarray *arr, elt value);
// return a particular element in the dynarray
elt dynarray_get_elt(dynarray *arr, int index);
// free the dynarray and its data.
void dynarray_free(dynarray *arr);
</code></pre>
<p>This way the user doesn't have to remember exactly how to allocate things or what size the array is currently. Hope that gets you started.</p>
|
<p>Xahtep explains how your caller can deal with the fact that realloc() might move the array to a new location. As long as you do this, you should be fine.</p>
<p>realloc() might get expensive if you start working with large arrays. That's when it's time to start thinking of using other data structures -- a linked list, a binary tree, etc.</p>
| 44,355
|
<p>Unquestionably, I would choose to use the STL for most C++ programming projects. The question was presented to me recently however, "Are there any cases where you wouldn't use the STL?"...</p>
<p>The more I thought about it, the more I realized that perhaps there SHOULD be cases where I choose not to use the STL... For example, a really large, long term project whose codebase is expected to last years... Perhaps a custom container solution that precisely fits the projects needs is worth the initial overhead? What do you think, are there any cases where you would choose NOT to STL?</p>
|
<p>The main reasons not to use STL are that:</p>
<ol>
<li>Your C++ implementation is old and has horrible template support.</li>
<li>You can't use dynamic memory allocation.</li>
</ol>
<p>Both are very uncommon requirements in practice.</p>
<p>For a longterm project rolling your own containers that overlap in functionality with the STL is just going to increase maintenance and development costs. </p>
|
<p>I started programming C back in about 1984 or so and have never used the STL. Over the years I have rolled my own function librarys and they have evolved and grown when the STL was not stable yet and or lacked cross platform support. My common library has grown to include code by others ( mostly things like libjpeg, libpng, ffmpeg, mysql ) and a few others and I would rather keep the amount of external code in it to a minimum. I'm sure now the STL is great but frankly I'm happy with the items in my toolbox and see no need at this point to load it up with more tools. But I certainly see the great leaps and bounds that new programmers can make by using the STL without having to code all that from scratch. </p>
| 21,028
|
<p>I have some controller methods I'd like to share. What is the best practice for doing this in ruby on rails? Should I create an abstract class that my controllers extend, or should I create module and add it in to each controller? Below are the controller methods I want to share:</p>
<pre><code>def driving_directions
@address_to = params[:address_to]
@address_from = params[:address_from]
@map_center = params[:map_center_start]
# if we were not given a center point to start our map on
# let's create one.
if !@map_center && @address_to
@map_center = GeoKit::Geocoders::MultiGeocoder.geocode(@address_to).ll
elsif !@map_center && @address_from
@map_center = GeoKit::Geocoders::MultiGeocoder.geocode(@address_from).ll
end
end
def printer_friendly
starting_point = params[:starting_point].split(',').collect{|e|e.to_f}
ne = params[:ne].split(',').collect{|e|e.to_f}
sw = params[:sw].split(',').collect{|e|e.to_f}
size = params[:size].split(',').collect{|e|e.to_f}
address = params[:address]
@markers = retrieve_points(ne,sw,size,false)
@map = initialize_map([[sw[0],sw[1]],[ne[0],ne[1]]],[starting_point[0],starting_point[1]],false,@markers,true)
@address_string = address
end
</code></pre>
|
<p>In my opinion, normal OO design principles apply:</p>
<ul>
<li>If the code is really a set of utilities that doesn't need access to object state, I would consider putting it in a module to be called separately. For instance, if the code is all mapping utilities, create a module <code>Maps</code>, and access the methods like: <code>Maps::driving_directions</code>.</li>
<li>If the code needs state and is used or could be used in every controller, put the code in ApplicationController.</li>
<li>If the code needs state and is used in a subset of all controllers that are closely and logically related (i.e. all about maps) then create a base class (<code>class MapController < ApplicationController</code>) and put the shared code there.</li>
<li>If the code needs state and is used in a subset of all controllers that are not very closely related, put it in a module and include it in necessary controllers.</li>
</ul>
<p>In your case, the methods need state (<code>params</code>), so the choice depends on the logical relationship between the controllers that need it.
In addition:</p>
<p>Also:</p>
<ul>
<li>Use partials when possible for repeated code and either place in a common 'partials' directory or include via a specific path.</li>
<li>Stick to a RESTful approach when possible (for methods) and if you find yourself creating a lot of non-RESTful methods consider extracting them to their own controller.</li>
</ul>
|
<p>Another possibility:</p>
<p>If your common code needs state and you want to share the behavior amongst controllers, you could put it in a plain old ruby class in either your <code>model</code> or <code>lib</code> directory. Remember that <code>model</code> classes don't have to be persistent even though all ActiveRecord classes are persistent. In other words, it's acceptable to have transient <code>model</code> classes. </p>
| 15,629
|
<p>Can anyone provide a clear explanation / example of what these functions do, and when it's appropriate to use them?</p>
|
<p>Straight from <a href="http://www.postgresql.org/docs/8.3/static/ddl-constraints.html#DDL-CONSTRAINTS-FK" rel="noreferrer">the manual</a>...</p>
<blockquote>
<p>We know that the foreign keys disallow creation of orders that do not relate to any products. But what if a product is removed after an order is created that references it? SQL allows you to handle that as well. Intuitively, we have a few options:</p>
<p>Disallow deleting a referenced product</p>
<p>Delete the orders as well</p>
<p>Something else?</p>
</blockquote>
<pre><code>CREATE TABLE order_items (
product_no integer REFERENCES products ON DELETE RESTRICT,
order_id integer REFERENCES orders ON DELETE CASCADE,
quantity integer,
PRIMARY KEY (product_no, order_id)
);
</code></pre>
<blockquote>
<p>Restricting and cascading deletes are the two most common options. RESTRICT prevents deletion of a referenced row. NO ACTION means that if any referencing rows still exist when the constraint is checked, an error is raised; this is the default behavior if you do not specify anything. (The essential difference between these two choices is that NO ACTION allows the check to be deferred until later in the transaction, whereas RESTRICT does not.) CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well. There are two other options: SET NULL and SET DEFAULT. These cause the referencing columns to be set to nulls or default values, respectively, when the referenced row is deleted. Note that these do not excuse you from observing any constraints. For example, if an action specifies SET DEFAULT but the default value would not satisfy the foreign key, the operation will fail.</p>
<p>Analogous to ON DELETE there is also ON UPDATE which is invoked when a referenced column is changed (updated). The possible actions are the same.</p>
</blockquote>
<p><strong>edit:</strong> You might want to take a look at this related question: <a href="https://stackoverflow.com/questions/59297/whenwhy-to-use-cascading-in-sql-server">When/Why to use Cascading in SQL Server?</a>. The concepts behind the question/answers are the same.</p>
|
<p>I have a PostGreSQL database and I use On Delete when I have a user that I delete from the database and I need to delete it's information from other table. This ways I need to do only 1 delete and FK that has ON delete will delete information from other table.</p>
<p>You can do the same with ON Update. If you update the table and the field have a FK with On Update, if a change is made on the FK you will be noticed on the FK table.</p>
| 27,924
|
<p>I have a Monthly Status database view I need to build a report based on. The data in the view looks something like this:</p>
<pre><code>Category | Revenue | Yearh | Month
Bikes 10 000 2008 1
Bikes 12 000 2008 2
Bikes 12 000 2008 3
Bikes 15 000 2008 1
Bikes 11 000 2007 2
Bikes 11 500 2007 3
Bikes 15 400 2007 4
</code></pre>
<p><br/>
... And so forth</p>
<p>The view has a product category, a revenue, a year and a month. I want to create a report comparing 2007 and 2008, showing 0 for the months with no sales. So the report should look something like this:</p>
<pre><code>Category | Month | Rev. This Year | Rev. Last Year
Bikes 1 10 000 0
Bikes 2 12 000 11 000
Bikes 3 12 000 11 500
Bikes 4 0 15 400
</code></pre>
<p><br/>
The key thing to notice is how month 1 only has sales in 2008, and therefore is 0 for 2007. Also, month 4 only has no sales in 2008, hence the 0, while it has sales in 2007 and still show up.</p>
<p>Also, the report is actually for financial year - so I would love to have empty columns with 0 in both if there was no sales in say month 5 for either 2007 or 2008.</p>
<p>The query I got looks something like this:</p>
<pre><code>SELECT
SP1.Program,
SP1.Year,
SP1.Month,
SP1.TotalRevenue,
IsNull(SP2.TotalRevenue, 0) AS LastYearTotalRevenue
FROM PVMonthlyStatusReport AS SP1
LEFT OUTER JOIN PVMonthlyStatusReport AS SP2 ON
SP1.Program = SP2.Program AND
SP2.Year = SP1.Year - 1 AND
SP1.Month = SP2.Month
WHERE
SP1.Program = 'Bikes' AND
SP1.Category = @Category AND
(SP1.Year >= @FinancialYear AND SP1.Year <= @FinancialYear + 1) AND
((SP1.Year = @FinancialYear AND SP1.Month > 6) OR
(SP1.Year = @FinancialYear + 1 AND SP1.Month <= 6))
ORDER BY SP1.Year, SP1.Month
</code></pre>
<p>The problem with this query is that it would not return the fourth row in my example data above, since we didn't have any sales in 2008, but we actually did in 2007.</p>
<p>This is probably a common query/problem, but my SQL is rusty after doing front-end development for so long. Any help is greatly appreciated!</p>
<p>Oh, btw, I'm using SQL 2005 for this query so if there are any helpful new features that might help me let me know.</p>
|
<p>The Case Statement is my best sql friend. You also need a table for time to generate your 0 rev in both months.</p>
<p>Assumptions are based on the availability of following tables:</p>
<blockquote>
<p>sales: Category | Revenue | Yearh |
Month</p>
</blockquote>
<p>and</p>
<blockquote>
<p>tm: Year | Month (populated with all
dates required for reporting)</p>
</blockquote>
<p>Example 1 without empty rows:</p>
<pre><code>select
Category
,month
,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year
,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year
from
sales
where
year in (2008,2007)
group by
Category
,month
</code></pre>
<p>RETURNS:</p>
<pre><code>Category | Month | Rev. This Year | Rev. Last Year
Bikes 1 10 000 0
Bikes 2 12 000 11 000
Bikes 3 12 000 11 500
Bikes 4 0 15 400
</code></pre>
<p>Example 2 with empty rows:
I am going to use a sub query (but others may not) and will return an empty row for every product and year month combo.</p>
<pre><code>select
fill.Category
,fill.month
,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year
,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year
from
sales
Right join (select distinct --try out left, right and cross joins to test results.
product
,year
,month
from
sales --this ideally would be from a products table
cross join tm
where
year in (2008,2007)) fill
where
fill.year in (2008,2007)
group by
fill.Category
,fill.month
</code></pre>
<p>RETURNS:</p>
<pre><code>Category | Month | Rev. This Year | Rev. Last Year
Bikes 1 10 000 0
Bikes 2 12 000 11 000
Bikes 3 12 000 11 500
Bikes 4 0 15 400
Bikes 5 0 0
Bikes 6 0 0
Bikes 7 0 0
Bikes 8 0 0
</code></pre>
<p>Note that most reporting tools will do this crosstab or matrix functionality, and now that i think of it SQL Server 2005 has pivot syntax that will do this as well.</p>
<p>Here are some additional resources.
CASE
<a href="https://web.archive.org/web/20210728081626/https://www.4guysfromrolla.com/webtech/102704-1.shtml" rel="noreferrer">https://web.archive.org/web/20210728081626/https://www.4guysfromrolla.com/webtech/102704-1.shtml</a>
SQL SERVER 2005 PIVOT
<a href="http://msdn.microsoft.com/en-us/library/ms177410.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms177410.aspx</a></p>
|
<p>Using pivot and Dynamic Sql we can achieve this result</p>
<pre><code>SET NOCOUNT ON
IF OBJECT_ID('TEMPDB..#TEMP') IS NOT NULL
DROP TABLE #TEMP
;With cte(Category , Revenue , Yearh , [Month])
AS
(
SELECT 'Bikes', 10000, 2008,1 UNION ALL
SELECT 'Bikes', 12000, 2008,2 UNION ALL
SELECT 'Bikes', 12000, 2008,3 UNION ALL
SELECT 'Bikes', 15000, 2008,1 UNION ALL
SELECT 'Bikes', 11000, 2007,2 UNION ALL
SELECT 'Bikes', 11500, 2007,3 UNION ALL
SELECT 'Bikes', 15400, 2007,4
)
SELECT * INTO #Temp FROM cte
Declare @Column nvarchar(max),
@Column2 nvarchar(max),
@Sql nvarchar(max)
SELECT @Column=STUFF((SELECT DISTINCT ','+ 'ISNULL('+QUOTENAME(CAST(Yearh AS VArchar(10)))+','+'''0'''+')'+ 'AS '+ QUOTENAME(CAST(Yearh AS VArchar(10)))
FROM #Temp order by 1 desc FOR XML PATH ('')),1,1,'')
SELECT @Column2=STUFF((SELECT DISTINCT ','+ QUOTENAME(CAST(Yearh AS VArchar(10)))
FROM #Temp FOR XML PATH ('')),1,1,'')
SET @Sql= N'SELECT Category,[Month],'+ @Column +'FRom #Temp
PIVOT
(MIN(Revenue) FOR yearh IN ('+@Column2+')
) AS Pvt
'
EXEC(@Sql)
Print @Sql
</code></pre>
<p>Result</p>
<pre><code>Category Month 2008 2007
----------------------------------
Bikes 1 10000 0
Bikes 2 12000 11000
Bikes 3 12000 11500
Bikes 4 0 15400
</code></pre>
| 3,790
|
<p>Is it possible to get a list of events (with recurring events expanded) out of Sharepoint's Calendar using the Web Service exposed through Lists.aspx?</p>
<p>This is evidently possible if you are using C# or VB, as described <a href="http://blogs.msdn.com/sharepoint/archive/2007/05/14/understanding-the-sharepoint-calendar-and-how-to-export-it-to-ical-format.aspx" rel="nofollow noreferrer">here</a> using a snippet like this:</p>
<pre><code>SPQuery query = new SPQuery();
query.ExpandRecurrence = true;
query.Query = "<Where><DateRangesOverlap><FieldRef Name=\"EventDate\" /><FieldRef Name=\"EndDate\" /><FieldRef Name=\"RecurrenceID\" /><Value Type=\"DateTime\"><Month /></Value></DateRangesOverlap></Where>";
</code></pre>
<p>I am trying to do the same using plain XML via cURL with this query:</p>
<pre><code><GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>{my guid goes here}</listName>
<query>
<Query xmlns="">
<Where>
<DateRangesOverlap>
<FieldRef Name="EventDate" />
<FieldRef Name="EndDate" />
<FieldRef Name="RecurrenceID" />
<Value Type="DateTime"><Month/></Value>
</DateRangesOverlap>
</Where>
</Query>
</query>
<queryOptions>
<QueryOptions>
<ExpandRecurrence>TRUE</ExpandRecurrence>
</QueryOptions>
</queryOptions>
</code></pre>
<p></p>
<p>This kinda works - it gets all the list items, but recurring items are not expanded. The key seems to be the ExpandRecurrence property. Surprisingly, Google does not seem to have a lot to say on the matter beyond a couple of blog posts. Scouring the web, I've read a few comments indicating that the ExpandRecurrence property does not work, but others say it works fine and nothing I've read has struck me as definitive.</p>
<p>Has anybody tried this and gotten it to work without using C# or VB - just straight XML? </p>
|
<p>Finally got this to work correctly and return all recurrent events on a SharePoint Calendar. Here is the XML for the Web Service Query:</p>
<pre><code><GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>
<listName>{your GUID goes here}</listName>
<query>
<Query>
<Where>
<DateRangesOverlap>
<FieldRef Name=\"EventDate\" />
<FieldRef Name=\"EndDate\" />
<FieldRef Name=\"RecurrenceID\" />
<Value Type='DateTime'><Year/></Value>
</DateRangesOverlap>
</Where>
</Query>
</query>
<queryOptions>
<QueryOptions>
<ExpandRecurrence>TRUE</ExpandRecurrence>
</QueryOptions>
</queryOptions>
</GetListItems>
</code></pre>
<p>The key was not only setting the ExpandRecurrence option to true - you also have to include the value in the DateRangeOverlap to Year.</p>
|
<p>Nope is not possible. You would need to use the SP Object model via, for example the SPQuery object. But that would mean that you would have to run that code directly on the sharepoint server, instead of calling in from a client.</p>
<p>Please see this post of mine; <a href="http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/3c399768-c492-4d7e-8f6e-fa304ed03131" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/3c399768-c492-4d7e-8f6e-fa304ed03131</a></p>
| 49,231
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.