instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
---|---|---|---|
<p>I wrote a component that displays a filename, a thumbnail and has a button to load/play the file. The component is databound to a repeater. How can I make it so that the button event fires to the main application and tells it which file to play?</p>
| <p>Maybe you should try including a fourth column, stating the table it came from, and then order and group by it:</p>
<pre><code>SELECT A,B,C, "query 1" as origin FROM table WHERE field LIKE 'query%'
UNION
SELECT A,B,C, "query 2" as origin FROM table WHERE field LIKE '%query'
UNION
SELECT A,B,C, "query 3" as origin FROM table WHERE field LIKE '%query%'
GROUP BY origin, B ORDER BY origin, B ASC LIMIT 5
</code></pre>
| <p>If there isn't a sort that makes sense to order them you desire, don't union the results together - just return 3 separate recordsets, and deal with them accordingly in your data tier.</p>
| 2,589 |
<p>What do you guys think about this for a generic singleton?</p>
<pre><code>using System;
using System.Reflection;
// Use like this
/*
public class Highlander : Singleton<Highlander>
{
private Highlander()
{
Console.WriteLine("There can be only one...");
}
}
*/
public class Singleton<T> where T : class
{
private static T instance;
private static object initLock = new object();
public static T GetInstance()
{
if (instance == null)
{
CreateInstance();
}
return instance;
}
private static void CreateInstance()
{
lock (initLock)
{
if (instance == null)
{
Type t = typeof(T);
// Ensure there are no public constructors...
ConstructorInfo[] ctors = t.GetConstructors();
if (ctors.Length > 0)
{
throw new InvalidOperationException(String.Format("{0} has at least one accesible ctor making it impossible to enforce singleton behaviour", t.Name));
}
// Create an instance via the private constructor
instance = (T)Activator.CreateInstance(t, true);
}
}
}
}
</code></pre>
| <p>Creating a singleton class is just a few lines of code, and with the difficulty of making a generic singleton i always write those lines of code.</p>
<pre><code>public class Singleton
{
private Singleton() {}
static Singleton() {}
private static Singleton _instance = new Singleton();
public static Singleton Instance { get { return _instance; }}
}
</code></pre>
<p>The </p>
<pre><code>private static Singleton _instance = new Singleton();
</code></pre>
<p>line removes the need for locking, as a static constructor is thread safe.</p>
| <p>Using generics is not useful for singletons. Because you can always create multiple instances of the type parameter T and then it is <strong>not</strong> by definition a singleton. </p>
<p>Look at this:</p>
<pre><code>public sealed class Singleton<T> where T : class, new()
{
private static readonly Lazy<T> instance = new Lazy<T>(() => new T());
public static T Instance => instance.Value;
private Singleton() { }
}
</code></pre>
<p>And when you use it like this</p>
<pre><code>public class Adapter
{
public static Adapter Instance => Singleton<Adapter>.Instance;
// private Adapter(){ } // doesn't compile.
}
</code></pre>
<p>you can still create Adapters yourself just call</p>
<pre><code>new Adapter();
</code></pre>
<p>Adding the private constructor to Adapter breaks the code.
Note that this Adapter uses composition not inheritance. I.e. it is not a Singleton it has a Singleton. If something is a Singleton it should derive from or implement an interface.</p>
<pre><code>public abstract class Singleton<T>
{
protected static Lazy<T> instance;
public static T Instance => instance.Value;
}
public sealed class Adapter : Singleton<Adapter>
{
static Adapter()
{
instance = new Lazy<Adapter>(() => new Adapter());
}
private Adapter() { }
}
</code></pre>
<p>Basically this only moves a static field into a generic base class while it is no longer readonly and therefore can be changed after initialization. Also it requires you to remember to add the private constructor, mark it as sealed and perform some initialization so it still isn't well encapsulated and prone to mistakes. </p>
<p>We can improve this by adding a check in the base constructor.</p>
<pre><code>public abstract class Singleton<T> where T : Singleton<T>, new()
{
private static bool instantiated;
private static readonly Lazy<T> instance = new Lazy<T>(() => new T());
public static T Instance => instance.Value;
protected Singleton()
{
if (instantiated)
throw new Exception();
instantiated = true;
}
}
public /* sealed */ class Adapter : Singleton<Adapter>
{
}
</code></pre>
<p>Due to the fact that the Singleton is lazy the pattern is still broken. </p>
<pre><code> new Adapter(); // this works
Adapter.Instance; // this throws an error.
</code></pre>
<p>also</p>
<pre><code> Adapter.Instance; // this works
// just running in production someone decided to call:
new Adapter(); // this throws an error
</code></pre>
<p>These kind of error's can only be detected during testing.</p>
<p>I would still prefer to just use the pattern directly it's basically just 3 lines of code and it is compile time safe. Also when you need a different base classes but still need a lazy singleton and require it to be a true singleton a simple solution exists: (see: <a href="http://csharpindepth.com/Articles/General/Singleton.aspx" rel="nofollow noreferrer">http://csharpindepth.com/Articles/General/Singleton.aspx</a>)</p>
<pre><code>public sealed class Adapter
{
private static readonly Lazy<Adapter> instance = new Lazy<Adapter>(() => new Adapter());
public static Adapter Instance { get { return instance.Value; } }
private Adapter() { }
}
</code></pre>
<p>You cannot refactor this properly into a generic singleton that cannot be misused like the above investigated approaches.</p>
| 49,896 |
<p>I am new to python and struggling to find how to control the amount of memory a python process can take? I am running python on a Cento OS machine with more than 2 GB of main memory size. Python is taking up only 128mb of this and I want to allocate it more. I tried to search all over the internet on this for last half an hour and found absolutely nothing! Why is it so difficult to find information on python related stuff :(</p>
<p>I would be happy if someone could throw some light on how to configure python for various things like allowed memory size, number of threads etc.</p>
<p>A link to a site where most controllable parameters of python are described would be appreciated well.</p>
| <p>Forget all that, python just allocates more memory as needed, there is not a myriad of comandline arguments for the VM as in java, just let it run. For all comandline switches you can just run python -h or read man python.</p>
| <p>Are you sure that the machine does not have a 128M process limit? If you are running the python script as a CGI inside a web server, it is quite likely that there is a process limit set - you will need to look at the web server configuration.</p>
| 23,283 |
<p>What do you think.. are clean URLs a backend or frontend 'discipline'</p>
| <p>If we're talking url's being 'clean' from an end user experience then I'm going to break the mould a bit and say that url's in general are not intuitive and they never will be, they are intended to be machine readable. </p>
<p>There is no standard to the format of a url such that when navigating from site to site humans will never ever remember how to reach a resource purely through remembering urls and their 'friendly syntax'. We can argue the toss about whether using a '?' and '&' or '/' to express how how to identify a resource via a url; is one method better than the other? it doesn't matter. At the end of the day a machine parses it and sends back the result.</p>
<p>We should stop deluding ourselves that people actually type these things in and realise that uri's are for machines, not people.</p>
<p>I have yet to use/remember a uri that goes beyond the first few characters of the <a href="http://domain.com/" rel="nofollow noreferrer">http://domain.com/</a> part of an address, and I've been using the web since a long time. That's what bookmarks are for. Nowhere on a website does it say 'change this part here in our url to view 'whatever else' resource' because url's are usually undocumented and opaque. </p>
<p>Yes make your uri's SEO friendly (hell even they change periodically) but forget about the whole 'human/clean' resource identifier thing, it's a mystical pipe dream.</p>
<p>I agree with Vlion that url's should provide a unique mechanism to bookmark a resource and return to it (unlike some of these abominable web 2.0 ajax/silverlight/flash creations), but the bookmark will never be for humans to comprehend and understand. There seems to be quite a lot of preoccupation and energy spent in dreaming up url strategies that humans can remember and type in, it's a waste of energy. Let's get on and solve real problems.</p>
<p>Sorry for the rant, but there's a lot of web 2.0 nonsense related to urls going on in certain circles that are just a total waste of time.</p>
| <p>I think the main reasons for using friendly URLs are:</p>
<ul>
<li>Ease of linking / sharing</li>
<li>Presentation</li>
<li>Seo </li>
</ul>
<p>So I think it's purely a client-side pleasure. While they're nice on the server as well, they're not mission critical.</p>
| 24,869 |
<p>Here's my issue: I need to close a process, already running, from a C# program.
The problem is that the process now runs as an icon (minimized to taskbar), and unless the user opens it at least once (which will never happen on unattended machines), it'll never
have a main window. </p>
<p>The other requirement that I have is that the application be <strong>closed</strong> not <strong>killed</strong>. I need it to write it's memory buffers to disk - and killing it causes data loss.</p>
<p>Here's what I tried so far:</p>
<pre><code> foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.ToLower().StartsWith("myapp"))
{
if (proc.MainWindowHandle.ToInt32() != 0)
{
proc.CloseMainWindow();
proc.Close();
//proc.Kill(); <--- not good!
}
}
}
</code></pre>
<p>I've added the <strong>if</strong> clause, after discovering that <strong>MainWindowHandle == 0</strong> when the window was minimized. Removing the <strong>if</strong> doesn't help. Neither the <strong>CloseMainWindow()</strong> nor the <strong>Close()</strong> work. The <strong>Kill()</strong> does, but as mentioned above - it's not what I need.</p>
<p>Any idea would be accepted, including the use of arcane Win32 API functions :)</p>
| <p>This should work:</p>
<pre><code>[DllImport("user32.dll", CharSet=CharSet.Auto)]
private static extern IntPtr FindWindow(string className, string windowName);
[DllImport("user32.dll", CharSet=CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
private const int WM_CLOSE = 0x10;
private const int WM_QUIT = 0x12;
public void SearchAndDestroy(string windowName)
{
IntPtr hWnd = FindWindow(null, windowName);
if (hWnd == IntPtr.Zero)
throw new Exception("Couldn't find window!");
SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
</code></pre>
<p>Since some windows don't respond to <code>WM_CLOSE</code>, <code>WM_QUIT</code> might have to be sent instead. These declarations should work on both 32bit and 64bit.</p>
| <p>Question to clarify why you're attempting this: If the only user interface on the process is the system tray icon, why would you want to kill that and but leave the process running? How would the user access the process? And if the machine is "unattended", why concern yourself with the tray icon?</p>
| 13,558 |
<p>Where I can download sample database which can be used for data warehouse creation? It should't be sample from Microsoft (Northwind etc.).</p>
<p>EDIT: Sorry for not clarifying my question. At my university we have class where we must create some data warehouse and since Northwind is so popular over net then professor told us not to use this database. We will use for this SQL Server 2008 but using Northwind is forbidden.</p>
| <p>This is a free online database data generator:
<a href="http://www.generatedata.com/" rel="noreferrer">www.generatedata.com</a></p>
<p>You can design a table structure and let the script generate rows to populate it.
It's not exactly what you need, but I think it can help.</p>
| <p>Hey Just use Adventure works SR4</p>
| 29,268 |
<p>When userA uploads a file, his files will be uploaded to folderA, when userB, to folderB, and so on. Roles/Profiles in ASP.NET. Folders will be pre-existing. Anyone?</p>
| <p>You'll probably want to hand-code that. There's nothing intrinsic to ASP.NET for managing user files. However, the code to do so should be relatively easy. Assuming the username is unique and never changes, you can combine the username with a path (use Path.Combine) and upload to that location. I would also lock down that location so that nobody else can access it.</p>
| <p>You can just check for the existance of the folder and create it for the user if it doesn't exists, but there are security implications for this. You might also want to try and store data in a database and tie it to a user.. this depends on what you are letting users upload I guess.</p>
| 15,254 |
<p>Imagine I have a property defined in global.asax. </p>
<pre><code>public List<string> Roles
{
get
{
...
}
set
{
...
}
}
</code></pre>
<p>I want to use the value in another page. how to I refer to it?</p>
| <p>You can access the class like this:</p>
<pre><code>((Global)this.Context.ApplicationInstance).Roles
</code></pre>
| <p>If the values are dependent on the Session then this is actually simple using the HttpContext.Items Dictionary:</p>
<p>Place this code in the Global.asax to store the value:</p>
<pre><code>Dim someValue As Integer = 5
Context.Items.Add("dataKey", someValue)
</code></pre>
<p>Let retreive it in a Page with this code:</p>
<pre><code>Dim someValue As Integer = CType(HttpContext.Current.Items("dataKey"), Integer)
</code></pre>
<p>Here's a link that describes it in further detail: <a href="https://web.archive.org/web/20210608183011/http://aspnet.4guysfromrolla.com/articles/060904-1.aspx" rel="nofollow noreferrer">https://web.archive.org/web/20210608183011/http://aspnet.4guysfromrolla.com/articles/060904-1.aspx</a></p>
| 31,397 |
<p>I have build plenty of SOAP webservices, but am building a REST webservice for a specific project, and I was wondering what people used for a 'WSDL' for REST services or if it is even needed.</p>
| <p>You can try <a href="http://swagger.io/" rel="nofollow noreferrer">Swagger</a>(now OpenAPI) which allows to describe REST services using a JSON open standard.</p>
| <p>You can supply an XSD if you are using XML in your REST service.</p>
<p>Or just examples of the XML, should be enough to work things out for simple data structures anyway.</p>
| 36,129 |
<p>I am attempting to copy a custom struct from kernel space to user space. inside user space errno returns 'bad address'. What is the usual cause of a bad address error?</p>
<pre><code>if(copy_to_user(info, &kernel_info, sizeof(struct prinfo)))
</code></pre>
| <p>Bad Address error means that the address location that you have given is invalid. With the case you have above I would guess it is because you are passing a copy of <code>info</code> instead of a pointer to <code>info</code>'s memory location.</p>
<p>Looking at the docs, <code>copy_to_user</code> is defined as</p>
<pre><code>copy_to_user(void __user * to, const void * from, unsigned long n);
</code></pre>
<p>So unless your <code>info</code> variable is a pointer I would update your code to be:</p>
<pre><code>if(copy_to_user(&info, &kernel_info, sizeof(struct prinfo)) ) {
//some stuff here i guess
}
</code></pre>
| <p>I had a same problem while writing a small char driver. All I was doing wrong was the function copy_to_user returns non-zero on failure, so you have to do this..</p>
<pre><code>if(copy_to_user(void *userbuf, void *kernelbuf, long len))
return -EFAULT;
// Continue with code..
</code></pre>
| 8,721 |
<p>DocumentsController#common_query can handle multiple different request styles.</p>
<p>i.e. all docs in batch 4 or all docs tagged "happy"</p>
<p>I want a single route to make em pretty, so:</p>
<p>/documents/common_query?batch=4</p>
<p>/documents/common_query?tag=happy</p>
<p>become:</p>
<p>/documents/batch/4</p>
<p>/documents/tag/happy</p>
<p>So the end result is that #common_query is called but part of the url was used as the param name and part as it's value.</p>
| <p>As a single route:</p>
<pre><code>ActionController::Routing::Routes.draw do |map|
map.connect "documents/:type/:id", :controller => "documents_controller",
:action => "common_query"
end
</code></pre>
<p>Then <code>params[:type]</code> will either be <code>"batch"</code> or <code>"tag"</code>, and <code>params[:id]</code> either <code>"4"</code> or <code>"happy"</code>. You will have to make sure that other actions for the <code>DocumentsController</code> come before this in the routes because this will match any url that looks like <code>"documents/*/*"</code>.</p>
<p>But why does it have to be a single route? You could use two routes like this:</p>
<pre><code>map.with_options(:controller => "documents_controller",
:action => "common_query") do |c|
c.connect "documents/batch/:page", :type => "batch"
c.connect "documents/tag/:tag", :type => "tag"
end
</code></pre>
<p>which will have the same effect, but is more specific, so you wouldn't have to worry about the priority order of the routes.</p>
| <p>As a single route:</p>
<pre><code>ActionController::Routing::Routes.draw do |map|
map.connect "documents/:type/:id", :controller => "documents_controller",
:action => "common_query"
end
</code></pre>
<p>Then <code>params[:type]</code> will either be <code>"batch"</code> or <code>"tag"</code>, and <code>params[:id]</code> either <code>"4"</code> or <code>"happy"</code>. You will have to make sure that other actions for the <code>DocumentsController</code> come before this in the routes because this will match any url that looks like <code>"documents/*/*"</code>.</p>
<p>But why does it have to be a single route? You could use two routes like this:</p>
<pre><code>map.with_options(:controller => "documents_controller",
:action => "common_query") do |c|
c.connect "documents/batch/:page", :type => "batch"
c.connect "documents/tag/:tag", :type => "tag"
end
</code></pre>
<p>which will have the same effect, but is more specific, so you wouldn't have to worry about the priority order of the routes.</p>
| 44,118 |
<p>Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent?</p>
<p>Something like the opposite of <a href="http://ruby-doc.org/core-2.0.0/String.html#method-i-to_i" rel="noreferrer"><code>String#to_i</code></a>:</p>
<pre><code>"0A".to_i(16) #=>10
</code></pre>
<p>Like perhaps:</p>
<pre><code>"0A".hex #=>10
</code></pre>
<p>I know how to roll my own, but it's probably more efficient to use a built in Ruby function.</p>
| <p>You can give <a href="http://www.ruby-doc.org/core/classes/Integer.html#method-i-to_s" rel="noreferrer"><code>to_s</code></a> a base other than 10:</p>
<pre><code>10.to_s(16) #=> "a"
</code></pre>
<p>Note that in ruby 2.4 <code>FixNum</code> and <code>BigNum</code> were unified in the <code>Integer</code> class.
If you are using an older ruby check the documentation of <a href="https://ruby-doc.org/core-2.3.8/Fixnum.html#method-i-to_s" rel="noreferrer">FixNum#<code>to_s</code></a> and <a href="https://ruby-doc.org/core-2.3.8/Bignum.html#method-i-to_s" rel="noreferrer">BigNum#<code>to_s</code></a></p>
| <p>Just in case you have a preference for how negative numbers are formatted:</p>
<pre><code>p "%x" % -1 #=> "..f"
p -1.to_s(16) #=> "-1"
</code></pre>
| 11,000 |
<p>I have a ComboBox bound to an ObservableCollection of decimals. What is the correct way to apply our currency converter to the items?</p>
<p>Edit:</p>
<p>a) I have an existing currency converter that I must use
b) .NET 3.0</p>
<p>Do I need to template the items?</p>
| <p>You can use the ItemStringFormat property on ComboBox to tell it how to format each of its items:</p>
<pre><code><ComboBox ItemStringFormat="c">
</code></pre>
<p>However, be aware that when using "c" as a currency formatter, it will use the currency defined by the local machine. If your values are defined in $ but your client PC is running with pounds or yen as their currency symbol, they won't be seeing what you want them to see.</p>
| <p>Use <strong>StringFormat</strong> in the Binding expression like </p>
<pre><code><TextBox Text="{Binding Path=Value, StringFormat=Amount: {0:C}}"/>
</code></pre>
<p>See this <a href="http://blogs.msdn.com/llobo/archive/2008/05/19/wpf-3-5-sp1-feature-stringformat.aspx" rel="nofollow noreferrer">blog for more details.</a></p>
<p>A <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx" rel="nofollow noreferrer">ValueConverter</a> is another way - StringFormat doesnt work on .NET3.0 it needs WPF3.5 SP1. </p>
| 37,638 |
<p>After creating a instance of a class, can we invoke the constructor explicitly?
For example</p>
<pre><code>class A{
A(int a)
{
}
}
A instance;
instance.A(2);
</code></pre>
<p>Can we do this?</p>
| <p>You can use <a href="http://en.wikipedia.org/wiki/Placement_new" rel="nofollow noreferrer">placement new</a>, which permits</p>
<pre><code>new (&instance) A(2);
</code></pre>
<p>However, from your example you'd be calling a constructor on an object twice which is very bad practice. Instead I'd recommend you just do</p>
<pre><code>A instance(2);
</code></pre>
<p>Placement new is usually only used when you need to pre-allocate the memory (e.g. in a custom memory manager) and construct the object later.</p>
| <p>Just to summarize, the three ways to specify the explicit constructor are via</p>
<ol>
<li><p>A instance(2); // does A instance = 2; ever work?</p></li>
<li><p>A *instance = new A(2); //never sure about & versus * here, myself</p></li>
<li><p>new (&instance) A(2);</p></li>
</ol>
<p>and flavors of those. The <strike>idea</strike> goal is to arrange that at no time is an object constructed that is not in a proper initialized state, and constructors are designed to assure that. (This means that methods don't have to check on whether some .init(...) method has been successfully called or not.)</p>
<p>This strikes me as the more-functional way to go about this, especially for classes that are parts of frameworks and reused in libraries. If that is what you are interested in, work toward having all constructors, including any default one, deliver a fully-working instance.</p>
<p>Exception Cases: There are things you might not have in the constructor operation if it is possible for them to fail, unless it is appropriate to throw an exception from the constructor. And some folks like having "blank" instances that are propogated using subsequent methods and even exposed-to-initialization members. It is interesting to explore ways to mitigate such situations and have robust instances that don't have bad states that need to be protected against in method implementations and in usage.</p>
<p>PS: In some complex cases, it may be useful to have an initialized instance (reference) be delivered as the result of a function or of a method on a "factory" class, so that the intermediate, under-setup instance is never seen outside of the encapsulating factory class instance or function. That gives us,</p>
<p>+4. A *instance = MakeAnA(2); </p>
<p>+5. A *instance = InterestingClass.A(2);</p>
| 40,479 |
<p>Is there similar component for Delphi like dictionary of Python?</p>
<p>I'm now using TStringList to map string/object pairs, but I'd like more general approach and maybe more powerful (TStringList has binary search when it is sorted).</p>
<p>Solutions for pre-D2009 are also welcome.</p>
| <p>There is in Delphi 2009. A whole new containers unit has been added, and a Dictionary class is one of the classes available.</p>
<p>Couple this with Generics, and you have a very powerful set of classes.</p>
| <p>I have allways used <a href="http://sourceforge.net/projects/decal/" rel="nofollow noreferrer">DeCAL</a>. It includes both sequences, maps and hashtables.</p>
| 49,522 |
<p>I'm pretty sure most of us are familiar with the concept of a project's requirements changing after it starts, this becomes more and more of an issue the less the client knows about how things work and the closer you work with them.</p>
<p>How then can I design a system (specifically a website but general advice will probably be best here) so that smallish changes can be made, are there any programming strategies that deal with this issue?</p>
| <p>All the normal oo principles apply here, reduce coupling, increase cohesion, don't repeat yourself etc. This will make sure you have a flexible and extendible code base.</p>
<p>Apart from that don't try to preempt change. Apply YAGNI (You aint gonna need it) everywhere. Only build stuff you know your users need. Dont build stuff you think you're going to need. You're more likely to guess wrong and then you've got a bunch of code that's probably only in the way.</p>
| <p>This is where frameworks come into play.</p>
<p>If all the baseline, background, business-as-usual is in the framework, then your application is the extensions, special-cases and add-ons.</p>
<p>The framework is already designed and built for change. Your stuff is the change that the frame was designed to accept. </p>
<p>When change occurs, you will respond to change with some combination of modifying the framework configuration and rewriting your stuff that plugs into the framework. You cope with change by <em>not</em> focusing on the default, background stuff. Delegate that to someone else -- the framework authors.</p>
| 16,067 |
<p>Your backend could be PHP or Python but you want to use the controls from the ASP.NET toolkit is there a successful way to do this?</p>
| <p>I don't think that it is possible.</p>
<p>The ASP.NET AJAX Toolkit is based on ASP.NET technique (what a surprise) and needs ASP.NET.</p>
<p>It contains server-side controls, which are translated to HTML and Javascript by the ASP.NET engine. It is not working without the engine.</p>
<p>However you can check the code itself to see how it is working, what it generates on the browser side and get ideas and Javascript codes to build into your application or framework.</p>
<p><strong>Edit:</strong> I've just found an interesting project, which is in alpha stage, check <a href="http://www.codeplex.com/phpmsajax" rel="nofollow noreferrer">this</a> out.</p>
| <p>I have found that much of the functionality in AJAX Control Toolkit can be accomplished via the javascript frameworks such as jQuery.</p>
| 7,717 |
<p>In JavaScript this was a cross-browser compatibility issue, so both were used, but there are numerous instances in different languages where I see both printed out together as \r\n. Is this still the generally excepted norm that you should just always use both, or is there ever a time where languages understand both and you end up with a break and a return?</p>
| <p>The CRLF pair is the expected end-of-line (EOL) marker on most internet protocols.</p>
<p>Here, Postel's "Robustness Principle" should apply. Be liberal in what you accept, but strict in what you send. So, be prepared to receive just a LF, but if you're sending data use whatever the relevant standards require.</p>
| <p>This is not a language compatibility issue, but either a file issue or a protocol issue. File-wise: Unix uses \n as a carriage return, Windows uses \r\n and I think MacOS used (not sure about now) \r. Many 'cross platform' languages abstract this in a platform dependant variable. Protocol-wise: what the protocol specifies.</p>
| 32,115 |
<p>We are using the Board SKR 1.3 with the following pins:</p>
<pre><code>/**
* Trinamic Stallguard pins
*/
#define X_DIAG_PIN P1_29 // X-
#define Y_DIAG_PIN P1_27 // Y-
#define Z_DIAG_PIN P1_25 // Z-
#define E0_DIAG_PIN P1_28 // X+
#define E1_DIAG_PIN P1_26 // Y+
</code></pre>
<p>We need a double Z motor, so We have defined the number of stepper drivers to 2 and it works like a charm:</p>
<pre><code>#define NUM_Z_STEPPER_DRIVERS 2
</code></pre>
<p>Here is the problem, We need to have a single extruder with <strong>two heating zones</strong>, not a real second extruder. We have defined the number of extruders to 2:</p>
<pre><code>#define EXTRUDERS 2
</code></pre>
<p>We want to reinforce that the second extruder does not exist, we only need the <strong>second heating zone</strong>. It's a big hotend with two different heating cartridges, that is, two different temperatures. So we do not need the stepper driver, only the temperature.
Then we get the following error messages:</p>
<p><a href="https://i.stack.imgur.com/5jNEg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5jNEg.png" alt="enter image description here"></a></p>
<p>We have thought of enabling the chamber and use it's pin, but we got stuck with all the structure for it:</p>
<pre><code>#define TEMP_SENSOR_CHAMBER 5
</code></pre>
<pre><code>#define CHAMBER_MAXTEMP 250 // Extruder first temperature zone
</code></pre>
<pre><code>#define HEATER_CHAMBER_PIN 24
</code></pre>
| <p>I second the previous answer if running second Z motor in parallel, just split wires or buy adapter consisting of two females to one male, Z motor on most printers don't draw huge current (or at least in smaller less frequent intervals to give things time to cool). </p>
<p>Erm I extruder with two temperature zones, hmmm buy a larger heating element, like a E3D Volcano or I believe they have an extreme version now, mine is rated for 40 W+.</p>
<p>Or you could use external MOSFET with separate Arduino PID.</p>
| <p>Unfortunately, I faced the same problem. The heated chamber will not be accurate enough due to lack of PID tuning. As a result, the temp will differ up to 10 degrees celsius when the heater is on. Is a big difference that will either not dry your filament enough or in the worst scenario will melt it. You will need to enable other features in order to bypass the issue. Find below how I enabled the 2nd heater element with the exact same setup as yours. You need to define the following:</p>
<pre><code>#define EXTRUDERS 2
</code></pre>
<hr />
<p>On the following part you must change the <code>SERVO_NR</code> to <code>-1</code> otherwise you will face issues in case you are using a BLTouch, for example:</p>
<pre><code>// A dual extruder that uses a single stepper motor
#define SWITCHING_EXTRUDER
#if ENABLED(SWITCHING_EXTRUDER)
#define SWITCHING_EXTRUDER_SERVO_NR -1
#define SWITCHING_EXTRUDER_SERVO_ANGLES { 0, 90 } // Angles for E0, E1[, E2, E3]
#if EXTRUDERS > 3
#define SWITCHING_EXTRUDER_E23_SERVO_NR 1
#endif
#endif
// A dual-nozzle that uses a servomotor to raise/lower one (or both) of the nozzles
#define SWITCHING_NOZZLE
#if ENABLED(SWITCHING_NOZZLE)
#define SWITCHING_NOZZLE_SERVO_NR -1
//#define SWITCHING_NOZZLE_E1_SERVO_NR 1 // If two servos are used, the index of the second
#define SWITCHING_NOZZLE_SERVO_ANGLES { 0, 90 } // Angles for E0, E1 (single servo) or lowered/raised (dual servo)
#endif
-----------------------------
#define TEMP_SENSOR_1 1
-----------------------------
</code></pre>
<p>And finally, you must <code>#define PID_PARAMS_PER_HOTEND</code> in order to be able to PID tuning the 2nd heater which will be used for your inline filament dryer.</p>
| 1,608 |
<p>I am looking for a Dataflow / Concurrent Programming API for Java.<br>
I know there's <a href="http://www.pervasivedatarush.com/" rel="noreferrer">DataRush</a>, but it's not free. What I'm interested in specifically is multicore data processing, and not distributed, which rules out <a href="http://en.wikipedia.org/wiki/MapReduce" rel="noreferrer">MapReduce</a> or <a href="http://en.wikipedia.org/wiki/Hadoop" rel="noreferrer">Hadoop</a>.<br>
Any thoughts?<br>
Thanks,
Rollo</p>
| <p>You might try <a href="http://www.gpars.org/" rel="nofollow noreferrer">gpars</a>; it apparently has implementations of data flow variables and streams in Java even though it is geared towards providing concurrent programming goodies for Groovy.</p>
| <p>Does the built in Java <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/package-summary.html" rel="nofollow noreferrer">concurrent</a> package meet your needs? It's a very nice package, built in ThreadPools, CopyOnWriteCollections, Executors, Future. We use it to process large volumns of data in thread pools.</p>
| 19,621 |
<p>Reading through <a href="https://stackoverflow.com/questions/39879/why-doesnt-javascript-support-multithreading">this question</a> on multi-threaded javascript, I was wondering if there would be any security implications in allowing javascript to spawn mutliple threads. For example, would there be a risk of a malicious script repeatedly spawning thread after thread in an attempt to overwhelm the operating system or interpreter and trigger entrance into "undefined behavior land", or is it pretty much a non-issue? Any other ways in which an attack might exploit a hypothetical implementation of javascript that supports threads that a non-threading implementation would be immune to?</p>
<p><strong>Update:</strong> Note that locking up a browser isn't the same as creating an undefined behavior exploit. </p>
| <p>No, multiple threads would not add extra security problems in a perfect implementation. Threaded javascript would add complexity to the javascript interpreter which makes it more likely to have an exploitable bug. But threads alone are not going to add any security issues. </p>
<p>Threads are not present in javascript because "Threads Suck" - read more from the language designer (<a href="http://weblogs.mozillazine.org/roadmap/archives/2007/02/threads_suck.html" rel="nofollow noreferrer">http://weblogs.mozillazine.org/roadmap/archives/2007/02/threads_suck.html</a>)</p>
| <p>Well I think that the only major example of multi-threaded javascript is Google's chrome (WOULD THEY RELEASE IT ALREADY JEEZ) and if I understand it the javascript will only one process per tab, so unless it started spawning tabs (popups) I would assume this would be a null issue, but I think that Google has that under wraps anyway, the are running all the javascript in a sandbox.</p>
| 6,117 |
<p>I'm looking to establish some kind of socket/COMET type functionality from my server(s) to my iPhone application. Essentially, anytime a user manages to set an arbitrary object 'dirty' on the server, by say, updating their Address.. the feedback should be pushed from the server to any clients keeping a live poll to the server. The buzzword for this is COMET I suppose. I know there is DWR out there for web browser applications, so I'm thinking, maybe it's best to set a hidden UIWebView in each of my controllers just so I can get out of the box COMET from their javascript framework? Is there a more elegant approach? </p>
| <p>There are a couple of solutions available to use a <a href="http://stomp.codehaus.org/Protocol" rel="noreferrer">STOMP</a> client.</p>
<p>STOMP is incredibly simple and lightweight, perfect for the iPhone.</p>
<p>I used <a href="http://code.google.com/p/stompframework/" rel="noreferrer">this one</a> as my starting point, and found it very good. It has a few object allocation/memory leak problems, but once I got the hang of iPhone programming, these were easy to iron out.</p>
<p>Hope that helps!</p>
| <p>COMET, LightStreamer, AJAX all that junk is broken. It is basics of TCP that no 'keep-alives' are ever guaranteed without pinging traffic.. So you can forget that long-polling if any decent reliability or timely delivery is to be guaranteed..</p>
<p>It's just hype everyone saw through back in 2003 when the lame-mania kicked off..</p>
| 43,861 |
<p><em>TLDR - I’ve just driven myself insane trying to fix what I thought was a physical problem with my Z-axis, but it seems to have been solved by switching from the TH3D firmware to the Creality firmware. I’m hoping someone can help me see where I went wrong here, so I can learn from it. Have I missed something obvious?</em></p>
<p>My printer is a Creality Ender 3 Pro. I have a BLTouch. I recently upgraded to the silent 4.2.7 board and compiled my own firmware using TH3D Unified 2 using their instructions. <a href="https://pastebin.com/MYs8sYGj" rel="nofollow noreferrer">This is my <code>configuration.h</code></a>.</p>
<p>This “worked”, but after that upgrade, I had severe print problems. (See the photos below) These are supposed to be 20x20x20 calibration cubes (the big one is 200%). They are significantly taller than they should be. It may be hard to see in the photo, but this is because the Z spacing on the bottom layers seems to be too high. But, at the same point on each print (even the bigger one), the problem seems to just stop - and layer spacing is correct again for the end of the print.</p>
<p><a href="https://i.stack.imgur.com/BGayd.jpg" rel="nofollow noreferrer" title="Comparison of multiple calibration cubes"><img src="https://i.stack.imgur.com/BGayd.jpg" alt="Comparison of multiple calibration cubes" title="Comparison of multiple calibration cubes" /></a></p>
<p>I tried everything to figure out what this was and I was convinced it was a physical problem with my Z-axis. I read lots of questions on here but nothing quite on topic. I printed on different parts of the bed and got the same result. I re-calibrated my Z steps, but these turned out to be pretty much at the firmware default anyway. I tightened every bolt and eccentric nut I could find that related to the X-axis gantry, but nothing made any difference. Same problem, every time.</p>
<p>Out of desperation, I eventually switched to the official Creality firmware for the Ender 3 Pro 4.2.7 board with BLTouch - and the problem was fixed:</p>
<p><a href="https://i.stack.imgur.com/7tXcf.jpg" rel="nofollow noreferrer" title="Printed calibration cube after firmware change"><img src="https://i.stack.imgur.com/7tXcf.jpg" alt="Printed calibration cube after firmware change" title="Printed calibration cube after firmware change" /></a></p>
<p>Does anyone have any ideas about what caused this? Have I overlooked something obvious? I’d ideally like to go back to the TH3D firmware but it’s seemingly not an option.</p>
<p><a href="https://pastebin.com/MYs8sYGj" rel="nofollow noreferrer">https://pastebin.com/MYs8sYGj</a></p>
| <p>It's well known in mathematical circles that the "salesman problem" is what mathematicians call "hard" -- in their usage, that means a lot of extremely smart people have worked on the problem for many years (more than a century?) and still not found a robust, works-every-time solution.</p>
<p>What's probably happening with Cura and other slicers is that, for their version of this issue (the most efficient way to visit multiple locations) the decision was made that reducing computing time in slicing was more practical than optimizing travel time of the machine. This is a reasonable decision, from a programming standpoint, because you're likely to be sitting in front of a screen, getting more and more impatient (and thinking less and less of the software you're using) every second the slicing takes, but when the actual printing is going on, you can be doing something else (sleeping, working at your day job, etc.)</p>
<p>Therefor, it's likely that what you see in Cura <em>is</em> optimized -- to minimize <em>your</em> time on the way to a solution, rather than to minimize the time for a machine that simply doesn't care if a print takes five hours or nine.</p>
| <p><strong>Long story short:</strong> I only know the setting "Combing Mode OFF" that improves the travel paths. In my case it did not help. In your case I suggest you should give PrusaSlicer a try. I assume that the overall print duration will be improved because of a better calculation of the travel paths. But this is only my personal opinion between these two Slicers.</p>
<p><strong>Further explanation:</strong> I downloaded the Cura 4.9 and made an install from scratch. I tried to reproduce your issue by placing lots of copies of the same part. As printer I selected the Ultimaker S5 and used the standard configuration for slicing. I let Cura arrange the parts on the print plate.
I checked the travel paths between the parts and in most cases Cura has chosen the nearest distance to move the printhead to the next part. In my opinion, there could be a more efficient choice for the next part to print.
After this first test I experimented with the settings (e.g. "Combing Mode" OFF) but without an improvement in travel movements.</p>
<p>In the past I used Cura in combination with an Ultimaker S5 at work to print parts for production usecases. Over the past two years I recognized lots of parts where the travel movements have been chosen very unefficiently at the cost of high print duration.</p>
<p>For comparison I used my standard slicer "PrusaSlicer" and did the test under the same conditions: standard settings, auto-arrangement of the parts.
Overall the travel paths are calculated more efficiently, but there is also some room for improvement.</p>
| 1,992 |
<p>My company is currently migrating some of their really old db's to sql server 2005. Some legacy apps have problems connecting to the new server. The connection string works in Asp.NET 2.0, probably because it assumes tcp:1433 automatically.</p>
<p>I have to construct the connection string like this in ASP.NET 1.1 for it to work:</p>
<pre><code>"Server=tcp:my.server.com,1433;..."
</code></pre>
<p>Without the protocol and the port, the connection fails ("Invalid Connection exception")</p>
<p>TCP 1433 and UDP 1434 are open on our firewall. On SQL Server 2005 Remote Access is enabled, so is TCPIP, the SQL Browser service is running, I use the proper login credentials.</p>
<p>Any ideas why I can't just specify the server name without protocol and port number?</p>
| <p>IIRC SQL Server 2005 defaults to find any-old-port that is available. On my laptop this means port 1212.</p>
<p>To force it to a specific port you must go to Start->Programs->SQL Server 2005->Configuration Tools->SQL Server Configuration Manager</p>
<p>From here you must go to SQL Server 2005 Network Configuration->Protocols for (name of service)->Right click on TCP/IP->Properties->Choose tab "IP Address" and set TCP Dynamic Ports to . </p>
<p>For some reason "0" means "Yes, use dynamic ports" and (i.e. no entry in field) menas "No, I will specify it myself"</p>
<p>Then fill in the field TCP Port with 1433.</p>
<p>Do so on all adapters that are listed, and restart the SQL Service.</p>
<p>You can now check if the service is indeed on the right port by doing the following</p>
<p>Start->Run->cmd.exe</p>
<p>C:>netstat -ano</p>
<p>look for an entry like this</p>
<pre><code> local address <stuff> PID
0.0.0.0:1433 <some number>
</code></pre>
<p>Now do
C:>tasklist</p>
<p>and look for the task with the number from above. This task should be called something like sqlsrvr.exe.</p>
| <p>Perhaps your SQL Server is configured for multi-protocol, and it's trying to use the other protocol first and failing, perhaps for some security reason (the account that the app is running as in IIS). Just a guess.</p>
| 36,858 |
<p>This declaration causes an overflow in VBA:</p>
<pre><code>Const OVERFLOWS As Long = 10 * 60 * 60
</code></pre>
<p>whereas setting the value directly is fine:</p>
<pre><code>Const COMPILES_OK As Long = 36000
</code></pre>
<p>How do you persuade VBA to treat literal integers as longs?</p>
<p>Thanks</p>
| <p>Add the <code>long</code> suffix <code>&</code> to at least one number:</p>
<pre><code>Const OVERFLOWS As Long = 10& * 60 * 60
</code></pre>
<p>Note that using the <code>CLNG</code> function to convert the values to <code>long</code> will not work, because VBA does not allow assigning the return value of a function to a constant.</p>
| <p>The type character can also be appended to literals : Const OVERFLOWS As Long = (10& * 60 * 60)
(one is suffucient actually because of the way the VBA engine evaluates the expression).</p>
| 32,718 |
<p>What are the ways by which we can reduce the size of the HTML Response sent by an asp.net application?</p>
<p>I am using Controls which are not owned by me and it produces output with white spaces. I am interested in Minifying the entire HTML output of the page just like how google does (View source www.google.com) to improve the timing.</p>
<p>Is there any Utility classes available for ASP.NET which can do this stuff for me?</p>
| <p>There is no need to do it at run time. Because it can be done at compile time.</p>
<p>Details: <a href="http://omari-o.blogspot.com/2009/09/aspnet-white-space-cleaning-with-no.html" rel="noreferrer">http://omari-o.blogspot.com/2009/09/aspnet-white-space-cleaning-with-no.html</a></p>
| <p>The accepted answer does not work with MVC 4, so here is a similar lib that minifies at build-time <a href="https://github.com/jitbit/HtmlOptimizerMvc4" rel="nofollow">https://github.com/jitbit/HtmlOptimizerMvc4</a></p>
| 31,818 |
<p>I erroneously delete all the rows from a MS SQL 2000 table that is used in merge replication (the table is on the publisher). I then compounded the issue by using a DTS operation to retrieve the rows from a backup database and repopulate the table.</p>
<p>This has created the following issue:
The delete operation marked the rows for deletion on the clients but the DTS operation bypasses the replication triggers so the imported rows are not marked for insertion on the subscribers. In effect the subscribers lose the data although it is on the publisher.</p>
<p>So I thought "no worries" I will just delete the rows again and then add them correctly via an insert statement and they will then be marked for insertion on the subscribers.</p>
<p>This is my problem:
I cannot delete the DTSed rows because I get a "Cannot insert duplicate key row in object 'MSmerge_tombstone' with unique index 'uc1MSmerge_tombstone'." error. What I would like to do is somehow delete the rows from the table bypassing the merge replication trigger. Is this possible? I don't want to remove and redo the replication because the subscribers are 50+ windows mobile devices.</p>
<p>Edit: I have tried the Truncate Table command. This gives the following error "Cannot truncate table xxxx because it is published for replication"</p>
| <p>Have you tried truncating the table?</p>
| <p>Would creating a second table be an option? You could create a second table, populate it with the needed data, add the constraints/indexes, then drop the first table and rename your second table. This should give you the data with the right keys...and it should all consist of SQL statements that are allowed to trickle down the replication. It just isn't probably the best on performance...and definitely would impose some risk.</p>
<p>I haven't tried this first hand in a replicated environment...but it may be at least worth trying out.</p>
| 10,912 |
<p>I'm planning to write a aspx pages on Windows XP machine. I have IIS 7.0 enabled and virtual directory setup. Are aspx page developments allowed on Win XP?</p>
| <p>Yes, you can develop ASP.NET pages (.aspx) on Windows XP. XP only runs IIS 5.1, however you don't even need IIS installed as Visual Web Developer Express has a built-in web server you can use during development.. To get started, I would go to <a href="http://www.microsoft.com/express/" rel="nofollow noreferrer">http://www.microsoft.com/express/</a> and download Microsoft Visual Web Developer Express. After doing that, go to <a href="http://www.asp.net/get-started/" rel="nofollow noreferrer">http://www.asp.net/get-started/</a> to learn the basics. Post any questions or problems you encounter back here on StackOverflow.</p>
| <p>The new Web Platform Installer now supports XP:</p>
<p><a href="http://www.microsoft.com/web/channel/products/WebPlatformInstaller.aspx" rel="nofollow noreferrer">http://www.microsoft.com/web/channel/products/WebPlatformInstaller.aspx</a></p>
| 42,405 |
<p>Has anyone else experienced (and possibly solved) unintentional pitch changes using MS SAPI TTS voices? </p>
<p>I'm using the SpVoice automation interface with SAPI 5.1.</p>
<p>Right now, my application (VB6 app) can get into a state where the TTS (Microsoft Anna) starts to sound like a chipmunk (proper rate, but high pitch) and even a reboot of Vista does not correct the issue. </p>
<p>I'm passing in XML to the Voice.Speak() function. I've tried sending < pitch absmiddle="0" /> before all other XML and it still does not correct the pitch issue. When I try the TTS voice preview in the Speech control panel, the voice has a normal pitch.</p>
<p>The issue has occurred for me in XP in the past, however a reboot seemed to correct it.</p>
| <p>Can you answer your own question? Can you ask another question in the answer? Too late... :)</p>
<p>My solution was to initialize the Voice.AudioOutputStream.format.Type to something sensible, like 16kHz16BitMono. I had a bug where if there is only one voice available, this initialization step could be skipped. Turns out that (for my project running in a Vista VMWare environment) if you don't set the audio format for the voice, you will get a high pitch voice. Good to know..</p>
| <p>I haven't seen that happen, although my experience is mostly with SAPI 5.3 with SSML, which gets translated (under the covers) to SAPI TTS.</p>
<p>Have you tried surrounding your text with the <code><pitch absmiddle="0"></code> Your Text Here instead of just at the front of the text?</p>
| 11,820 |
<p>I've searched a lot for an answer for this question in the web: they say it's true, SBCL doesn't work under Vista.
But I really need to work with lisp on my home Vista laptop and VM doesn't help really...
And CL is not so interesting because of speed...</p>
<p>If you have any recommendation, please share!</p>
| <p>Have you seen these articles?</p>
<p><a href="http://robert.zubek.net/blog/2008/04/09/sbcl-emacs-windows-vista/" rel="noreferrer">http://robert.zubek.net/blog/2008/04/09/sbcl-emacs-windows-vista/</a></p>
<p><a href="http://brainrack.wordpress.com/2008/05/29/running-sbcl-on-windows/" rel="noreferrer">http://brainrack.wordpress.com/2008/05/29/running-sbcl-on-windows/</a></p>
| <p>Make sure you have DEP off for SBCL.</p>
| 17,814 |
<p>I have some thread-related questions, assuming the following code. Please ignore the possible inefficiency of the code, I'm only interested in the thread part.</p>
<pre><code>//code without thread use
public static int getNextPrime(int from) {
int nextPrime = from+1;
boolean superPrime = false;
while(!superPrime) {
boolean prime = true;
for(int i = 2;i < nextPrime;i++) {
if(nextPrime % i == 0) {
prime = false;
}
}
if(prime) {
superPrime = true;
} else {
nextPrime++;
}
}
return nextPrime;
}
public static void main(String[] args) {
int primeStart = 5;
ArrayList list = new ArrayList();
for(int i = 0;i < 10000;i++) {
list.add(primeStart);
primeStart = getNextPrime(primeStart);
}
}
</code></pre>
<p>If I'm running the code like this and it takes about 56 seconds. If, however, I have the following code (as an alternative):</p>
<pre><code>public class PrimeRunnable implements Runnable {
private int from;
private int lastPrime;
public PrimeRunnable(int from) {
this.from = from;
}
public boolean isPrime(int number) {
for(int i = 2;i < from;i++) {
if((number % i) == 0) {
return false;
}
}
lastPrime = number;
return true;
}
public int getLastPrime() {
return lastPrime;
}
public void run() {
while(!isPrime(++from))
;
}
}
public static void main(String[] args) {
int primeStart = 5;
ArrayList list = new ArrayList();
for(int i = 0;i < 10000;i++) {
PrimeRunnable pr = new PrimeRunnable(primeStart);
Thread t = new Thread(pr);
t.start();
t.join();
primeStart = pr.getLastPrime();
list.add(primeStart);
}
}
</code></pre>
<p>The whole operation takes about 7 seconds. I am almost certain that even though I only create one thread at a time, a thread doesn't always finish when another is created. Is that right? I am also curious: why is the operation ending so fast?</p>
<p>When I'm joining a thread, do other threads keep running in the background, or is the joined thread the only one that's running?</p>
| <p>By putting the join() in the loop, you're starting a thread, then waiting for that thread to stop before running the next one. I think you probably want something more like this:</p>
<pre><code>public static void main(String[] args) {
int primeStart = 5;
// Make thread-safe list for adding results to
List list = Collections.synchronizedList(new ArrayList());
// Pull thread pool count out into a value so you can easily change it
int threadCount = 10000;
Thread[] threads = new Thread[threadCount];
// Start all threads
for(int i = 0;i < threadCount;i++) {
// Pass list to each Runnable here
// Also, I added +i here as I think the intention is
// to test 10000 possible numbers>5 for primeness -
// was testing 5 in all loops
PrimeRunnable pr = new PrimeRunnable(primeStart+i, list);
Thread[i] threads = new Thread(pr);
threads[i].start(); // thread is now running in parallel
}
// All threads now running in parallel
// Then wait for all threads to complete
for(int i=0; i<threadCount; i++) {
threads[i].join();
}
}
</code></pre>
<p>By the way pr.getLastPrime() will return 0 in the case of no prime, so you might want to filter that out before adding it to your list. The PrimeRunnable has to absorb the work of adding to the final results list. Also, I think PrimeRunnable was actually broken by still having incrementing code in it. I think this is fixed, but I'm not actually compiling this.</p>
<pre><code>public class PrimeRunnable implements Runnable {
private int from;
private List results; // shared but thread-safe
public PrimeRunnable(int from, List results) {
this.from = from;
this.results = results;
}
public void isPrime(int number) {
for(int i = 2;i < from;i++) {
if((number % i) == 0) {
return;
}
}
// found prime, add to shared results
this.results.add(number);
}
public void run() {
isPrime(from); // don't increment, just check one number
}
}
</code></pre>
<p>Running 10000 threads in parallel is not a good idea. It's a much better idea to create a reasonably sized fixed thread pool and have them pull work from a shared queue. Basically every worker pulls tasks from the same queue, works on them and saves the results somewhere. The closest port of this with Java 5+ is to use an ExecutorService backed by a thread pool. You could also use a CompletionService which combines an ExecutorService with a result queue. </p>
<p>An ExecutorService version would look like:</p>
<pre><code>public static void main(String[] args) {
int primeStart = 5;
// Make thread-safe list for adding results to
List list = Collections.synchronizedList(new ArrayList());
int threadCount = 16; // Experiment with this to find best on your machine
ExecutorService exec = Executors.newFixedThreadPool(threadCount);
int workCount = 10000; // See how # of work is now separate from # of threads?
for(int i = 0;i < workCount;i++) {
// submit work to the svc for execution across the thread pool
exec.execute(new PrimeRunnable(primeStart+i, list));
}
// Wait for all tasks to be done or timeout to go off
exec.awaitTermination(1, TimeUnit.DAYS);
}
</code></pre>
<p>Hope that gave you some ideas. And I hope the last example seemed a lot better than the first.</p>
| <p>Running a test, the second one doesn't seem to take 9 seconds--in fact, it takes at least as long as the first (which is to be expected, threding can't help the way it's implemented in your example.</p>
<p>Thread.join will only return when the thread.joined terminates, then the current thread will continue, the one you called join on will be dead.</p>
<p>For a quick reference--think threading when starting one iteration does not depend on the result of the previous one. </p>
| 30,867 |
<p>I was thinking of centralizing this functionality by having a single method that gets passed an AppState argument and it deals with changing the properties of all GUI elements based on this argument. Every time the app changes its state (ready, busy, downloading so partially busy, etc), this function is called with the appropriate state (or perhaps it's a bit field or something) and it does its magic.</p>
<p>If I scatter changing the state of GUI elements all over the place, then it becomes very easy to forget that when the app is in some state, this other widget over there needs to be disabled too, etc. </p>
<p>Any other ways to deal with this sort of thing?</p>
| <p>Emrah,</p>
<p>Your idea is good. You need to limit the state structure and this is the only way to ensure reliable UI. On the other hand do not follow the "one function" idea to strictly. Rather continuously follow its direction, by creating a function and then do progressively refactoring all attributes to a single "setter" function. You need to remember about a few things on your way:</p>
<ol>
<li><p>Use only one-way communication. Do not read the state from controls since this is the source of all evil. First limit the number of property reads and then the number of property writes.</p></li>
<li><p>You need to incorporate some caching methodology. Ensure that caching does not inject property reading into main code.</p></li>
<li><p>Leave dialog boxes alone, just ensure that all dialog box communication is done during opening and closing and not in between (as much as you can).</p></li>
<li><p>Implement wrappers on most commonly used controls to ensure strict communication framework. Do not create any global control framework.</p></li>
<li><p>Do not use this ideas unless your UI is really complex. In such case using regular WinForms or JavaScript events will lead you to much smaller code.</p></li>
<li><p>The less code the better. Do not refactor unless you loose lines.</p></li>
</ol>
<p>Good luck!</p>
| <p>Yes, this is the most time consuming part of the GUI work, to make a user friendly application. Disable this, enable that, hide this, show that. To make sure all controls has right states when inserting/updateing/deleteing/selecting/deselecting things.</p>
<p>I think thats where you tell a good programmer from a bad programmer. A bad programmer has an active "Save"-button when there is nothing changed to save, a good programmer enables the "save"-button only when there are things to save (just one example of many).</p>
<p>I like the idea of a UIControlstate-handler for this purpose.</p>
<p>Me.UIControlStates=UIControlstates.EditMode or something like that.</p>
<p>If having such object it could raise events when the state changes and there we put the code.</p>
<pre><code>Sub UIControlStates_StateChanged(sender as object, e as UIControlStateArgs)
if e.Oldstate=UIControlStates.Edit and e.NewState=UIControlStates.Normal then
rem Edit was aborted, reset fields
ResetFields()
end if
select case e.NewState
case UIControlStates.Edit
Rem enalbe/disable/hide/show, whatever
Case UIControlStates.Normal
Rem enalbe/disable/hide/show, whatever
Case UIControlStates.Busy
Rem enalbe/disable/hide/show, whatever
Case Else
Rem enalbe/disable/hide/show, whatever
end select
end sub
</code></pre>
| 43,825 |
<p>I'm new to ReSharper and am surprised that there isn't a template defined for</p>
<pre><code>public void MethodName(<params>)
{
}
</code></pre>
<p>I realize I could create one, but I would have thought this would have been part of the standard product. Perhaps I'm missing some other shortcut?</p>
| <p>I'm not aware of any such default template, but as you pointed out it's terribly easy to write:</p>
<pre><code>public void $METHODNAME$($PARAMS$)
{
$END$
}
</code></pre>
<p>However, I'm more that a tiny bit perplexed that you're interested in making all your methods both public and void <strong>by default.</strong></p>
| <p>My version:</p>
<pre><code>//-----------------------------------------------------------------
private $RETURN_TYPE$ $METHODNAME$($PARAMS$)
{
$CLIPBOARD$
$END$
}
</code></pre>
<p>Notice: In Template Editor you can insert macro for each <code>$FIELD$</code>. For example: "Clipboard content" macro for <code>$CLIPBOARD$</code>.</p>
| 41,701 |
<p>In my app have a window splitted by a QSplitter, and I need to remove an widget. </p>
<p>How can I do that? I can't find useful methods </p>
| <p>Many things in Qt cannot be "traditionally" removed. Instead call hide() on it and destruct it. From <a href="http://doc.qt.io/qt-5/qsplitter.html#details" rel="noreferrer">QSplitter</a> documentation:</p>
<blockquote>
<p>When you hide() a child its space will
be distributed among the other
children. It will be reinstated when
you show() it again.</p>
</blockquote>
| <p>Another easy way to prevent the child widget from getting deleted is to use QSplitter.takeWidget(child). This is also the recommended way of removing the widget from a splitter. (Qt Documentation)</p>
| 48,565 |
<p>What is the best practice for naming UI controls (textboxes, drop-downs, etc.) on forms and reports for reference in the code-behind pages?</p>
<p>I develop a lot of reports and forms in my office. I have several web applications providing about 80+ "live" reports being generated from various and multiple data sources (Access, SQL, Oracle). These reports are considered "live" because they accept user set paramaters from a form, then query the database to produce a report based on the current information available.</p>
<p>So, the process starts with obtaining the values set by the user, passing those to the database query, receiving the dataset, and finally assigning the dataset to the report. In some cases, additional fields displayed on the report need to be calculated from the dataset before the report can be generated. This requires referencing the output controls on the report to assign the calculated value.</p>
<p>While I don't really care to use prefixes in my code for variables or member fields, I do use them to identify the UI controls. For example, txtFirstName to reference the report control to assign the data from the FirstName field in the dataset to the display control on the report. Is there a better practice for naming/referencing UI controls on forms and reports?</p>
| <p>The main product I work on at work uses the txt_ pnl_ etc prefixes. This does work, though it is a bit of a pain at times when switching something that just hides/shows controls from say, a tr to a panel because you have to rename it. </p>
<p>What I've started doing in new projects, is naming my UI controls with a ui prefix; for example, uiName. Since I am strongly opposed to <a href="http://blogs.msdn.com/rick_schaut/archive/2004/02/14/73108.aspx" rel="noreferrer">anti-hungarian notation</a>, and strive for <a href="http://codebetter.com/blogs/eric.wise/archive/2005/12/06/135418.aspx" rel="noreferrer">self-documenting code</a>, this convention works well. In fact, if anything, it is <em>real</em> hungarian notation (ui being the prefix meaning user interface control). </p>
| <p>I've always felt that the only real reason for the prefixes was so you could have things like txtFirstName and lblFirstName on the same form/page. Since, the vast majority of the time, I'm really only working with the actual field control itself, I skip the prefix for that, and only use the prefixes for associated controls. For instance, lblMonth & Month, skipping the cbo prefix.</p>
<p>It saves typing, and it will generally be obvious what sort of control you're using in such forms. More complex controls will get the full prefix treatment.</p>
| 13,701 |
<p>I'm a pretty experienced Grails developer, but most of my experience has been with using grails for serving up JSON/XML to a flex app and some relatively simple HTML websites.</p>
<p>I've been diving deeper into using the sitemesh integration in grails and I'm struggling a little to find best practices for some more complex configurations, and I'm curious if there are any good tutorials or examples out there. The <a href="http://www.opensymphony.com/sitemesh/" rel="noreferrer">original Sitemesh</a> website isn't that useful as the tags it talks about aren't directly exposed in grails.</p>
<p>A google search is mostly showing old mailing list posts and some vanilla sitemesh stuff which is helping me to move a little further along, but it's a lot of trial and error.</p>
<p>I fully understand how the basic g:layoutTitle, g:layoutHead, and g:layoutBody tags work. Those are easy and well documented.</p>
<p>The kinds of things that I'd like to see examples for:</p>
<ul>
<li><p>g:applyLayout - <a href="http://grails.org/doc/1.0.x/ref/Tags/applyLayout.html" rel="noreferrer">the documentation on this</a> is weak and I don't fully understand the uses suggested in the main docs. How is this different than setting the <code>meta name='layout' content='foo'</code> property?</p></li>
<li><p>g:pageProperty - some better examples on how to pull and use properties into the main template by setting the values as meta tags in the page that's being decorated. The <a href="http://grails.org/doc/1.0.x/ref/Tags/pageProperty.html" rel="noreferrer">grails docs on pageProperty</a> show only the onload attribute from the body being brought forward. I think you can also use meta tag values here as well, anything else?</p></li>
<li><p>can you use multiple levels of sitemesh layouts? My testing seems to make me think that I can't, but that seems to reduce reusability. I think that the answer here is some usage of the g:applyLayout, but that's where I'm struggling the most. </p></li>
</ul>
| <p>Well, I can answer a bit:</p>
<p>Your first and third questions are related, as you can't chain layouts using the meta tag.</p>
<p>Your final page should have a meta tag as you suggest, but if you want to layer a layout on top of another layout, you put a g:applyLayout tag at the top of the child layout, pointing at the parent.</p>
<p>In your edit.gsp, you'd have:</p>
<pre><code><meta name="layout" content="editTemplate" />
</code></pre>
<p>and in editTemplate.gsp, you'd have:</p>
<pre><code><g:applyLayout name="baseTemplate" >
<!-- the html for the editTemplate -->
</g:applyLayout>
</code></pre>
<p>so edit.gsp would use editTemplate.gsp, which would use baseTemplate.gsp as a base layout. You can chain those as needed.</p>
<p>I haven't used g:pageProperty at all, so I can't throw you better examples there, sorry.</p>
| <p>See our <a href="https://github.com/Rabbytes/rabbtor-examples" rel="nofollow">Rabbtor Showcase App</a> for a few very good examples on </p>
<ul>
<li>creating nested layouts</li>
<li>rendering templates </li>
<li>applying layouts to specific parts of a page</li>
</ul>
<p>. This app is actually a showcase for our tool Rabbtor which enables using GSP outside Grails but parts related with Sitmesh are also valid for Grails.</p>
| 44,077 |
<p>I'm not new to web publishing, BUT I am new to publishing against a web site that is frequently used. Previously, the apps on this server were not hit very often, but we're rolling out a high demand application. So, what is the best practice for publishing to a live web server?</p>
<ol>
<li>Is it best to wait until the middle
of the night when people won't be on
it (Yes, I can pretty much rely on
that -- it's an intranet and
therefore will have times of
non-use)</li>
<li>Publish when new updates are made to
the trunk (dependent on build
success of course)</li>
<li>If 2 is true, then that seems bad if someone is using that specific page or DLL and it gets overwritten.</li>
</ol>
<p>...I'm sure there are lots of great places for this kind of thing, but I didn't use the right google search terms.</p>
| <blockquote>
<p><strong>@Nick DeVore wrote:</strong></p>
<p>If 2 is true, then that seems bad if
someone is using that specific page or
DLL and it gets overwritten.</p>
</blockquote>
<p>It's not really an issue if you're using ASP.NET stack (Webforms, MVC or rolling your own) because all your aspx files get compiled and therefore not touched by webserver. /bin/ folder is completely shadowed somewhere else, so libraries inside are not used by webserver either.</p>
<p>IIS will wait until all requests are done (however there is some timeout though) and then will proceed with compilation (if needed) and restart of AppDomain. If only a few files have changed, there won't even be AppDomain restart. IIS will load new assemblies (or compiled aspx/asmx/ascx files) into existing AppDomain.</p>
<blockquote>
<p><strong>@Nick DeVore wrote:</strong></p>
<p>Help me understand this a little bit
more. Point me to the place where this
is explained from Microsoft. Thanks!</p>
</blockquote>
<p>Try google for "IIS AppDomain" keywords. I found <a href="http://www.odetocode.com/articles/305.aspx" rel="nofollow noreferrer">What ASP.NET Programmers Should Know About Application Domains</a>.</p>
| <p>We do most of our updates in the wee small hours.</p>
<p>Handy hint, if this is an ASP.NET site, whatever time of the day you roll out, drop in an App_Offline.htm file with a message explaining to users that the site is down for maintenance. </p>
<p>Scott Guthrie has more info here:</p>
<p><a href="http://weblogs.asp.net/scottgu/archive/2006/04/09/442332.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2006/04/09/442332.aspx</a></p>
| 3,286 |
<p>Wondering if my approach is ok or could be improved:</p>
<pre><code>Public Class Company
private _id as Integer
private _name as String
private _location as String
Public Function LoadMultipleByLocation(Byval searchStr as String) as List(Of Company)
'sql etc here to build the list
End Function
End Classs
</code></pre>
<p>Thoughts on having the object mapping like this?</p>
| <p>In this case, you would create an instance of Company, and then use it to return a List of Companies?</p>
<p>Some people do this, but I prefer to seperate my data object into a dumb data container:</p>
<pre><code>public class Company : EntityBase
{
private int _id;
private string _name;
private string _location;
}
</code></pre>
<p>I use a base class (EntityBase) that contains common methods for converting the dumb entity back into a collection of SQLParameters (for persisting), as well as instantiating it from a passed in SQLReader (this gets overridden in each concrete class, to map the reader to the private variables).</p>
<p>I then prefer to use a "Service" class that actually makes the database calls, creates the appropriate entity object, and returns it, I can utilize polymorphism here to reduce code duplication heavily.</p>
| <p>@Dan</p>
<p>EntityBase would be a base class that each entity object would inherit, something like:</p>
<pre><code>public class EntityBase
{
public virtual string SaveSproc { get; }
public virtual void LoadFromReader(SqlReader reader)
{
}
public virtual void Save()
{
List<SqlParameters> paramList = = this.CreateParamsList();
DoSqlStuff(this.SaveSproc, paramList);
}
public virtual List<SqlParamenter> CreateParamsList()
{
return new List<SqlParameter>
}
}
public Company : EntityBase
{
private string _data;
public override string SaveSproc { get { return "SprocThatSaves"; } }
public override List<SqlParameter> CreateParamList()
{
List<SqlParameter> param = new List<SqlParameter>
param.Add(new SqlParameter("Data",_data);
return param;
}
public override void LoadFromReader(SqlReader reader)
{
// PsuedoCode
_data = reader["data"];
}
}
</code></pre>
<p>Now, your DB tier can get a reader with company data, and do something like:</p>
<pre><code>Company = new Company();
Company.LoadFromReader(reader);
</code></pre>
<p>And elsewhere, to save your data back:</p>
<pre><code>Company.Save();
</code></pre>
| 32,484 |
<p>In Eclipse, under <kbd>Windows</kbd> -> <kbd>Preference</kbd> -> <kbd>Java</kbd> -> <kbd>Code Style</kbd>, you can define code templates for comments and code, and you can setup a code formatter. </p>
<p>I'm wondering if it is possible in Eclipse to have these setting take affect every time I save a source file. Basically, instead of me highlighting everything and pressing <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>F</kbd>, I want Eclipse to be responsible for making sure my code is formatted properly.</p>
<p>Is this possible and how do you set it up?</p>
<p><strong>Note On Using the Auto-Format:</strong> It's probably best to choose "Format Edited Lines" as merging changes becomes very difficult when you reformat a whole file that is in source control already that was not formatted properly. Already did this to a co-worker.</p>
| <p>Under <kbd>Preferences</kbd>, choose <kbd>Java</kbd> --> <kbd>Editor</kbd> --> <kbd>Save Actions</kbd>. Check the <kbd>Perform the selected actions on save</kbd>, and check the <kbd>Format source code</kbd> box.</p>
<p>This may or may not be available in previous versions of Eclipse. I know it works in:</p>
<pre><code>Version: 3.3.3.r33x_r20080129-_19UEl7Ezk_gXF1kouft<br>
Build id: M20080221-1800
</code></pre>
| <p>If you find that you do not have a <kbd>Save Actions</kbd> preference under <kbd>Java</kbd>--> <kbd>Editor</kbd>, it may be because you are using an older version of Eclipse. In that case you can install the Format on save plugin from <a href="http://sourceforge.net/projects/ejp/files/eclipse%20formatonsave%20plugin/" rel="nofollow noreferrer">here</a>.</p>
<p>Then, under <kbd>Preferences</kbd>, choose <kbd>Java</kbd> --> <kbd>Format on save</kbd>. Select the <kbd>Run Format</kbd> option under <kbd>Select a code formatting action</kbd> </p>
| 29,039 |
<p>Consider this sample code:</p>
<pre><code><div class="containter" id="ControlGroupDiv">
<input onbeforeupdate="alert('bingo 0'); return false;" onclick="alert('click 0');return false;" id="Radio1" type="radio" value="0" name="test" checked="checked" />
<input onbeforeupdate="alert('bingo 1'); return false;" onclick="alert('click 1');return false;" id="Radio2" type="radio" value="1" name="test" />
<input onbeforeupdate="alert('bingo 2'); return false;" onclick="alert('click 2');return false;" id="Radio3" type="radio" value="2" name="test" />
<input onbeforeupdate="alert('bingo 3'); return false;" onclick="alert('click 3');return false;" id="Radio4" type="radio" value="3" name="test" />
<input onbeforeupdate="alert('bingo 4'); return false;" onclick="alert('click 4');return false;" id="Radio5" type="radio" value="4" name="test" />
<input onbeforeupdate="alert('bingo 5'); return false;" onclick="alert('click 5');return false;" id="Radio6" type="radio" value="5" name="test" />
</div>
</code></pre>
<p>On FireFox 2 and 3, putting the <code>return false</code> on the click event of a radio button prevents the value of it and of all the other radio buttons in the group from changing. This effectively makes it read-only without disabling it and turning it gray.</p>
<p>On Internet Explorer, if another radio button is checked and you click on a different one in the group, the checked one clears before the click event fires on the one you clicked. However, the one you clicked on does not get selected because of the 'return false' on the click event. </p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms536913(VS.85).aspx" rel="noreferrer">According to MSDN</a>, the <a href="http://msdn.microsoft.com/en-us/library/ms536908(VS.85).aspx" rel="noreferrer"><code>onbeforeupdate</code></a> event fires on all controls in the control group before the click event fires and I assumed that was where the other radio button was being cleared. But if you try the code above, no alert is ever shown from the <code>onbeforeupdate</code> event - you just get the click event alert. Evidently that event is never getting fired or there isn't a way to trap it.</p>
<p>Is there any event you can trap that allows you to prevent other radio buttons in the group from clearing?</p>
<p>Note that this is a simplified example, we are actually using jQuery to set event handlers and handle this.</p>
<p><strong>Update:</strong> </p>
<p>If you add this event to one of the radio buttons:</p>
<pre><code>onmousedown="alert('omd'); return false;"
</code></pre>
<p>The alert box pops up, you close it, and the click event <em>never fires</em>. So we thought we had it figured out, but no, it couldn't be that easy. If you remove the alert and change it to this: </p>
<pre><code>onmousedown="return false;"
</code></pre>
<p>It doesn't work. The other radio button clears and the click event on the button you clicked on fires. <code>onbeforeupdate</code> still never fires.</p>
<p>We thought it might be timing (that's always a theory even though it's rarely true), so I tried this:</p>
<pre><code>onmousedown="for (i=0; i<100000; i++) {;}; return false;"
</code></pre>
<p>You click, it pauses for a while, then the other radio button clears and then the click event fires. Aaargh!</p>
<p><strong>Update:</strong></p>
<p>Internet Explorer sucks. Unless someone comes up with a good idea, we're abandoning this approach and going with the checkbox jQuery extension which does do what we want, but puts a heavier client-side script burden on the page and requires more recoding of the HTML because of the ASP.Net server control rendering and master-page name mangling.</p>
| <p>Yup, that's a strange bug. I did manage to cook up a workaround. I use a bit of Prototype to handle class names here. It works in IE and FF. You can probably shorten it up with a selector instead of a crude loop.</p>
<pre><code><form name="f1">
<input type=radio onmouseover="recordMe()" onclick="clickCheck();return false" checked value="A" name="r1" id="radio1" />
<input type=radio onmouseover="recordMe()" onclick="clickCheck();return false" value="B" name="r1" id="radio2" />
</form>
<script type="text/javascript">
function recordMe() {
for(var x=0;x<document.f1.r1.length;x++) {
if(document.f1.r1[x].checked) {
$(document.f1.r1[x].id).addClassName('radioChecked')
}
}
}
function clickCheck() {
for(var x=0;x<document.f1.r1.length;x++) {
if($(document.f1.r1[x].id).hasClassName('radioChecked')) {
$(document.f1.r1[x].id).checked=true
}
}
}
</script>
</code></pre>
| <p>What is your goal? If you just want to capture when a change is made, run your logic on the onclick event. (this will get around IE's bug with onchange)</p>
<p>If you are trying to change the expected behavior of radio buttons - I would highly recommend against it.</p>
| 49,207 |
<p>I'm trying to create a new Excel file using jxl, but am having a hard time finding examples in their API documentation and online.</p>
| <p>After messing around awhile longer I finally found something that worked and saw there still wasn't a solution posted here yet, so here's what I found:</p>
<pre><code>try {
String fileName = "file.xls";
WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName));
workbook.createSheet("Sheet1", 0);
workbook.createSheet("Sheet2", 1);
workbook.createSheet("Sheet3", 2);
workbook.write();
workbook.close();
} catch (WriteException e) {
}
</code></pre>
| <pre><code>public void exportToExcel() {
final String fileName = "TodoList2.xls";
//Saving file in external storage
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/javatechig.todo");
//create directory if not exist
if(!directory.isDirectory()){
directory.mkdirs();
}
//file path
File file = new File(directory, fileName);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook;
try {
workbook = Workbook.createWorkbook(file, wbSettings);
//Excel sheet name. 0 represents first sheet
WritableSheet sheet = workbook.createSheet("MyShoppingList", 0);
Cursor cursor = mydb.rawQuery("select * from Contact", null);
try {
sheet.addCell(new Label(0, 0, "id")); // column and row
sheet.addCell(new Label(1, 0, "name"));
sheet.addCell(new Label(2,0,"ff "));
sheet.addCell(new Label(3,0,"uu"));
if (cursor.moveToFirst()) {
do {
String title =cursor.getString(0) ;
String desc = cursor.getString(1);
String name=cursor.getString(2);
String family=cursor.getString(3);
int i = cursor.getPosition() + 1;
sheet.addCell(new Label(0, i, title));
sheet.addCell(new Label(1, i, desc));
sheet.addCell(new Label(2,i,name));
sheet.addCell(new Label(3,i,family));
} while (cursor.moveToNext());
}
//closing cursor
cursor.close();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
workbook.write();
try {
workbook.close();
} catch (WriteException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
</code></pre>
| 18,161 |
<p>I've noticed there are a few solutions to allow the use of memcached on C# / ASP.NET:</p>
<ul>
<li><p>memcacheddotnet</p></li>
<li><p>enyim.com Memcached Client</p></li>
<li><p>BeIT</p></li>
</ul>
<p>Which one should I use? It seems like the enyim port has more active development, but I wanted to see what you guys recommend.</p>
| <p>I use <a href="http://code.google.com/p/beitmemcached/" rel="nofollow noreferrer">BeIT</a> and i am happy with it.</p>
| <p>Take a look at <a href="http://msdn.microsoft.com/en-us/data/cc655792.aspx" rel="nofollow noreferrer">Velocity</a>. Its Microsofts new alternative, its not stable yet but looks promising.</p>
| 34,378 |
<p>Assuming you can't use LINQ for whatever reason, is it a better practice to place your queries in stored procedures, or is it just as good a practice to execute <em>ad hoc</em> queries against the database (say, SQL Server for argument's sake)?</p>
| <p>In my experience writing mostly WinForms Client/Server apps these are the simple conclusions I've come to:</p>
<p><strong>Use Stored Procedures:</strong></p>
<ol>
<li>For any complex data work. If you're going to be doing something truly requiring a cursor or temp tables it's usually fastest to do it within SQL Server.</li>
<li>When you need to lock down access to the data. If you don't give table access to users (or role or whatever) you can be sure that the only way to interact with the data is through the SP's you create.</li>
</ol>
<p><strong>Use ad-hoc queries:</strong></p>
<ol>
<li>For CRUD when you don't need to restrict data access (or are doing so in another manner).</li>
<li>For simple searches. Creating SP's for a bunch of search criteria is a pain and difficult to maintain. If you can generate a reasonably fast search query use that.</li>
</ol>
<p>In most of my applications I've used both SP's and ad-hoc sql, though I find I'm using SP's less and less as they end up being code just like C#, only harder to version control, test, and maintain. I would recommend using ad-hoc sql unless you can find a specific reason not to.</p>
| <blockquote>
<p>is it good system architecture if you
let connect 1000 desktops directly to
database?</p>
</blockquote>
<p>No it's obviously not, it's maybe a poor example but I think the point I was trying to make is clear, your DBA looks after your database infrastructure this is were their expertise is, stuffing SQL in code locks the door to them and their expertise.</p>
| 4,293 |
<p>I have a Linq Query where I do the following:</p>
<pre><code>query = context.Select(a => new
{
Course = (CourseType)a.CourseCode,
CourseDetail = sting.Format("Course: {0}\r\nCourse Detail: {1}", ((CourseType)a.CourseCode).ToString(), a.CourseDetail)
});
enum CourseType{
Unknown = 0,
FullTime = 1,
PartTime = 2
}
</code></pre>
<p>a.CourseCode is an int and a.CourseDetail is a string.
I now bind a label inside a grid to this query. I set the Text to <%# Eval("Course")%> and the Tooltip to <%# Eval("CourseDetail")%>.
Although the text in the label correctly displays the value expected from Enum.ToString(), the Tootip always shows the value of the integer value of the enum as 1,2,3...</p>
<p>Whats causing this?</p>
<p>Kind regards,</p>
| <p>Are you sure that's the exact code you're using? </p>
<p>There's a typo: sting.Format instead of st<strong>r</strong>ing.Format, so I guess you've retyped the code for this question. Check to make sure all your brackets are in the correct place etc.</p>
<p>I've tried the following code, prints out "Fulltime", so the .ToString method should work as you're expecting:</p>
<pre><code>class Program
{
enum CourseType
{
Unknown = 0,
Fulltime = 1,
Parttime = 2
}
static void Main(string[] args)
{
var i = 1;
Console.WriteLine("Coursetype: {0}", ((CourseType)i).ToString());
}
}
</code></pre>
| <p>Not directly an answer, but just a question, why are you typing:</p>
<pre><code>((CourseType)i).ToString()
((CourseType)a.CourseCode).ToString()
</code></pre>
<p>The string.Format takes objects as ParamArray and calls .ToString() on each of them. The additional .ToString() you use performs just the creation of a new string that is not needed.</p>
| 49,359 |
<p>We are developing a port of the GNU Assembler for a client architecture.
Now the problem being faced is that:</p>
<p>If an immediate operand to an instruction is an expression involving more than one relocatable symbols, how is it handled in output file in elf format. What will be the relocation information produced in such a case?</p>
<p>For example:</p>
<pre><code>j label1 + label2
</code></pre>
<p>where label1 and label2 are defined in relocatable sections, they might be the same sections or different relocatable sections.</p>
| <p>ELF doesn't know about instructions, per se. It knows about particular encodings of symbol offsets within instructions. In the assembler, you would need to output two relocation records, each with the corresponding [address,type,symbol] triplet to properly patch that portion of the instruction. The linker wouldn't necessarily even know that these two records point to the same instruction.</p>
<p>The ELF relocation types are completely CPU-dependent (or, to be more precise, ISA-dependent), so you are free to define whatever relocations you need for a new architecture.</p>
<p>It's hard to be more specific without details of the instruction encoding.</p>
| <p>I know jack about ELF and only a little more about linking but...</p>
<p>I would expect that each operand is handled the same way that it would be if there was only one.</p>
<p>OTOH might the issue be that the format for <code>j</code> alters depending on where the labels are? If so, I <em>think</em> you're sunk as linkers aren't smart enough to do that sort of thing (the ADA build system IIRC might be smarter than most so you might look at it.)</p>
| 45,094 |
<p>Does anyone know of papers/books/etc. that document patterns for databases? For example, one common rule of thumb is that every table should have a primary key and that the key should be <a href="http://en.wikipedia.org/wiki/Surrogate_key" rel="noreferrer">devoid of information content</a>. So I was wondering if anyone had written a book or published papers regarding design patterns for designing relational databases?</p>
<hr>
<p>@Gaius,</p>
<p>That is the question that a database designer needs to weigh--what is the probable stability of the database structure? Given a long-enough horizon nothing is stable. Or to say the converse, given a long-enough horizon, everything is subject to change. A surrogate key (in theory) should never change its meaning because it never had meaning to begin with. </p>
<p>I guess the other thing to consider in that particular design scenario is who is it that will be seeing the primary key? If the primary key is something that end-users will actually need to refer to then it makes sense to make it something they can understand. But I can't think of many cases where an end-user needs to see a primary key; usually the primary key is present to allow the DB engine to speed up certain operations.</p>
<p>My original thought in asking the question was to find design patterns for database design that were codified by more experienced database designers than myself so as to, hopefully, avoid some easily avoidable errors. It would be interesting reading if anyone had ever codified database design anti-patterns. </p>
| <p>Specifically, regarding keys: I strongly disagree with the strange idea that keys must be without meaning. In general, I consider a database a collection of facts; as soon as you start adding arbitrary numbers (like generated keys) and other irrelevant information into it, it should be a warning sign. I recommend <a href="http://www.intelligententerprise.com/030320/605celko1_1.jhtml" rel="noreferrer">this articly by Joe Celko</a> for more on keys.</p>
<p>More general notes:</p>
<p>Suggestions for schema designs/data models for different businesses:
David C. Hay: Data Model Patterns: Conventions of Thought
Rather old, but there is a reason why it's still in print
<br /><a href="http://www.dorsethouse.com/books/dmp.html" rel="noreferrer">http://www.dorsethouse.com/books/dmp.html</a></p>
<p>Maybe not very pattern-like, but still very good:
Stephane Faroult, Peter Robson: The Art of SQL
<a href="http://oreilly.com/catalog/9780596008949/" rel="noreferrer">http://oreilly.com/catalog/9780596008949/</a></p>
<p>Another one which I can recommend:
Vadim Tropashko: SQL Design Patterns - The Expert Guide to SQL Programming
<a href="http://www.rampant-books.com/book_2006_1_sql_coding_styles.htm" rel="noreferrer">http://www.rampant-books.com/book_2006_1_sql_coding_styles.htm</a></p>
<p>Systematic text-book about data modelling:
Graeme Simsion & Graham Witt, "Data Modeling Essentials"
<a href="http://www.elsevierdirect.com/product.jsp?isbn=9780126445510" rel="noreferrer">http://www.elsevierdirect.com/product.jsp?isbn=9780126445510</a></p>
<p>Maybe you are actually looking for a "style guide"?. I that case:
Joe Celko: SQL Programming Style
<a href="http://www.elsevierdirect.com/product.jsp?isbn=9780120887972" rel="noreferrer">http://www.elsevierdirect.com/product.jsp?isbn=9780120887972</a></p>
| <p>To answer exactly: <a href="http://www.amazon.com/s/ref=nb_ss_b/102-6537774-4068964?url=search-alias%3Dstripbooks&field-keywords=database+design+patterns&x=0&y=0" rel="nofollow noreferrer">yes</a>. There are s*-tons of info written on 'good' database design. Although youe example rule of thumb is certainly questionable.</p>
| 6,601 |
<p>We are now using NHibernate to connect to different database base on where our software is installed. So I am porting many SQL Procedures to Oracle.</p>
<p>SQL Server has a nice function called DateDiff which takes a date part, startdate and enddate.</p>
<p>Date parts examples are day, week, month, year, etc. . . </p>
<p>What is the Oracle equivalent?</p>
<p>I have not found one do I have to create my own version of it?</p>
<p><strong>(update by Mark Harrison)</strong> there are several nice answers that explain Oracle date arithmetic. If you need an Oracle datediff() see Einstein's answer. (I need this to keep spme SQL scripts compatible between Sybase and Oracle.) Note that this question applies equally to Sybase.</p>
| <p>I stole most of this from an old tom article a few years ago, fixed some bugs from the article and cleaned it up. The demarcation lines for datediff are calculated differently between oracle and MSSQL so you have to be careful with some examples floating around out there that don't properly account for MSSQL/Sybase style boundaries which do not provide fractional results.</p>
<p>With the following you should be able to use MSSQL syntax and get the same results as MSSQL such as SELECT DATEDIFF(dd,getdate(),DATEADD(dd,5,getdate())) FROM DUAL;</p>
<p>I claim only that it works - not that its effecient or the best way to do it. I'm not an Oracle person :) And you might want to think twice about using my function macros to workaround needing quotes around dd,mm,hh,mi..etc.</p>
<p><strong>(update by Mark Harrison)</strong> added dy function as alias for dd.</p>
<pre><code>CREATE OR REPLACE FUNCTION GetDate
RETURN date IS today date;
BEGIN
RETURN(sysdate);
END;
/
CREATE OR REPLACE FUNCTION mm RETURN VARCHAR2 IS BEGIN RETURN('mm'); END;
/
CREATE OR REPLACE FUNCTION yy RETURN VARCHAR2 IS BEGIN RETURN('yyyy'); END;
/
CREATE OR REPLACE FUNCTION dd RETURN VARCHAR2 IS BEGIN RETURN('dd'); END;
/
CREATE OR REPLACE FUNCTION dy RETURN VARCHAR2 IS BEGIN RETURN('dd'); END;
/
CREATE OR REPLACE FUNCTION hh RETURN VARCHAR2 IS BEGIN RETURN('hh'); END;
/
CREATE OR REPLACE FUNCTION mi RETURN VARCHAR2 IS BEGIN RETURN('mi'); END;
/
CREATE OR REPLACE FUNCTION ss RETURN VARCHAR2 IS BEGIN RETURN('ss'); END;
/
CREATE OR REPLACE Function DateAdd(date_type IN varchar2, offset IN integer, date_in IN date )
RETURN date IS date_returned date;
BEGIN
date_returned := CASE date_type
WHEN 'mm' THEN add_months(date_in,TRUNC(offset))
WHEN 'yyyy' THEN add_months(date_in,TRUNC(offset) * 12)
WHEN 'dd' THEN date_in + TRUNC(offset)
WHEN 'hh' THEN date_in + (TRUNC(offset) / 24)
WHEN 'mi' THEN date_in + (TRUNC(offset) /24/60)
WHEN 'ss' THEN date_in + (TRUNC(offset) /24/60/60)
END;
RETURN(date_returned);
END;
/
CREATE OR REPLACE Function DateDiff( return_type IN varchar2, date_1 IN date, date_2 IN date)
RETURN integer IS number_return integer;
BEGIN
number_return := CASE return_type
WHEN 'mm' THEN ROUND(MONTHS_BETWEEN(TRUNC(date_2,'MM'),TRUNC(date_1, 'MM')))
WHEN 'yyyy' THEN ROUND(MONTHS_BETWEEN(TRUNC(date_2,'YYYY'), TRUNC(date_1, 'YYYY')))/12
WHEN 'dd' THEN ROUND((TRUNC(date_2,'DD') - TRUNC(date_1, 'DD')))
WHEN 'hh' THEN (TRUNC(date_2,'HH') - TRUNC(date_1,'HH')) * 24
WHEN 'mi' THEN (TRUNC(date_2,'MI') - TRUNC(date_1,'MI')) * 24 * 60
WHEN 'ss' THEN (date_2 - date_1) * 24 * 60 * 60
END;
RETURN(number_return);
END;
/
</code></pre>
| <p>YOU Could write a function in oracle for this</p>
<pre><code>function datediff( p_what in varchar2, p_d1 in date, p_d2 in date) return number as l_result number;
BEGIN
select (p_d2-p_d1) *
decode( upper(p_what), 'SS', 24*60*60, 'MI', 24*60, 'HH', 24, NULL )
into l_result from dual;
return l_result;
END;
</code></pre>
<p>and use it like :</p>
<pre><code>DATEDIFF('YYYY-MM-DD', SYSTIMESTAMP, SYSTIMESTAMP)
</code></pre>
| 6,544 |
<p>In my database I have tables that define types for example</p>
<p>Table: Publication Types</p>
<pre>
ID | Type
----------
1 | Article
2 | Abstract
3 | Book
....
</pre>
<p>Which is related through the ID key to a publication tables which has the field <em>TypeID</em>.</p>
<p>I then create a PublicationTable data table my .NET application which I want to filter based on the publication type. For example the following function gives me the number of publications for a specific author and publication type.</p>
<pre>
Public Function countPublications(ByVal authorID As Integer, _
ByVal publicationType As Integer) As Integer
Dim authPubs As New PublicationsDataSet.tblPublicationsDataTable
authPubs = Me.getAuthorsPublications(authorID)
Dim dv As New DataView(authPubs)
dv.RowFilter = "status='published' AND type='" + _
publicationType.ToString + "'"
Return dv.Count
End Function
</pre>
<p>To call this function to get a count of articles by an author of a specific type, I could</p>
<ol>
<li><p>call the function with two integers</p>
<p>countPublications(authorID, 1)</p></li>
<li><p>setup an enum so that I can write</p>
<p>countPublications(authorID, pubType.Article)</p>
<p>or </p></li>
<li><p>somehow use the publication type table to filter the publication data set but I haven't got my head around how to do this.</p></li>
</ol>
<p>What other approaches should I consider.</p>
<p>Thanks</p>
| <p>if publication types are essentially static, enums are fine</p>
<p>there is arguably little difference between embedding </p>
<pre><code>inner join lookuptable lt on lt.id = (int)myenum.sometype
</code></pre>
<p>in a query and adding </p>
<pre><code>inner join lookuptable lt on lt.name = "somehardcodeddescription"
</code></pre>
<p>they're both embedded constants, the former just has a well-defined type behind it</p>
<p>alternately you could use</p>
<pre><code>inner join lookuptable lt on lt.name = myenum.sometype.ToString
</code></pre>
<p>i prefer the former</p>
<p>if, on the other hand, new lookup types may be added after the code is deployed, then an enum will quickly become outdated; </p>
<p>but if there is core set of static enum values that the code needs and the rest don't matter then the former solution is still fine</p>
<p>as usual, "it depends" ;-)</p>
| <p>For various reasons it would be nice to keep lists such as my publication type list and others in one place; the database. Then there is only one place for them to change. However, it seems to me that this adds some complexity to the code and I would still need to have some hard coded elements in the code if I wanted to refer to a specific publication type such as Journal Articles. Therefore, having an enumerated type that reflects the data in the table gives me the possibility of calling my count function in a readable manner</p>
<pre><code>countPublications(authorID, publicationType.JournalArticle)
</code></pre>
<p>If the data in the table changes which is unlikely, I can have a comment in the database to remind the maintainer (probably me) to update the enumerated type in the code and vice versa. </p>
<p>Thank you all for your answers. I can now proceed with my mind at ease.</p>
| 31,420 |
<p>I have a MySQL table with coordinates, the column names are X and Y. Now I want to swap the column values in this table, so that X becomes Y and Y becomes X. The most apparent solution would be renaming the columns, but I don't want to make structure changes since I don't necessarily have permissions to do that.</p>
<p>Is this possible to do with <b>UPDATE</b> in some way? <b>UPDATE table SET X=Y, Y=X</b> obviously won't do what I want.</p>
<hr>
<p>Edit: Please note that my restriction on permissions, mentioned above, effectively prevents the use of ALTER TABLE or other commands that change the table/database structure. Renaming columns or adding new ones are unfortunately not options.</p>
| <p>I just had to deal with the same and I'll summarize my findings.</p>
<ol>
<li><p>The <code>UPDATE table SET X=Y, Y=X</code> approach obviously doesn't work, as it'll just set both values to Y.</p></li>
<li><p>Here's a method that uses a temporary variable. Thanks to Antony from the comments of <a href="http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/" rel="noreferrer">http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/</a> for the "IS NOT NULL" tweak. Without it, the query works unpredictably. See the table schema at the end of the post. This method doesn't swap the values if one of them is NULL. Use method #3 that doesn't have this limitation.</p>
<p><code>UPDATE swap_test SET x=y, y=@temp WHERE (@temp:=x) IS NOT NULL;</code></p></li>
<li><p>This method was offered by Dipin in, yet again, the comments of <a href="http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/" rel="noreferrer">http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/</a>. I think it’s the most elegant and clean solution. It works with both NULL and non-NULL values.</p>
<p><code>UPDATE swap_test SET x=(@temp:=x), x = y, y = @temp;</code></p></li>
<li><p>Another approach I came up with that seems to work:</p>
<p><code>UPDATE swap_test s1, swap_test s2 SET s1.x=s1.y, s1.y=s2.x WHERE s1.id=s2.id;</code></p></li>
</ol>
<p>Essentially, the 1st table is the one getting updated and the 2nd one is used to pull the old data from.<br/>
Note that this approach requires a primary key to be present.</p>
<p>This is my test schema:</p>
<pre><code>CREATE TABLE `swap_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`x` varchar(255) DEFAULT NULL,
`y` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `swap_test` VALUES ('1', 'a', '10');
INSERT INTO `swap_test` VALUES ('2', NULL, '20');
INSERT INTO `swap_test` VALUES ('3', 'c', NULL);
</code></pre>
| <p>Swapping of column values using single query</p>
<p>UPDATE my_table SET a=@tmp:=a, a=b, b=@tmp;</p>
<p>cheers...!</p>
| 5,842 |
<p>Is there a way to get Visual Studio 2008 to do matching brace highlighting for Javascript?</p>
<p>If there is no way to do it in Studio, can it be done using ReSharper?</p>
<p>Thanks!!</p>
| <p>Note that Visual Studio will still find a matching brace in JavaScript via Ctrl + ].</p>
| <p>For what it's worth, I use the most excellent ViEmu plugin for visual studio, and it supplies the Vi(m) paren/brace/bracket matching. </p>
<p>ViEmu is <a href="http://www.viemu.com" rel="nofollow noreferrer">here</a></p>
<p>Of course, if you're not a Vi lover, the price for matching parens may be too high. ;)</p>
| 31,577 |
<p>This has me stumped. I had been printing normally until this happened. Below is an expurgated version of my headache over two days. Some help would be appreciated.</p>
<p>Printer is Hypercube Evolution (CoreXY) using Bowden tube and eSun PLA+ filament. Bowden tube goes from inside the feed cone in the extruder straight through the heatsink and into the feed throat of the heatbreak. Genuine Titan Extruder. Extruder stepper has no label.</p>
<p>Started a new print. Printer was at ambient temperature of about 18 degrees. Printer brought up to temperature, 60° bed and 200° hotend. Bed homed and levelled in gcode. Print speed 60mm/s. Hotend moved to centre of bed and print started. No filament extruded and extruder stepper was making a grinding noise. Normally expect this to be hotend not hot enough. Altered pressure adjustment on the extruder. Made no difference. Cancelled print.</p>
<p>Lowered bed out of the way. Hotend to 225°. Attempted to extrude filament. Nothing other than extruder stepper grinding. Tried to retract filament, no motion and extruder stepper still grinding.</p>
<p>Disassembled hotend. No problem removing nozzle. The heatbreak and the heatsink Bowden connections would not give. There was filament between the Bowden connector and the heatbreak. When this snapped, I could get the parts free. The heatbreak had stretched filament stuck in the feed throat. There was thickened filament in the Bowden tube preventing retraction. It is still in there and stuck. Extruder stepper replaced and VREF adjusted. New all metal 1.75mm heatbreak. Bowden tube replaced. Hotend reassembled.
Hotend to 200° and extruded 200mm of filament. There was some smoke from the hot end at first and the initial filament was burnt. Everything seemed to be working, hotend turned off and Z-offset calculated and stored.</p>
<p>Lowered the bed, hotend back to 200°. The problem was back, could not extrude nor retract, extruder stepper grinding. I was able to withdraw the filament manually. The end was slightly thickened with a whispy "tail". Cut the filament, hotend to 225° and re-fed filament. Acrid smoke initially from the hotend and filament extruded. Hotend allowed to cool to room temperature. Hotend to 225°. Filament would not extrude nor retract. Hotend turned off and left.</p>
<p>Disassembled hotend. Again, heatbreak and Bowden connections to heatsink would not give. Managed to manually feed filament whilst unscrewing heatbreak. The filament found is shown in the attached picture. The small thick bulge would seem to have occurred in the tiny area where the Bowden tube enters the feed throat of the heatbreak. The thin filament is stretching whilst trying to retract. After that can be seen where the filament has thickened again. Mangled filament trimmed and hotend reassembled making sure that the Bowden tube was seated in the heatbreak feed throat. Hotend to 200° and extruded 200mm filament. Tried a test print, not very good, but worked. Tried a second print, the problem was back again.</p>
<p>Has anybody any ideas how to solve this? I have also checked that the thermistor is reading correctly, changed the roll of filament (just in case I had a bad roll) and have replaced the extruder stepper driver.</p>
<p><a href="https://i.stack.imgur.com/iOIoz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iOIoz.jpg" alt="Filament from the Hotend" /></a></p>
| <p>The lump at the top of the heatbreak is because there is a gap between your bowden tube and the heatbreak. Liquid filament is leaking out of the heatbreak and solidifying there. When you reassemble, you need to close this gap.</p>
<p>There should not be smoke coming out of your nozzle. Maybe when it is new, there might be a bit of oil that would smoke, but it should only do that once. If you are getting burned filament, your nozzle temperature is too high. Either the control system is overshooting and the temperature spikes, or your temperature sensor has a problem.</p>
<p>The thickened filament is worrisome. With the filament jammed at the heatbreak, if the filament is soft, it might be getting compressed. But PLA should not do this unless there is enough heat leaking into the bowden tube to soften it.</p>
| <p>Worked out the reason for the thickening filament. A number of sites refer to heat creep and suggest that you check that the heatsink is clear and the heatsink fan is working properly. In my case, they were. However, the fan outlet (where it blows on the heat sink) was full of garbage. Cleaned that out things improved. Also replacing a dodgy thermistor cleared up the residual problem.</p>
| 2,061 |
<p>The .NET <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="noreferrer">IDisposable Pattern</a> <em>implies</em> that if you write a finalizer, and implement IDisposable, that your finalizer needs to explicitly call Dispose.
This is logical, and is what I've always done in the rare situations where a finalizer is warranted.</p>
<p>However, what happens if I just do this:</p>
<pre><code>class Foo : IDisposable
{
public void Dispose(){ CloseSomeHandle(); }
}
</code></pre>
<p>and don't implement a finalizer, or anything. Will the framework call the Dispose method for me?</p>
<p>Yes I realise this sounds dumb, and all logic implies that it won't, but I've always had 2 things at the back of my head which have made me unsure.</p>
<ol>
<li><p>Someone a few years ago once told me that it would in fact do this, and that person had a very solid track record of "knowing their stuff."</p></li>
<li><p>The compiler/framework does other 'magic' things depending on what interfaces you implement (eg: foreach, extension methods, serialization based on attributes, etc), so it makes sense that this might be 'magic' too. </p></li>
</ol>
<p>While I've read a lot of stuff about it, and there's been lots of things implied, I've never been able to find a <strong>definitive</strong> Yes or No answer to this question.</p>
| <p>The .Net Garbage Collector calls the Object.Finalize method of an object on garbage collection. By <strong>default</strong> this does <strong>nothing</strong> and must be overidden if you want to free additional resources.</p>
<p>Dispose is NOT automatically called and must be <strong>explicity</strong> called if resources are to be released, such as within a 'using' or 'try finally' block</p>
<p>see <a href="http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx</a> for more information</p>
| <p>The documentation on <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="nofollow noreferrer">IDisposable</a> gives a pretty clear and detailed explaination of the behavior, as well as example code. The GC will NOT call the <code>Dispose()</code> method on the interface, but it will call the finalizer for your object.</p>
| 6,683 |
<p>Since you can use reflector to reverse-engineer a .Net app, is there any reason to NOT ship the pdb files with the app? If you do ship them with it, then your stack trace will include the line number with the problem, which is useful if it crashes.</p>
<p>Please only enter 1 reason per comment for voting.</p>
| <p>Shipping pdb does not give any additional convenience to an user. So there are no reasons to ship pdb files with the app. Besides pdb file usually has a large size.</p>
<p>Instead of shipping pdb files you should use a local Microsoft Symbol Server for a fast access to pdb files corresponding to error reports. <a href="http://msdn.microsoft.com/en-us/library/ms681417(VS.85).aspx" rel="nofollow noreferrer">Here</a> you can find the detailed explanation how to use Symbol Server.</p>
| <p>Why would you ship anything more than you need to?</p>
| 11,460 |
<p>How can I create a table that has its first row and first column both locked, as in Excel, when you activate 'freeze panes'? I need the table to both scroll horizontally and vertically (a lot of solutions for this exist, but only allow vertical scrolling).</p>
<p>So, when you scroll down in the table, the first row will stay put, since it will have the column headings. This may end up being in a <code>thead</code>, or it may not, whatever makes the solution easier.</p>
<p>When you scroll right, the first column stays put, since it holds the labels for the rows.</p>
<p>I'm pretty certain this is impossible with CSS alone, but can anyone point me toward a JavaScript solution? It needs to work in all major browsers.</p>
| <p>Oh well, I looked up for scrollable table with fixed column to understand the need of this specific requirement and your question was one of it with no close answers.. </p>
<p>I answered this question <a href="https://stackoverflow.com/questions/10838700/large-dynamically-sized-html-table-with-a-fixed-scroll-row-and-fixed-scroll-colu/10922732#10922732">Large dynamically sized html table with a fixed scroll row and fixed scroll column</a> which inspired to showcase my work as a plugin <a href="https://github.com/meetselva/fixed-table-rows-cols" rel="nofollow noreferrer">https://github.com/meetselva/fixed-table-rows-cols</a></p>
<p>The plugin basically converts a well formatted HTML table to a scrollable table with fixed table header and columns.</p>
<p>The usage is as below,</p>
<pre><code>$('#myTable').fxdHdrCol({
fixedCols : 3, /* 3 fixed columns */
width : "100%", /* set the width of the container (fixed or percentage)*/
height : 500 /* set the height of the container */
});
</code></pre>
<p>You can check the <a href="http://meetselva.github.io/fixed-table-rows-cols/" rel="nofollow noreferrer">demo and documentation here</a></p>
| <p>I ran across a site a few weeks back. This is a working example of the first column locked but it is not browser compatible with Firefox. I didn't do a lot of checking around but it seems it only works in IE. There are some notes the author provided along with it that you can read.</p>
<p>Lock the First column:
<a href="http://home.tampabay.rr.com/bmerkey/examples/locked-column-csv.html" rel="nofollow noreferrer">http://home.tampabay.rr.com/bmerkey/examples/locked-column-csv.html</a></p>
<p>Let me know if you need the Javascript to lock the Table headers too.</p>
| 37,858 |
<p>I have a setup project created by Visual Studio 2005, and consists of both a C# .NET 2.0 project and C++ MFC project, and the C++ run time. It works properly when run from the main console, but when run over a Terminal Server session on a Windows XP target, the install fails in the following way -
When the Setup.exe is invoked, it immediately crashes before the first welcome screen is displayed. When invoked over a physical console, the setup runs normally.</p>
<p>I figured I could go back to a lab machine to debug, but it runs fine on a lab machine over Terminal Server.</p>
<p>I see other descriptions of setup problems over Terminal Server sessions, but I don't see a definite solution. Both machines have a nearly identical configuration except that the one that is failing also has the GoToMyPC Host installed.</p>
<p>Has anyone else seen these problems, and how can I troubleshoot this?</p>
<p>Thanks,</p>
| <p>I had LOTS of issues with developing installers (and software in general) for terminal server. I hate that damn thing.</p>
<p>Anyway, VS Setup Projects are just .msi files, and run using the Windows installer framework.</p>
<p>This will drop a log file when it errors out, they're called MSIc183.LOG (swap the c183 for some random numbers and letters), and they go in your logged-in-user account's temp directory.</p>
<p>The easiest way to find that is to type <code>%TEMP%</code> into the windows explorer address bar - once you're there have a look for these log files, they might give you a clue.</p>
<ul>
<li>Note - Under terminal server, sometimes the logs don't go directly into <code>%TEMP%</code>, but under numbered subdirectories. If you can't find any MSIXYZ.LOG files in there, look for directories called <code>1</code>, <code>2</code>, and so on, and look in those.</li>
</ul>
<p>If you find a log file, but can't get any clues from it, post it here. I've looked at more than I care to thing about, so I may be able to help</p>
| <p>Before installing, drop to a command prompt and type</p>
<pre><code>CHANGE USER /INSTALL
</code></pre>
<p>Then install your software. Once the install has completed, drop back to the command prompt and type:</p>
<pre><code>CHANGE USER /EXECUTE
</code></pre>
<p>Alternatively, don't start the installation by a double click but instead go to Add/Remove Programs and select "install software" from there. </p>
<p>Good luck!</p>
| 3,589 |
<p>How do they compare to the DevXpress ones or the original MSOffice ones.<br>
Are they worth investing time in them (for practical usage now, not academic curiosity which I'll do anyway)?</p>
| <p>From my experience, the new ribbon control implements the entire specification as laid out by Microsoft. The only issue I noticed was a slight flicker when the form was resized which caused one of the sections to collapse or expand. </p>
<p>Worth spending time in? Definitely, as they are lighter weight and its a matter of time before someone gets rid of the flicker (could be as simple as a lockwindowupdate inserted in the source?). It doesn't hurt to use the Delphi action manager, from which all is based.</p>
| <p>IMO, the DevExpress ribbon control is much more complex than it needs to be. i own the DevExpress ribbon control but converted to using the delphi TRibbon. the delphi TRibbon isn't perfect either but i've learned to avoid these problems.</p>
| 15,857 |
<p>With the jQuery datepicker, how does one change the year range that is displayed? On the jQuery UI site it says the default is "10 years before and after the current year are shown". I want to use this for a birthday selection and 10 years before today is no good. Can this be done with the jQuery datepicker or will I have to use a different solution?</p>
<p>link to datepicker demo: <a href="http://jqueryui.com/demos/datepicker/#dropdown-month-year" rel="noreferrer">http://jqueryui.com/demos/datepicker/#dropdown-month-year</a></p>
| <p>If you look down the demo page a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "<code>Year dropdown shows last 20 years</code>" demo , and hit view source:</p>
<pre><code>$("#restricting").datepicker({
yearRange: "-20:+0", // this is the option you're looking for
showOn: "both",
buttonImage: "templates/images/calendar.gif",
buttonImageOnly: true
});
</code></pre>
<p>You'll want to do the same (obviously changing <code>-20</code> to <code>-100</code> or something).</p>
| <p>i think this may work as well </p>
<pre><code>$(function () {
$(".DatepickerInputdob").datepicker({
dateFormat: "d M yy",
changeMonth: true,
changeYear: true,
yearRange: '1900:+0',
defaultDate: '01 JAN 1900'
});
</code></pre>
| 33,859 |
<p>I can't seem to figure out what I am doing wrong here. I publish my website to my server and when I try to run it I get the following exception:</p>
<blockquote>
<p>Could not load the assembly 'App_Web_kh7-x3ka'. Make sure that it is compiled before accessing the page.</p>
</blockquote>
<p>Has anyone else ever encountered this?</p>
| <p>This can also happen when you've taken a pre-compiled aspx page and edited it as if uncompiled, such as copying it from the Live server and overwriting your dev/working version.</p>
<p>On the first line of your aspx page within the <code><%@Page /></code> tag you'll probably see an attribute like: </p>
<p><code>inherits="yourPageClass, App_Web_kh7-x3ka"</code>. </p>
<p>Delete the "<code>App_Web_XXXX</code>" part and add the CodeFile attribute pointing to your code behind file:</p>
<p><code>CodeFile="yourPageFile.aspx.cs"</code></p>
<p>The <code><%@Page /></code> tag should now look similar to when you create a new page from scratch.</p>
<p>When your Asp.Net pages are precompiled for release to the production server, references to the code behind are replaced with references to the compiled DLLs which have the <code>App_Web_XXXX</code> name.</p>
| <p>We recently had this issue materialise overnight for one of our precompiled sites. Turns out our server's anti-virus software was silently quarantining one of the compiled DLL files. (apparently my code resembled an update hijacker... charming)</p>
<p>Slightly off-the-wall cause for this problem, but hopefully it helps someone else in future.</p>
| 37,836 |
<p>I am getting an 403 access forbidden when attempting to open a page under a vhost where the document root is sitting on a different drive than where apache is sitting. I installed using the apachefriends release. This is my httpd-vhosts.conf file: </p>
<p><pre><code>
NameVirtualHost 127.0.0.1</p>
<p><VirtualHost 127.0.0.1>
ServerName foo.localhost
DocumentRoot "C:/xampp/htdocs/foo/public"
</VirtualHost></p>
<p><VirtualHost 127.0.0.1>
ServerName bar.localhost
DocumentRoot "F:/bar/public"
</VirtualHost>
</pre></code></p>
<p>When opening bar.localhost in my browser, Apache is giving me 403 Access Forbidden. I tried setting lots of different access rights, even full rights to everyone, but nothing I tried helped.</p>
<p>Edit: Thanks! For future reference, add 'Options indexes' within to show directory indexes.</p>
| <p>You did not need</p>
<pre><code>Options Indexes FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order Allow,Deny
Allow from all
Require all granted
</code></pre>
<p>the only thing what you need is...</p>
<pre><code>Require all granted
</code></pre>
<p>...inside the directory section.</p>
<p>See Apache 2.4 upgrading side:</p>
<p><a href="http://httpd.apache.org/docs/2.4/upgrading.html" rel="noreferrer">http://httpd.apache.org/docs/2.4/upgrading.html</a></p>
| <p>I have fixed it with removing below code from </p>
<p><strong>C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf</strong> file</p>
<pre><code><VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "c:/Apache24/docs/dummy-host.example.com"
ServerName dummy-host.example.com
ServerAlias www.dummy-host.example.com
ErrorLog "logs/dummy-host.example.com-error.log"
CustomLog "logs/dummy-host.example.com-access.log" common
</VirtualHost>
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "c:/Apache24/docs/dummy-host2.example.com"
ServerName dummy-host2.example.com
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>
</code></pre>
<p>And added </p>
<pre><code><VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot "c:/wamp/www"
ServerName localhost
ErrorLog "logs/localhost-error.log"
CustomLog "logs/localhost-access.log" common
</VirtualHost>
</code></pre>
<p>And it has worked like charm</p>
| 11,471 |
<p>I am a programmer at a financial institute. I have recently been told to enforce that all new user id's to have at least one alpha and one numeric. I immediately thought that this was a horrible idea and I would rather not implement it, as I believe this is an anti-feature and of poor user experience. The problem is that I don't have a good case for not implementing this requirement.</p>
<p>Do you think this is a good requirement? </p>
<p>Do you have any good reasons not to do it?</p>
<p>Do you know of any research that I could reference.</p>
<blockquote>
<p>Edit: This is <strong>not</strong> in regards to the password. We already have similar requirements for that, which I am not opposed to.</p>
</blockquote>
| <p>One argument against this is that many usernames / ids in other areas do not require numeric components. It's more likely that users will be better able to remember user ids that they have used elsewhere -- and that is more likely if they do not need to include numerics. </p>
<p>Furthermore, depending on the system, the user ids may work well as defaults when connecting to external systems (ssh behaves this way under unix-like systems). In this case, it is clearly beneficial to have one ID that is shared between systems.</p>
<p>Using the same ID in multiple places improves consistency, which is a well-known aspect of good software interfaces. It's not too difficult to show that the way people interact with a system <em>is</em> a user-interface, and should adhere to (at least some) of the well-known interface guidelines. (Obviously ideas like keyboard shortcuts are meaningless if you're considering the interactions between multiple, possibly unknown, systems, but aspects such as consistency <em>do</em> apply.)</p>
<p><strong>Edit:</strong> I'm assuming that this discussion is about usernames or publicly visible IDs, <em>NOT</em> something that pertains directly to security, such as passwords.</p>
| <p>it's good if it's in their password (as alas, financial companies like to deny you this security right [i'm talking to you american express]).</p>
<p>username, i say no, unless they want to.</p>
| 12,326 |
<p>I have some Perl code that runs fine outside the debugger:</p>
<pre><code>% perl somefile.pl
</code></pre>
<p>but when I run it inside the debugger:</p>
<pre><code>% perl -d somefile.pl
</code></pre>
<p>it behaves differently.</p>
<p>The files in question (there are several) are part of the test suite for a large Perl module (~20K lines of code). The tests do a lot of setup work at compile time and use BEGIN blocks. Here's some minimal reproduction code:</p>
<pre><code>BEGIN
{
package MyEx;
sub new { bless {}, shift }
package main;
eval { die MyEx->new };
if($@)
{
die "Really die" unless($@->isa('MyEx'));
}
}
print "OK\n";
</code></pre>
<p>If you put that in <code>somefile.pl</code> and run it, it prints "OK" as expected. If you run it in the debugger with <code>perl -d somefile.pl</code>, it dies with this error:</p>
<pre><code>Can't call method "isa" without a package or object reference ...
</code></pre>
<p>The upshot is that <code>$@</code> is not an object when the code runs under the debugger. Instead, it's an unblessed scalar containing this string:</p>
<pre><code>" at somefile.pl line 9
eval {...} called at somefile.pl line 9
main::BEGIN() called at somefile.pl line 16
eval {...} called at somefile.pl line 16
"
</code></pre>
<p>(Internal newlines and spacing preserved. That's the literal text, even the "..."s.)</p>
<p>I need code like this to run in the debugger. Using the debugger in the test suite is an important part of my workflow. The module uses exception objects and does a lot of stuff at compile time and expects an object thrown to be an object when caught.</p>
<p>My question (finally) is this: How can I get this to work? Is there a workaround? Is this a bug in the perl debugger module? What's the best way to go about getting this resolved? (I know that's several questions, but they're all related.)</p>
<p>I'm using perl 5.10.0 on Mac OS X 10.5.5.</p>
<hr>
<p>The dieLevel thing suggested by Adam Bellaire looked promising, and indeed something (can't find out what) is setting it to 1 for me. But I set it to 0 using a <code>~/.perldb</code> file and the problem persists. In fact, I set all three of the related settings to 0. My <code>~/.perldb</code> file:</p>
<pre><code>parse_options('dieLevel=0 warnLevel=0 signalLevel=0');
</code></pre>
<p>I confirmed that the settings are in effect by running the <code>o</code> command in the debugger. I see them all set to 0 when I run <code>perl -de 0</code> and also when running the actual <code>somefile.pl</code> file.</p>
<hr>
<p>Thanks, brian. I used <code>perlbug</code> to file a bug (<a href="http://rt.perl.org/rt3/Ticket/Display.html?id=60890" rel="nofollow noreferrer">RT 60890</a>) and I've begun to sprinkle <code>local $SIG{'__DIE__'}</code> in all the appropriate places in my code. (I also noted in the bug that <code>perldoc perldebug</code> still seems to imply that the default <code>dieLevel</code> is 0.)</p>
| <p>This is a problem with perl5db.pl creating <code>__DIE__</code> handlers. If I localize <code>$SIG{__DIE__}</code> in your <code>eval</code>, things work as you expect.</p>
<pre>
eval {
local $SIG{__DIE__};
die MyEx->new
};
</pre>
<p>If you don't do that, you're getting the handler from DB::dbdie, which uses Carp::longmess. That shouldn't happen if dieLevel is 0, but by default it is 1, and it gets set to 1 if it is not defined. This was a patch to perl5db.pl back in 2001, and previously the default had been 0.</p>
<p>You're supposed to turn this off with:</p>
<pre><code>PERLDB_OPT="dieLevel=0" perl5.10.0 -d program
</code></pre>
<p>But there is still a code reference in <code>$SIG{__DIE__}</code> after that, and it's a reference to dbdie. I think this is a bug in handling the global variable <code>$prevdie</code> in perl5db.pl's <code>dieLevel</code>. At the end of that subroutine, there is:</p>
<pre>
# perl5db.pl dieLevel, around line 7777
elsif ($prevdie) {
$SIG{__DIE__} = $prevdie;
print $OUT "Default die handler restored.\n";
}
</pre>
<p>But notice that after restoring <code>$SIG{__DIE__}</code>, it keeps the previous value in <code>$prevdie</code>, meaning whatever is in there leaks to another call. When I run that command line, there are two calls to dieLevel before it handles <code>PERLDB_OPT</code>, so <code>$prevdie</code> is probably dirty.</p>
<p>So, that's as far as I got before I didn't want to think about perl5db.pl anymore.</p>
| <p>Is it possible you have an RC file or environment variable (<code>PERLDB_OPTS</code>) that is modifying the <code>dieLevel</code> option of the debugger? I personally haven't used <code>dieLevel</code> but apparently when it's set to a value greater than zero it can force stack unwinding and "tends to hopelessly destroy any program that takes its exception handling seriously." (<a href="http://www.xav.com/perl/lib/Pod/perldebug.html" rel="nofollow noreferrer">Quote from here</a>).</p>
| 41,705 |
<p>This is a design question and good practice question. How do you structure your Java web development such that a lot of logic is not in the JSP file. Should you use any of the JSP tags for if structures or loops. I see a lot of code where the logic is hard to follow because of poorly designed JSP files. And then when you want to output to a different format like a PDF or XML document, you can't do it because all the logic is in the JSP file.</p>
<p>Are there any tips or practices that you follow for Java Web development.</p>
<p>I am currently using a combination of Spring, Hibernate, Struts...and work with some Servlet code.</p>
<p>There are good practices associated with Java development. Many of us that have worked a while know them. What are some good practices for JSP development.</p>
| <p>The easiest way to avoid placing logic in JSPs is simply to perform all that logic <em>before</em> forwarding a request to a JSP. The only logic you should need to do in a JSP is some basic looping (e.g. for creating HTML table rows), evaluating conditional statements, and data formatting.</p>
<p>All of this can be done without using scriptlet code (Java code) in the JSPs by using JSP tag libraries and EL. The most important tag library is <a href="http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html" rel="noreferrer">JSTL</a>. The JSTL tag library provides most of the logic you should ever need to perform in a view, though you may occasionally also use niche 3rd party tag libraries like <a href="http://displaytag.sourceforge.net/11/" rel="noreferrer">displaytag</a> which can reduce the amount of JSP code you need to write for specific tasks.</p>
| <p>Since you're already using Spring you may want to check out Spring Webflow. I assume you're using Spring form tags, but if not, you should check those out as well. With this combination there should be very little need [if any] to use JSP tags in your view logic.</p>
| 38,404 |
<p>I just recently found out that exchange server2007 will no longer be supporting WMI, namely the service which uses <code>\ROOT\MicrosoftExchangeV2</code>.</p>
<p>The old script I wrote output the ServerName, StorageGroupName, Storename, MailboxDisplayName, Size, TotalItems, DeletedMessageSizeExtended fields to a CSV text file.</p>
<p>How would I go about doing this in PowerShell?</p>
<p>I found you can do this in the 2007 Exchange Management Console running</p>
<pre><code>Get-MailboxStatistics | FT database, DisplayName, ItemCount, TotalItemSize |
Out-File textfile1.txt
</code></pre>
<p>Which generates some of the exchange fields. How do I go about generating the rest of the Active Directory fields like the description and Office fields found in active directory for the same user in the exchange database and output it to a txt file?</p>
| <p>And BTW... depending on how you want to format this information it might be better to write a function which gets the user info, then the Exchange info, and then combines that together into a custom object. PowerShell can then take care of outputting and formatting it for you in various ways. My PowerShell column at <a href="http://technet.microsoft.com/en-us/magazine/dd228985.aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/magazine/dd228985.aspx</a> goes into exactly that - combining information from multiple places into consolidated output. I also have some blog posts on the subject (look up "evolution" in the search, I think) at ConcentratedTech.com. </p>
| <p>The Quest PowerShell cmdlets (quest.com/powershell) are probably the best way. You can use Get-QADUser -IncludeAllProperties to get all of the AD attributes for a user, including Office, Description, etc. Keep in mind that it's AD that has this info, not Exchange.</p>
<p>Exchange cmdlets (Get-Mailbox) will get a certain amount of information for you, but Exchange cmdlets are really focused on just the Exchange bits as much as possible.</p>
| 40,732 |
<p>I want to programatically create an NSTextView. How can I determine the correct frame height so that the view displays one line of text in the current default font?</p>
| <p>The NSFont class has a method that can give you the size of a rectangle that would enclose a specific attributed string. Get the font used by your text view, create a string that serves as a reasonable example of what will be in the text view, and use that to inform your frame height. (The frame height will need to be some number of points larger than the actual rectangle the string would be displayed in.)</p>
<p>Alternately, you can get the various metrics from the font and attempt to calculate a reasonable frame from that. That might or might not work; for example, a font like Apple Chancery has a huge amount of variation depending on the glyphs that are being rendered, where they are in a word, and so on; I don't know that you can calculate what the needed size would be in advance without knowing exactly what you were going to render.</p>
| <p>It would be more normal to be using an NSTextField than an NSTextView for a single line of text.</p>
<p>With NSTextField, just do the following:</p>
<pre><code>[textField setFont:myFont];
[textField sizeToFit];
</code></pre>
<p>Oh, and there is no built-in 'current default font'. If an application has such a concept, it needs to track it itself. The font panel doesn't read or write to anything global, it's used to operate on specific text objects.</p>
| 4,525 |
<p>I am looking for lightweight messaging framework in Java. My task is to process events in a SEDA’s manner: I know that some stages of the processing could be completed quickly, and others not, and would like to decouple these stages of processing.</p>
<p>Let’s say I have components A and B and processing engine (be this container or whatever else) invokes component A, which in turn invokes component B. I do not care if execution time of component B will be 2s, but I do care if execution time of component A is below 50ms, for example. Therefore, it seems most reasonable for component A to submit a message to B, which B will process at the desired time.</p>
<p>I am aware of different JMS implementations and Apache ActiveMQ: they are too heavyweight for this. I searched for some lightweight messaging (with really basic features like messages serialization and simplest routing) to no avail.</p>
<p>Do you have anything to recommend in this issue?</p>
| <p>Do you need any kind of persistence (e.g. if your JVM dies in between processing thousands of messages) and do you need messages to traverse to any other JVMs?</p>
<p>If its all in a single JVM and you don't need to worry about transactions, recovery or message loss if a JVM dies - then as Chris says above, Executors are fine.</p>
<p>ActiveMQ is pretty lightweight; you can use it in a single JVM only with no persistence if you want to; you can then enable transactions / persistence / recovery / remoting (working with multiple JVMs) as and when you need it. But if you need none of these things then its overkill - just use Executors.</p>
<p>Incidentally another option if you are not sure which steps might need persistence/reliability or load balancing to multiple JVMs would be to <a href="http://activemq.apache.org/camel/hiding-middleware.html" rel="noreferrer">hide the use of middleware completely</a> so you can switch between in memory SEDA queues with executors to JMS/ActiveMQ as and when you need to.</p>
<p>e.g. it might be that some steps need to be reliable & recoverable (so needing some kind of persistence) and other times you don't.</p>
| <p>For help to somebody else read this thread:<br>
One of the lightest messaging framework is <a href="https://github.com/bennidi/mbassador" rel="nofollow">Mbasseder</a>.
MBassador is a very light-weight message (event) bus implementation following the publish subscribe pattern. It is designed for ease of use and aims to be feature rich and extensible while preserving resource efficiency and performance.<br>
The core of MBassador's high performance is a specialized data structure that minimizes lock contention such that performance degradation of concurrent access is minimal.<br>
Features: Declarative listener definition via annotations, sync and/or async event delivery, weak-references, message filtering</p>
| 25,986 |
<p>I'm really beginning to understand what people mean when they say that C++'s error messages are pretty terrible in regards to templates. I've seen horrendously long errors for things as simple as a function not matching its prototype.</p>
<p>Are there any tricks to deciphering these errors?</p>
<p>EDIT: I'm using both gcc and MSVC. They both seem to be pretty terrible.</p>
| <p>You can try the following tool to make things more sane:</p>
<p><a href="http://www.bdsoft.com/tools/stlfilt.html" rel="noreferrer">http://www.bdsoft.com/tools/stlfilt.html</a></p>
| <p>Some compilers give better messages than others. What compiler are you using? Having said that, they are all pretty bad. C++0X will fix most of this problem (see <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Concepts" rel="nofollow noreferrer">concepts</a>), but the standard won't be released until 2009, and broad support will probably be even later than that :-(</p>
| 7,033 |
<p>I have a problem with an object I have created that looks something like this:</p>
<pre><code>var myObject = {
AddChildRowEvents: function(row, p2) {
if(document.attachEvent) {
row.attachEvent('onclick', function(){this.DoSomething();});
} else {
row.addEventListener('click', function(){this.DoSomething();}, false);
}
},
DoSomething: function() {
this.SomethingElse(); //<-- Error here, object 'this' does not support this method.
}
}
</code></pre>
<p>The problem is that when I am inside the 'DoSomething' function, 'this' does not refer to 'myObject' what am I doing wrong?</p>
| <p>WHen the function is called, "this" refers to row. If you want to have the object, you can do it something like this:
]</p>
<pre><code>AddChildRowEvents: function(row, p2) {
var theObj = this;
if(document.attachEvent) {
row.attachEvent('onclick', function(){theObj.DoSomething();});
} else {
row.addEventListener('click', function(){theObj.DoSomething();}, false);
}
},
</code></pre>
<p>When the function is called, it has access to the variable theOBj which was in scope when the function was defined.</p>
| <p>This is a common issue with closures. To resolve it try something like this:</p>
<pre><code>var myObject = {
AddChildRowEvents: function(row, p2) {
var self = this;
if(document.attachEvent) {
row.attachEvent('onclick', function(){this.DoSomething(self);});
} else {
row.addEventListener('click', function(){this.DoSomething(self);}, false);
}
},
DoSomething: function(self) {
self.SomethingElse();
}
}
</code></pre>
| 45,024 |
<p>How would you configure/handle extraneous/optional URLs entities (aliases, maybe)?</p>
<p>SO is a good example:</p>
<ul>
<li>stackoverflow.com/questions/99999999/</li>
<li>stackoverflow.com/questions/99999999/<strong>question-goes-here</strong> (bad example, but I couldn't think of better)</li>
</ul>
<p>Amazon URLs are even more confusing (e.g., the <a href="https://rads.stackoverflow.com/amzn/click/com/B000FI73MA" rel="nofollow noreferrer" rel="nofollow noreferrer">Kindle</a>)</p>
<ul>
<li>amazon.com/gp/product/B000FI73MA/</li>
<li>amazon.com/<strong>Kindle-Amazons-Wireless-Reading-Device</strong>/dp/B000FI73MA/</li>
</ul>
<p>[<strong>EDIT</strong>] This probably isn't the best plan-of-action, but I'm really asking this in general vs. for any single server.</p>
| <p>This technique is commonly known as url rewriting. If you are looking out for a solution in IIS, you can use <strong><a href="http://www.isapirewrite.com/" rel="nofollow noreferrer">ISAPI rewrite</a></strong>, which is quite similar to <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html" rel="nofollow noreferrer"><strong>mod_rewrite</strong></a> for apache. Or else, you can go for <strong><a href="http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx" rel="nofollow noreferrer">ASP.Net MVC routing</a></strong> mechanism.</p>
| <p>That's a task for your web app, not your web server.</p>
<p>On URL=>file mappings, like PHP (or static webservers) it's tricky; but on MVC frameworks it's quite natural, even on PHP MVC frameworks.</p>
| 21,718 |
<p>Considering such code:</p>
<pre><code>class ToBeTested {
public:
void doForEach() {
for (vector<Contained>::iterator it = m_contained.begin(); it != m_contained.end(); it++) {
doOnce(*it);
doTwice(*it);
doTwice(*it);
}
}
void doOnce(Contained & c) {
// do something
}
void doTwice(Contained & c) {
// do something
}
// other methods
private:
vector<Contained> m_contained;
}
</code></pre>
<p>I want to test that if I fill vector with 3 values my functions will be called in proper order and quantity. For example my test can look something like this:</p>
<pre><code>tobeTested.AddContained(one);
tobeTested.AddContained(two);
tobeTested.AddContained(three);
BEGIN_PROC_TEST()
SHOULD_BE_CALLED(doOnce, 1)
SHOULD_BE_CALLED(doTwice, 2)
SHOULD_BE_CALLED(doOnce, 1)
SHOULD_BE_CALLED(doTwice, 2)
SHOULD_BE_CALLED(doOnce, 1)
SHOULD_BE_CALLED(doTwice, 2)
tobeTested.doForEach()
END_PROC_TEST()
</code></pre>
<p>How do you recommend to test this? Are there any means to do this with CppUnit or GoogleTest frameworks? Maybe some other unit test framework allow to perform such tests?</p>
<p>I understand that probably this is impossible without calling any debug functions from these functions, but at least can it be done automatically in some test framework. I don't like to scan trace logs and check their correctness.</p>
<p><em>UPD</em>: I'm trying to check not only the <strong>state</strong> of an objects, but also the <strong>execution order</strong> to avoid performance issues on the earliest possible stage (and in general I want to know that my code is executed exactly as I expected).</p>
| <p>You should be able to use any good mocking framework to verify that calls to a collaborating object are done in a specific order.</p>
<p>However, you don't generally test that one method makes some calls to other methods on the same class... why would you?</p>
<p>Generally, when you're testing a class, you only care about testing its publicly visible state. If you test
anything else, your tests will prevent you from refactoring later.</p>
<p>I could provide more help, but I don't think your example is consistent (Where is the implementation for the AddContained method?).</p>
| <p>Some mocking frameworks allow you to set up ordered expectations, which lets you say exactly which function calls you expect in a certain order. For example, <a href="http://www.ayende.com/projects/rhino-mocks.aspx" rel="nofollow noreferrer">RhinoMocks</a> for C# allows this.</p>
<p>I am not a C++ coder so I'm not aware of what's available for C++, but that's one type of tool that might allow what you're trying to do.</p>
| 10,415 |
<p>How can I display a calendar control (date picker) in Oracle forms 9/10?</p>
| <p>This does seem to be possible in the version of Qt Designer 4.5.2, but it <em>can't</em> be done from the Signal/Slot Editor dock-widget in the main window.</p>
<p>This is what worked for me</p>
<ol>
<li>Switch to <a href="http://doc.qt.io/qt-4.8/designer-connection-mode.html" rel="noreferrer">Edit Signals/Slots</a> mode (F4)</li>
<li>Drag and drop from the widget which is to emit the signal, to the widget which is to receive the signal.</li>
<li>A <em>Configure Connection</em> dialog appears, showing the signals for the emitting widget, and the slots for the receiving widget. Click <em>Edit...</em> below the slots column on the right.</li>
<li>A <em>Signals/Slots of ReceivingWidget</em> dialog appears. In here its is possible to click the plus icon beneath slots to add a new slot of any name.</li>
<li>You can then go back and connect to your new slot in the <em>Configure Connection</em> dialog, or indeed in the Signal/Slot Editor dockwidget back in the main window.</li>
</ol>
<p>Caveat: I'm using PyQt, and I've only tried to use slots added in this way from Python, not from C++, so your mileage may vary...</p>
| <p>click the widget by right button</p>
<p>promote the widget into a class you defined</p>
<p>click the widget by right button again</p>
<p>you will see that signal and slot is editable</p>
| 20,005 |
<p>I switched to the dvorak keyboard layout about a year ago. I now use <a href="https://en.wikipedia.org/wiki/Dvorak_Simplified_Keyboard" rel="nofollow noreferrer">dvorak</a> full-time at work and at home.</p>
<p>Recently, I went on vacation to Peru and found myself in quite a conundrum. Internet cafes were qwerty-only (and Spanish qwerty, at that). I was stuck with a hunt-and-peck routine that grew old fairly quickly.</p>
<p>That said, is it possible to be "fluent" in both qwerty and dvorak at the same time? If not, are there any good solutions to the situation I found myself in?</p>
| <h2>Web</h2>
<p>For your situation of being at a public computer that you cannot switch the keyboard layout on, you can go to this website:
<a href="http://www.dvzine.org/type/DVconverter.html" rel="noreferrer">http://www.dvzine.org/type/DVconverter.html</a></p>
<p>Use this to translate your typing and then use copy paste. I found this very useful when I was out of the country and had to write a bunch of emails at public computers.</p>
<h2>USB Drive</h2>
<p>Put this <a href="http://typedvorak.com/2007/07/22/the-best-way-to-use-dvorak-on-windows-dvassist/" rel="noreferrer">Dvorak Utility</a> on your USB drive. </p>
<p>Run this app and it will put a icon in the system tray on windows. This icon will switch the computer between the two keyboard layouts and it works. (If you have tried switching back and forth from dvorak to qwerty you will know what I mean. Windows does the worst job of this one bit of functionality.)</p>
| <p>I've never used a public computer, but carry a keyboard and(/or, if you are good enough) just change the settings on the machine.</p>
| 3,261 |
<p>I'm about to be forced to write a script to download some number of files under Windows XP. The machines the script will be run at are all behind a proxy, and the proxy settings are entered into the IE configuration.</p>
<p>What came to my mind was either to somehow call IE from the command line, and using its configuration download files I'd need. Is it even possible using some shell-techniques? </p>
<p>Other option would be to use <code>wget</code> under Win, but I'd need to pass the proxy-settings to it. How to recover those settings from IE configuration?</p>
| <p>Create radio</p>
<pre><code>Radio radio = new Radio();
radio.setBoxLabel("Si");
radio.setValue(true);
radio.setValueAttribute("true");
Radio radio2 = new Radio();
radio2.setBoxLabel("No");
radio2.setValueAttribute("false");
RadioGroup radioGroup = new RadioGroup();
radioGroup.setFieldLabel("Afecto");
radioGroup.add(radio);
radioGroup.add(radio2);
</code></pre>
<p>get selected value</p>
<pre><code>Boolean b = Boolean.parseBoolean(radioGroup.getValue().getValueAttribute());
</code></pre>
| <p>Using radioButton.setItemId() and getItemId() resolve it.</p>
| 46,453 |
<p>If there a way to protect against concurrent modifications of the same data base entry by two or more users?</p>
<p>It would be acceptable to show an error message to the user performing the second commit/save operation, but data should not be silently overwritten.</p>
<p>I think locking the entry is not an option, as a user might use the "Back" button or simply close his browser, leaving the lock for ever.</p>
| <p>This is how I do optimistic locking in Django:</p>
<pre><code>updated = Entry.objects.filter(Q(id=e.id) && Q(version=e.version))\
.update(updated_field=new_value, version=e.version+1)
if not updated:
raise ConcurrentModificationException()
</code></pre>
<p>The code listed above can be implemented as a method in <a href="https://docs.djangoproject.com/en/1.7/topics/db/managers/#id2" rel="noreferrer">Custom Manager</a>. </p>
<p>I am making the following assumptions:</p>
<ul>
<li>filter().update() will result in a single database query because filter is lazy</li>
<li>a database query is atomic</li>
</ul>
<p>These assumptions are enough to ensure that no one else has updated the entry before. If multiple rows are updated this way you should use transactions.</p>
<p><strong>WARNING</strong> <a href="https://docs.djangoproject.com/en/1.7/topics/db/queries/#updating-multiple-objects-at-once" rel="noreferrer">Django Doc</a>:</p>
<blockquote>
<p>Be aware that the update() method is
converted directly to an SQL
statement. It is a bulk operation for
direct updates. It doesn't run any
save() methods on your models, or emit
the pre_save or post_save signals</p>
</blockquote>
| <p>To be safe the database needs to support <a href="http://en.wikipedia.org/wiki/Database_transaction" rel="nofollow noreferrer">transactions</a>. </p>
<p>If the fields is "free-form" e.g. text etc. and you need to allow several users to be able to edit the same fields (you can't have single user ownership to the data), you could store the original data in a variable.
When the user committs, check if the input data has changed from the original data (if not, you don't need to bother the DB by rewriting old data),
if the original data compared to the current data in the db is the same you can save, if it has changed you can show the user the difference and ask the user what to do. </p>
<p>If the fields is numbers e.g. account balance, number of items in a store etc., you can handle it more automatically if you calculate the difference between the original value (stored when the user started filling out the form) and the new value you can start a transaction read the current value and add the difference, then end transaction. If you can't have negative values, you should abort the transaction if the result is negative, and tell the user.</p>
<p>I don't know django, so I can't give you teh cod3s.. ;)</p>
| 41,398 |
<p>I have only been working with sharepoint for three months but right from the start I was told that the SharePoint content db was off limits as MS could change the schema at any time. The recommended route is to use the object model, and in most case I kind of understands that.</p>
<p>Now I need to join some lists in order to present the content grouped by some specific fields. Rather then iterating through each and every list I would prefer to link our own db which resides on the same DB server, to the WSS content DB and just create a view on the tables. This view should be on our DB in order to make such that we don't change ANYTHING on the WSS content DB.</p>
<p>Am I on the route to eternal damnation or not?</p>
| <p>Yes, you are. Microsoft is <em>very</em> clear that any modifications to the SharePoint tables renders you unsupportable. </p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb861829.aspx" rel="nofollow noreferrer">Direct modification of the SharePoint database or its data is not recommended because it puts the environment in an unsupported state.</a></p>
<p>Now, creating a link on your own DB which queries the SharePoint DB is shaky ground. Personally I'd do one of two things:</p>
<ul>
<li>If this is a mission-critical application, run it past MSFT support. </li>
<li>If it is anything else, just make sure that your view is not locking the DB during querying. </li>
</ul>
<p>A better strategy might be to iterate the lists and sync it to your own table so you can do whatever kind of data-mining you'd like - if you don't mind whatever lag time your sync routine would need.</p>
| <p>Well, if the joins you need to do are pretty simple, defining a <a href="http://office.microsoft.com/en-us/sharepointdesigner/HA101154041033.aspx" rel="nofollow noreferrer">linked data source</a> in SharePoint Designer may work for you</p>
| 34,412 |
<p>I'm translating a library written in C++ to C#, and the keyword 'union' exists once. In a struct.</p>
<p>What's the correct way of translating it into C#? And what does it do? It looks something like this;</p>
<pre><code>struct Foo {
float bar;
union {
int killroy;
float fubar;
} as;
}
</code></pre>
| <p>You can use explicit field layouts for that:</p>
<pre><code>[StructLayout(LayoutKind.Explicit)]
public struct SampleUnion
{
[FieldOffset(0)] public float bar;
[FieldOffset(4)] public int killroy;
[FieldOffset(4)] public float fubar;
}
</code></pre>
<p>Untested. The idea is that two variables have the same position in your struct. You can of course only use one of them.</p>
<p>More informations about unions in <a href="http://msdn.microsoft.com/en-us/library/aa288471(VS.71).aspx" rel="noreferrer">struct tutorial</a></p>
| <pre><code>public class Foo
{
public float bar;
public int killroy;
public float fubar
{
get{ return (float)killroy;}
set{ killroy = (int)value;}
}
}
</code></pre>
| 15,422 |
<p>I need to write a 'simple' util to convert from ASCII to EBCDIC? </p>
<p>The Ascii is coming from Java, Web and going to an AS400. I've had a google around, can't seem to find a easy solution (maybe coz there isn't one :( ). I was hoping for an opensource util or paid for util that has already been written. </p>
<p>Like this maybe? </p>
<pre><code>Converter.convertToAscii(String textFromAS400)
Converter.convertToEBCDIC(String textFromJava)
</code></pre>
<p>Thanks, </p>
<p>Scott</p>
| <p><a href="http://jt400.sourceforge.net/" rel="noreferrer">JTOpen</a>, IBM's open source version of their Java toolbox has a collection of classes to access AS/400 objects, including a FileReader and FileWriter to access native AS400 text files. That may be easier to use then writing your own conversion classes.</p>
<p>From the JTOpen homepage:</p>
<blockquote>
<p>Here are just a few of the many i5/OS and OS/400 resources you can access using JTOpen:</p>
<ul>
<li>Database -- JDBC (SQL) and record-level access (DDM)</li>
<li>Integrated File System</li>
<li>Program calls</li>
<li>Commands</li>
<li>Data queues</li>
<li>Data areas</li>
<li>Print/spool resources</li>
<li>Product and PTF information</li>
<li>Jobs and job logs</li>
<li>Messages, message queues, message files</li>
<li>Users and groups</li>
<li>User spaces</li>
<li>System values</li>
<li>System status</li>
</ul>
</blockquote>
| <p>It should be fairly simple to write a map for the EBCDIC character set, and one for the ASCII character set, and in each return the character representation of the other. Then just loop over the string to translate, and look up each character in the map and append it to an output string.</p>
<p>I don't know if there are any converter's publicly available, but it shouldn't take more than an hour or so to write one.</p>
| 48,122 |
<p>I am trying to use JMockit's code coverage abilities. Using the JVM parameter</p>
<pre><code>-javaagent:jmockit.jar=coverage=.*MyClass.java:html::
</code></pre>
<p>I am able to run my tests (jmockit.jar and coverage.jar are on the classpath), unfortunately my log file says:</p>
<pre><code>Loaded external tool: mockit.coverage.CodeCoverage=.*MyClass.java:html::
Loaded external tool: mockit.integration.junit3.JUnitTestCaseDecorator
Loaded external tool: mockit.integration.junit4.JUnit4ClassRunnerDecorator
Exception in thread "Thread-0" java.lang.NoClassDefFoundError
at mockit.coverage.CodeCoverage$OutputFileGenerator.run(CodeCoverage.java:56)
</code></pre>
<p>...and no coverage file is generated. Has anyone gotten JMockit Coverage to work? If so, any thoughts as to what is causing this error? Thanks...</p>
<p><strong>Answer</strong>: <s>I needed to add coverage to the bootstrap entries rather than only the user entries (in the Eclipse run configuration)</s></p>
<p><strong>Actual Answer</strong> The actual answer is that I was running the test with JUnit 3, but the coverage needs JUnit 4. That fixed things, and I didn't have to add any bootstrap entries.</p>
| <p>I was running the test with JUnit 3, but the coverage needs JUnit 4. That fixed things, and I didn't have to add any bootstrap entries.</p>
| <p>Random guess... Is coverage.jar on the classpath that jmockit uses - it might be a different one?</p>
| 25,557 |
<p>I'm working with an ASP.net 2.0 GridView control that is bound to the results of a sql query, so it looks something like this:</p>
<pre><code><asp:GridView ID="MySitesGridView" runat="server" AutoGenerateColumns="False" DataSourceID="InventoryDB" AllowSorting="True" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCommand="GridView1_RowCommand" OnRowDataBound="siteRowDataBound">
<Columns>
<asp:BoundField DataField="Server" HeaderText="Server"/>
<asp:BoundField DataField="Customer" HeaderText="Customer" SortExpression="Customer" />
<asp:BoundField DataField="PublicIP" HeaderText="Site Address" DataFormatString="&lt;a href='http://{0}/foo'&gt;Go To Site&lt;/a&gt;" />
</Columns>
</asp:GridView>
</code></pre>
<p>As you can see, I'm displaying links with addresses in one of the columns (the one bound to the PublicIP field) using the format string:</p>
<pre><code>&lt;a href='http://{0}/foo'&gt;Go To Site&lt;/a&gt;
</code></pre>
<p>Here's the problem: I need to use one of the <em>other</em> columns from the result set as well as the PublicIP column in my links, but I don't know how to make that available to my format string. I essentially need that column bound to two columns from the result set. To clarify, I need something like:</p>
<pre><code>&lt;a href='http://{0}/{1}'&gt;Go To Site&lt;/a&gt;
</code></pre>
<p>Where {1} is the value of my other column. Is there any way to accomplish this cleanly (even if it doesn't use format strings)? I've looked into using TemplateFields as well, but can see no easy way to do it with them either.</p>
| <p>TemplateFields are the way to go.</p>
<p>I usually prefer to have a private string function in the Page which I pass several object variables, and calculate the resulting string.</p>
<pre><code><a href="<%# CalculateUrl(Eval("PublicIP"), Eval("Customer")) %>">site</a>
</code></pre>
<p>and in the code-behind:</p>
<pre><code>private string CalculateUrl(object PublicIP, object Customer)
{
if (PublicIP==null || PublicIP==DBNull.Value)
return "";
if (Customer==null || Customer==DBNull.Value)
return "";
return "http://" + PublicIP.ToString() + "/" + Customer.ToString();
}
</code></pre>
<p>Advantage is that the function can be shared in a common parent class, or as a static public function of a utility class.</p>
| <p>If you want an actual link, you can also use a HyperLinkField, which has a property DataNavigateUrlFields (plural) that you can use to specify multiple fields. You then set DataNavigateUrlFormatString to something containing {0}, {1} etc. This will become your link. For the link text, you use DataTextFormatString and DataTextField (singular, don't ask me why). This is probably a bit easier than a TemplateField (although less flexible).</p>
| 35,747 |
<p>I thought I have already had and fixed every problem one could possibly have with a 3D printer. Guess I was wrong.</p>
<p>I haven't used my Creality CR-10 for a few weeks, everything was working the last time I tried. Today I wanted to print something minor and the printer just randomly paused a few times in the middle of the print.</p>
<p>To be exact, it seems that after a few G-code commands have been executed the printer just freezes for like 10 seconds and then continues like nothing happened. This occurred a few times and every time the nozzle is melting the surrounding plastic and extruding a little which ruins the print.</p>
<p>I have tried:</p>
<ul>
<li>Print from SD Card</li>
<li>Print from Laptop via USB connection to Ultimaker Cura</li>
<li>Print different models at different settings</li>
</ul>
<p>My theory is that either there is a core problem with how Ultimaker Cura exports the G-code files or something is wrong with the printer software. I thought that maybe re-installing the firmware might fix it but I heard that that is a risky process. What do I do?</p>
| <p><strong>Edit: The z-hop problem has been fixed in Cura 4.2.</strong></p>
<hr>
<p>This is a known issue with Cura 4.1 when z-hop is enabled.</p>
<p>If you touch the z-axis motor frame while it is apparently stationary, you may feel it is actually moving.</p>
<p>The solution is to set a value (I used something like 250 in conjunction with an Ender 3) for the "Maximum Z Speed".</p>
<p>First you need to get the setting to be visible, so go to the "Settings" menu and choose "Configure setting visibility...":</p>
<p><a href="https://i.stack.imgur.com/LrN1v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LrN1v.png" alt="Configure setting visibility dialog"></a></p>
<p>Then in the "Print settings" panel:</p>
<p><a href="https://i.stack.imgur.com/Jzm3u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jzm3u.png" alt="Print settings panel"></a></p>
<p>The full story is available on GitHub at <a href="https://github.com/Ultimaker/Cura/issues/5753" rel="nofollow noreferrer">[4.1 - current master branch] Z feed rates #5753</a>.</p>
| <p>I experienced the same with 4.1. Everything went back to normal after going back to 4.0 despite that all settings were identical as far as I could see. I compared the two g-code files using a simple file comparison tool. They were very different, hardly anything was the same. I still need to figure out what they mean. The model and thus the g-code files are far to large to go through. So, I will have to use a simple and small model to start unraveling what those differences mean.</p>
| 1,351 |
<p>I have an application that sends the customer to another site to handle the payments. The other site, outside of the customer, calls a page on our server to let us know what the status is of the payment. The called page checks the parameters that are given by the payment application and checks to see whether the transaction is known to us. It then updates the database to reflect the status. This is all done without any interaction with the customer.</p>
<p>I have personally chosen to implement this functionality as a JSP since it is easier to just drop a file in the file system than to compile and package the file and then to add an entry into a configuration file.</p>
<p><p>Considering the functionality of the page I would presume that a servlet would be the preferred option. The question(s) are:
<li>Is my presumption correct?</li>
<li>Is there a real reason to use a servlet over a JSP?</li>
<li>What are those reasons?</li></p>
| <p>A JSP is compiled to a servlet the first time it is run. That means that there's no real runtime difference between them. </p>
<p>However, most have a tradition to use servlets for controllers and JSPs for views. Since controllers are just java classes you can get full tool support (code completion etc.) from all IDEs. That gives better quality and faster development times compared to JSPs. Some more advanced IDE's (IntelliJ IDEA springs to mind) have great JSP support, rendering that argument obsolete.</p>
<p>If you're making your own framework or just making it with simple JSPs, then you should feel free to continue to use JSPs. There's no performance difference and if you feel JSPs are easier to write, then by all means continue.</p>
| <p>Yeah, this should be a servlet. A JSP may be easier to develop, but a servlet will be easier to maintain. Just imagine having to fix some random bug in 6 months and trying to remember how it worked.</p>
| 12,709 |
<p>I'm accessing an Ubuntu machine using PuTTY, and using gcc.</p>
<p>The default <code>LANG</code> environment variable on this machine is set to <code>en_NZ.UTF-8</code>, which causes GCC to think PuTTY is capable of displaying UTF-8 text, which it doesn't seem to be.
Maybe it's my font, I don't know - it does this:</p>
<pre><code>foo.c:1: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â at end of input
</code></pre>
<p>If I set it with <code>export LANG=en_NZ</code>, then this causes GCC to behave correctly, I get:</p>
<pre><code>foo.c:1: error: expected '=', ',', ';', 'asm' or '__attribute__' at end of input
</code></pre>
<p>but this then causes everything else to go wrong. For example</p>
<pre><code>man foo
man: can't set the locale; make sure $LC_* and $LANG are correct
</code></pre>
<p>I've trawled Google and I can't for the life of me find out what I have to put in there for it to just use ASCII. <code>en_NZ.ASCII</code> doesn't work, nor do any of the other things I can find.</p>
<p>Thanks</p>
| <p><code>LANG=en_NZ</code> is correct. However, you must make locale files for <code>en_NZ</code>.</p>
<p>For Ubuntu, edit <code>/var/lib/locales/supported.d/local</code> and add <code>en_NZ ISO-8859-1</code> to the file. If your system is another distribution (including Debian), the location will be different. Look at <code>/usr/sbin/locale-gen</code> and see where it stores this info.</p>
<p>Afterwards, run <code>locale-gen</code> to create the <code>en_NZ</code> locale file. Hope this helps!</p>
| <p>For Debian 5.0 Lenny:</p>
<pre><code>aptitude install locales
</code></pre>
<p>If that's already installed:</p>
<pre><code>dpkg-reconfigure locales
</code></pre>
| 4,669 |
<p>The following C# code takes 5 minutes to run:</p>
<pre><code>int i = 1;
string fraction = "";
while (fraction.Length < 1000000)
{
fraction += i.ToString();
i++;
}
</code></pre>
<p>"Optimising it" like this causes it to run in 1.5 seconds:</p>
<pre><code>int i = 1;
string fraction = "";
while (fraction.Length < 1000000)
{
// concatenating strings is much faster for small strings
string tmp = "";
for (int j = 0; j < 1000; j++)
{
tmp += i.ToString();
i++;
}
fraction += tmp;
}
</code></pre>
<p><strong>EDIT:</strong> Some people suggested using <code>StringBuilder</code>, which is an excellent suggestion also, and this comes out at 0.06s:</p>
<pre><code>int i = 1;
StringBuilder fraction = new StringBuilder();
while (fraction.Length < 1000000)
{
fraction.Append(i);
i++;
}
</code></pre>
<p>Playing around to find the optimum value of <code>j</code> is a topic for another time, but why exactly does this non-obvious optimisation work so well? Also, on a related topic, I've heard it said that you should never use the <code>+</code> operator with strings, in favour of <code>string.Format()</code>, is this true?</p>
| <p>You will probably see that the first 1000 chars will take almost no time opposed to the last 1000 chars. </p>
<p>I would assume that the time-consuming part is the actual copying of the large string into a new memory-area every time you add a char that is the tough work for your computer.</p>
<p>Your optimization can easily be compared to what you usually do with streams, you use a buffer. Larger chunks will usually result in better performance until you hit the critical size where it no longer makes any difference, and starts to be a downside when your handling small amounts of data.</p>
<p>If you however would have defined a char-array with the appropriate size from the beginning, it would probably be blazing fast, because then it won't have to copy it over and over again.</p>
| <p>Answer to the modified queston ("why does this non-obvious optimization work so well" and "is it true you shouldn't use + operator on strings"):</p>
<p>I'm not sure which non-obvious optimization you are talking about. But the answer to the second question, I think, covers all of the bases.</p>
<p>The way strings work in C# is that they are allocated as fixed-length, and cannot be changed. This means that any time you try to change the length of the string, an entire new string is created and the old string is copied in up to the proper length. This is obviously a slow process. When you use String.Format it internally uses a StringBuilder to create the string.</p>
<p>StringBuilders work by using a memory buffer which is more intelligently allocated than fixed-length strings, and thus performs significantly better in most situations. I'm not sure on the details of StringBuilder internally, so you'll have to ask a new question for that. I can speculate it either doesn't reallocate the old portions of the string (instead creating a linked list internally and only actually allocating the final output when needed by ToString) or it reallocates with exponential growth (when it runs out of memory, it allocates twice as much the next time, thus for a 2GB string it would only need to reallocate about 30 times).</p>
<p>Your example with the nested loops grows linearly. it takes a small string and grows that up to 1000, and then tacks that 1000 on to the larger string in one large operation. As the large string gets really large, the copy that results from creating a new string gets to take a long time. When you reduce the amount of times this is done (by instead resizing a smaller string more often instead) you increase the speed. Of course, StringBuilder is even smarter about allocating memory, and thus is much faster.</p>
| 35,772 |
<p>Given a pointer to some variable.. is there a way to check whether it was statically or dynamically allocated?? </p>
| <p>Quoting from your comment:</p>
<blockquote>
<p>im making a method that will basically get rid of a struct. it has a data member which is a pointer to something that may or may not be malloced.. depending on which one, i would like to free it</p>
</blockquote>
<p>The correct way is to add <em>another</em> member to the struct: a pointer to a deallocation function.</p>
<p>It is not just static versus dynamic allocation. There are <em>several</em> possible allocators, of which <code>malloc()</code> is just one.</p>
<p>On Unix-like systems, it could be:</p>
<ul>
<li>A static variable</li>
<li>On the stack</li>
<li>On the stack but dynamically allocated (i.e. <code>alloca()</code>)</li>
<li>On the heap, allocated with <code>malloc()</code></li>
<li>On the heap, allocated with <code>new</code></li>
<li>On the heap, in the middle of an array allocated with <code>new[]</code></li>
<li>On the heap, within a struct allocated with <code>malloc()</code></li>
<li>On the heap, within a base class of an object allocated with <code>new</code></li>
<li>Allocated with <code>mmap</code></li>
<li>Allocated with a custom allocator</li>
<li>Many more options, including several combinations and variations of the above</li>
</ul>
<p>On Windows, you also have several runtimes, <code>LocalAlloc</code>, <code>GlobalAlloc</code>, <code>HeapAlloc</code> (with several heaps which you can create easily), and so on.</p>
<p>You must always release memory with the correct release function for the allocator you used. So, either the part of the program responsible for allocating the memory should also free the memory, or you must pass the correct release function (or a wrapper around it) to the code which will free the memory.</p>
<p>You can also avoid the whole issue by either requiring the pointer to always be allocated with a specific allocator or by providing the allocator yourself (in the form of a function to allocate the memory and possibly a function to release it). If you provide the allocator yourself, you can even use tricks (like tagged pointers) to allow one to also use static allocation (but I will not go into the details of this approach here).</p>
<p><a href="http://en.wikipedia.org/wiki/Raymond_Chen" rel="nofollow noreferrer">Raymond Chen</a> has a blog post about it (Windows-centric, but the concepts are the same everywhere): <a href="https://devblogs.microsoft.com/oldnewthing/20060915-04/?p=29723" rel="nofollow noreferrer">Allocating and freeing memory across module boundaries</a></p>
| <p>1.) Obtain a map file for the code u have.</p>
<p>2.) The underlying process/hardware target platform should have a memory map file which typically indicates - starting address of memory(stack, heap, global0, size of that block, read-write attributes of that memory block.</p>
<p>3.) After getting the address of the object(pointer variable) from the mao file in 1.) try to see which block that address falls into. u might get some idea.</p>
<p>=AD</p>
| 34,883 |
<p>What does it mean by logical grouping of modules in assembly?
Can anyone please explain how .NET's CLR works with assembly ?</p>
| <p>You can organise modules using Namespaces. With Namespaces you can make one for each logical grouping of modules within your assembly.</p>
<p>So if you have a <strong>Utlity</strong> assembly with some string helpers and some file helpers you could put the string helper modules in a Namespace called <strong>Utility.StringHelper</strong> and the file helper modules in an Namespace called <strong>Utility.FileHelper</strong>.</p>
| <p>A dotNet Assembly is the container for all your executable code. The package that contains the executable code for your program in other words. Your question seems to be confusing a Microsoft term with another term perhaps. Can you clarify your question.</p>
| 49,640 |
<p>I'm building an ASP.Net MVC website. Rather than have everything in one project, I've decided to separate the Web, Model and Controller out into different projects in the same solution, that reference each-other.</p>
<p>The referencing goes like this:</p>
<blockquote>
<p>Web ---[references]---> Controller ---[references]---> Model</p>
</blockquote>
<p>Now I wanted to add 2 custom methods to the HtmlHelper class - they're called "IncludeScript" and "IncludeStyle". They each take a single string parameter, and generate a script or link tag respectively.</p>
<p>I've created an extender class, according to documentation on the web, and written the two methods and compiled the application.</p>
<p>Now, when I go into the Public.Master page (which is my main master-page, and one of the places where I intend to use these methods), I can enter code such as below:</p>
<p><code><%= Html.IncludeScript("\js\jquery.js") %></code></p>
<p>The IntelliSense picks up and IncludeScript method and shows me the syntax just fine. So I'd expect that everything should work.</p>
<p>But it doesn't.</p>
<p>Everything compiles, but as soon as I run the application, I get the following run-time error from line 14 of Default.aspx.cs:</p>
<p><code>c:\\Projects\\PhoneReel\\PhoneReel.Web\\Views\\Shared\\Public.Master(11): error CS0117: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'IncludeScript'</code></p>
<p>Here's the line of code that the error happens on:</p>
<p><code>httpHandler.ProcessRequest(HttpContext.Current);</code></p>
<p>Any ideas what could be going wrong here?</p>
| <p>Check to make sure that the namespace of your extensions is accessible to our view. You need either this in your view:</p>
<pre><code><%@ Import Namespace="MyRootNamespace.NamespaceForMyHtmlHelperExtensions"%>
</code></pre>
<p>or this in your web config namespaces section:</p>
<pre><code><add namespace="MyRootNamespace.NamespaceForMyHtmlHelperExtensions"/>
</code></pre>
| <p>Are you sure the compiler is set to .NET Framework 3.5? This happened to me when I inadvertently set the compiler to .NET Framework 2.0</p>
| 26,710 |
<p>I use Visual SourceSafe with Visual Studio. Every time I work on a project for a while, the directory structure on my harddisk gets messed up.
The latest versions of the files are going to their own nested folder, so I end up with <code>C:\VS2005\Projects\MyProject\MyProject\MyProject\MyProject</code></p>
<p>What is causing this?</p>
| <p>I can't help with your particular problem, but I remember my own pains using SourceSafe just a few years ago.</p>
<p>If you have a choice on the source control system you use, I'd recommend taking a look at other options. There are several good ones to choose from. </p>
<p>I switched to <a href="http://subversion.tigris.org/" rel="nofollow noreferrer">SVN</a> and never looked back. It is light-years better than SourceSafe and setup only takes a few minutes if you use <a href="http://www.visualsvn.com/server/" rel="nofollow noreferrer">visualsvn server</a> (a free product). As for Visual Studio integration, <a href="http://www.visualsvn.com/visualsvn/" rel="nofollow noreferrer">visualsvn client</a> is about $50, or just use <a href="http://ankhsvn.open.collab.net/" rel="nofollow noreferrer">ANKH</a> + <a href="http://tortoisesvn.net/downloads" rel="nofollow noreferrer">Tortoise</a> (both are open source and very good). Bottom line is that the switch doesn't have to cost any money, and the installer packages are quick to get the system running on both the clients and the server.</p>
<p>Hope that helps, and good luck with SourceSafe if you have to keep using it.</p>
<p><strong>Update:</strong> See also, <a href="https://stackoverflow.com/questions/115493/how-do-i-convince-my-team-to-drop-sourcesafe-and-move-to-svn">this thread</a></p>
| <p>What is causing this?</p>
<p>Just the general contra-expectation insanity which is VSS and VS combined I'm afraid. You could spend the time to really get to know VSS and how it thinks of things and how to avoid the quirks and pitfalls, but the thing is such an outdated beast I'd second Robert's asssertion that it's more profitable to get yourself a copy of SVN and VisualSVN and never worry about this again.</p>
| 46,498 |
<p>In static languages like Java you need interfaces because
otherwise the type system just won't let you do certain things.
But in dynamic languages like PHP and Python you just take
advantage of <em>duck-typing</em>.</p>
<p>PHP supports interfaces.
Ruby and Python don't have them.
So you can clearly live happily without them.</p>
<p>I've been mostly doing my work in PHP and have never really
made use of the ability to define interfaces. When I need a
set of classes to implement certain common interface, then
I just describe it in documentation.</p>
<p>So, what do you think? Aren't you better off without using
interfaces in dynamic languages at all?</p>
| <p>I think of it more as a level of convenience. If you have a function which takes a "file-like" object and only calls a read() method on it, then it's inconvenient - even limiting - to force the user to implement some sort of File interface. It's just as easy to check if the object has a read method.</p>
<p>But if your function expects a large set of methods, it's easier to check if the object supports an interface then to check for support of each individual method.</p>
| <p>Stop trying to write Java in a dynamic language.</p>
| 11,702 |
<p>Yes, it sounds crazy....It might be.</p>
<p>The final updatepanel does not appear to trigger anything, it just refreshes the update panels and does not call back to the usercontrol hosting it.</p>
<p>Any ideas?</p>
<p>EDIT: I got it posting back, however the controls inside the final usercontrol have lost their data...I'm thinking its because the main repeater is rebinding on each postback...Not sure where to take this one now.</p>
| <p>I would suggest you start by removing the UpdatePanels at first, and make sure your control orgy is working correctly with postbacks. Once you have that working, try adding the UpdatePanels back in from the bottom up.</p>
| <p>If you set the UpdateMode property to Conditional (default is Always) on both UpdatePanels it should stop the outer UpdatePanel triggering when only the usercontrols updatepanel should have refreshed.</p>
| 5,063 |
<p>I've had this long term issue in not quite understanding how to implement a decent Lucene sort or ranking. Say I have a list of cities and their populations. If someone searches "new" or "london" I want the list of prefix matches ordered by population, and I have that working with a prefix search and an sort by field reversed, where there is a population field, IE New Mexico, New York; or London, Londonderry.</p>
<p>However I also always want the exact matching name to be at the top. So in the case of "London" the list should show "London, London, Londonderry" where the first London is in the UK and the second London is in Connecticut, even if Londonderry has a higher population than London CT.</p>
<p>Does anyone have a single query solution?</p>
| <p>dlamblin,let me see if I get this correctly: You want to make a prefix-based query, and then sort the results by population, and maybe combine the sort order with preference for exact matches.
I suggest you separate the search from the sort and use a CustomSorter for the sorting:
Here's <a href="http://blog.tremend.ro/2007/05/17/a-z-0-9-custom-sorting-in-lucene/" rel="nofollow noreferrer">a blog entry describing a custom sorter</a>.
<a href="https://rads.stackoverflow.com/amzn/click/com/1932394281" rel="nofollow noreferrer" rel="nofollow noreferrer">The classic Lucene book</a> describes this well.</p>
| <p>My current solution is to create an exact searcher and a prefix searcher, both sorted by reverse population, and then copy out all my hits starting from the exact hits, moving to the prefix hits. It makes paging my results slightly more annoying than I think it should be.</p>
<p>Also I used a hash to eliminate duplicates but later changed the prefix searcher into a boolean query of a prefix search (MUST) with an exact search (MUST NOT), to have Lucene remove the duplicates. Though this seemed even more wasteful.</p>
<p><em>Edit</em>: Moved to a comment (since the feature now exists): <a href="https://stackoverflow.com/users/1702/yuval-f">Yuval F</a> Thank you for your blog post ... How would the sort comparator know that the name field "london" exactly matches the search term "london" if it cannot access the search term?</p>
| 2,996 |
<p>I need to install amp on a windows2003 production server. I'd like, if possible, an integrated install/management tool so I don't have to install/integrate the components of amp separately. Those that I've found are 'development' servers. Are there any packages out there that install amp in a production ready (locked down state)?</p>
<p>I'm aware of LAMP... Windows, since we have IIS apps already and we've paid for this box, is a requirement. I'll take care of all the other hangups. I just want a simple way to install, integrate, and manage AMP.</p>
| <p>There doesn't appear to be any all-in one packages that are up to date and 'designed' for production. You just can't trust the default installs to be secure on whats out there.</p>
<p>I ended up just doing this manually. It wasn't painful though. Each component's install procedure was documented reasonably well. Took me about 3.5hrs. A nice side effect of the involved setup was that it gave me a much better understanding of each component's dependencies and the ways in which they touch. In hind sight I should have done it manually from the start.</p>
<p>Note: make sure you read the comments below each component's documentation pages. Some contain valuable corrections to the install process.</p>
| <p>Xampp is quite popular, i just don't know how "production level" it is:</p>
<p><a href="http://www.apachefriends.org/en/xampp.html" rel="nofollow noreferrer">http://www.apachefriends.org/en/xampp.html</a></p>
<p>Without wanting to sound elite: For "real" production Environments, it's possibly not a bad idea to setup and configure the components individually, but this requires some deeper knowledge than "hit setup and run".</p>
| 15,490 |
<p>Does anyone know how to change the Bordercolor for a Datagridviewcell in c#?</p>
<p>Here's a picture of what I mean: </p>
<p><a href="http://www.zivillian.de/datagridview.png" rel="nofollow noreferrer">Datagridviewstyle http://www.zivillian.de/datagridview.png</a>
<a href="http://www.zivillian.de/datagridview.png" rel="nofollow noreferrer">Picture</a></p>
<p>Backgroundcolor, Textcolor and <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=233320&SiteID=1" rel="nofollow noreferrer">Images</a> are no Problem, but I don't know how to realise the Borders.</p>
<p>EDIT: I want to realise this with winforms.</p>
<p>Another problem is the cross in the second Row, but that's for later...</p>
| <p>You'd have to draw the cells yourself to achieve this, using OwnerDraw.</p>
| <p>You can hook up on two events on your datagridview. 'ItemCreated' and 'ItemDatabound' Each will pass you an eventarg that can access your itemtemplate. Within that you can .FindControl("ControlId") or step through the .Controls collections to find the cell. Once you got that cell you can do whatever you want - both bordercolor and the cross.
ItemCreated will fire for each drawing (postback) while ItemDatabound only when you databind :)</p>
| 13,391 |
<p>In my code, I want to view all data from a CSV in table form, but it only displays the last line. How about lines 1 and 2? Here's the data:</p>
<pre><code>1,HF6,08-Oct-08,34:22:13,df,jhj,fh,fh,ffgh,gh,g,rt,ffgsaf,asdf,dd,yoawa,DWP,tester,Pattern
2,hf35,08-Oct-08,34:12:13,dg,jh,fh,fgh,fgh,gh,gfh,re,fsaf,asdf,dd,yokogawa,DWP,DWP,Pattern
3,hf35,08-Oct-08,31:22:03,dg,jh,fh,fgh,gh,gh,gh,rte,ffgsaf,asdf,dfffd,yokogawa,DWP,DWP,ghh
</code></pre>
<p>Here's the code:</p>
<pre><code>#! /usr/bin/perl
print "Content-type:text/html\r\n\r\n";
use CGI qw(:standard);
use strict;
use warnings;
my $line;
my $file;
my ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19);
$file='MyFile.txt';
open(F,$file)||die("Could not open $file");
while ($line=<F>)
{
($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19)= split ',',$line;
}
close(F);
print "<HTML>";
print "<head>";
print "<body bgcolor='#4682B4'>";
print "<title>FUSION SHIFT REPORT</title>";
print "<div align='left'>";
print "<TABLE CELLPADDING='1' CELLSPACING='1' BORDER='1' bordercolor=black width='100%'>";
print "<TR>";
print "<td width='12%'bgcolor='#00ff00'><font size='2'>RECORD No.</td>";
print "<td width='12%'bgcolor='#00ff00'><font size='2'>TESTER No.</td>";
print "<td width='12%'bgcolor='#00ff00'><font size='2'>DATE</td>";
print "<td width='13%'bgcolor='#00ff00'><font size='2'>TIME</td>";
print "<td width='11%'bgcolor='#00ff00'><font size='2'>DEVICE NAME</td>";
print "<td bgcolor='#00ff00'><font size='2'>TEST PROGRAM</td>";
print "<td bgcolor='#00ff00'><font size='2'>DEVICE FAMILY</td>";
print "<td width='13%'bgcolor='#00ff00'><font size='2'>SMSLOT</td>";
print "<td width='13%'bgcolor='#00ff00'><font size='2'>DIE LOT</td>";
print "<td width='12%'bgcolor='#00ff00'><font size='2'>LOADBOARD</td>";
print "<td width='12%'bgcolor='#00ff00'><font size='2'>TESTER </td>";
print "<td width='12%'bgcolor='#00ff00'><font size='2'>SERIAL NUMBER</td>";
print "<td width='13%'bgcolor='#00ff00'><font size='2'>TESTER CONFIG</td>";
print "<td width='11%'bgcolor='#00ff00'><font size='2'>SMSLOT</td>";
print "<td bgcolor='#00ff00'><font size='2'>PACKAGE</td>";
print "<td bgcolor='#00ff00'><font size='2'>SOCKET</td>";
print "<td width='13%'bgcolor='#00ff00'><font size='2'>ROOT CAUSE 1</td>";
print "<td width='13%'bgcolor='#00ff00'><font size='2'>ROOT CAUSE 2</td>";
print "<td width='13%'bgcolor='#00ff00'><font size='2'>ROOT CAUSE 3</td>";
print "</tr>";
print "<TR>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f1</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f2</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f3</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f4</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f5</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f6</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f7</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f8</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f9</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f10</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f11</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f12</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f13</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f14</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f15</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f16</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f17</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f18</TD>";
print "<TD bgcolor='#ADD8E6'><font size='2'>$f19</TD>";
print "</tr>";
print "</TABLE>";
print "</body>";
print "<html>";
</code></pre>
| <p>You need to output the table rows <em>inside</em> the while loop, as that's where you are reading the lines.</p>
<p>So change the code so that it</p>
<ul>
<li>outputs table headers</li>
<li>reads the file line by line outputting table rows</li>
<li>outputs table footer</li>
</ul>
<p>Here's how your loop might look if a little simplified...</p>
<pre><code>while ($line=<F>)
{
print "<tr>";
my @cells= split ',',$line;
foreach my $cell (@cells)
{
print "<td>$cell</td>";
}
print "</tr>";
}
</code></pre>
| <p>Please close your <font> tags. Just because the browser will handle their lack doesn't mean they're not valuable to include.</p>
| 24,404 |
<p>I have an IList of type Breadcrumb which is just a lightweight class that has NavigationTitle, NavigationUrl and IsCurrent properties. It is cached on the webserver. I have a method that builds out the current breadcrumb trail up until the first Breadcrumb that has IsCurrent set to true... using the code below. Its very ugly and definitely a quick dirtbag willie solution, but I was curious, can this be easily refactored into LINQ? </p>
<pre><code>IList<Breadcrumb> crumbs = new List<Breadcrumb>();
bool foundCurrent = false;
for (int a = 0; a < cachedCrumbs.Count; a++)
{
crumbs.Add(crumbs[a]);
if (foundCurrent)
{
break;
}
foundCurrent = (crumbs[a + 1] != null && ((Breadcrumb)crumbs[a + 1]).IsCurrent);
}
</code></pre>
| <p>I'm typing this as I think, so that it shows a train of thought as well as just an answer.</p>
<ul>
<li>Your source is just cachedCrumbs</li>
<li>You want to add the first crumb which <em>does</em> have IsCurrent set, but nothing afterwards</li>
<li>TakeWhile sounds like the way to go, but getting the "previous value had IsCurrent" is a bit of a pain</li>
<li>We can use a closure to effectively keep a variable determining whether the last value had IsCurrent set</li>
<li>We can do a somewhat "no-op" select to keep the TakeWhile separate from the working out of whether to keep going</li>
</ul>
<p>So, we end up with:</p>
<pre><code>bool foundCurrent = false;
var crumbs = cachedCrumbs.TakeWhile(crumb => !foundCurrent)
.Select(crumb => {
foundCurrent = crumb == null || !crumb.IsCurrent;
return crumb; });
</code></pre>
<p>I haven't tried this, but I <em>think</em> it should work... there might be a simpler way though.</p>
<p>EDIT: I'd argue that actually a straight foreach loop <em>is</em> simpler in this case. Having said that, you could write another extension method which acted like TakeWhile except it <em>also</em> returned the element which caused the condition to fail. Then it would be as simple as:</p>
<pre><code>var crumbs = cachedCrumbs.NewMethod(crumb => crumb == null || !crumb.IsCurrent);
</code></pre>
<p>(I can't think of a decent name for the method at the moment, hence <code>NewMethod</code> !)</p>
| <p>First of all, that code doesn't work. I'm gonna guess that some of those places where you used "crumbs" you meant "cachedCrumbs". If so, the code can be reduced to:</p>
<pre><code>IList<Breadcrumb> crumbs = new List<Breadcrumb>();
for (int a = 0; a < cachedCrumbs.Count; a++)
{
crumbs.Add(cachedCrumbs[a]);
if (cachedCrumbs[a] != null && cachedCrumbs[a].IsCurrent)
{
break;
}
}
</code></pre>
| 29,289 |
<p>I have a table of time-series data of which I need to find all columns that contain at least one non-null value within a given time period. So far I am using the following query:</p>
<pre><code>select max(field1),max(field2),max(field3),...
from series where t_stamp between x and y
</code></pre>
<p>Afterwards I check each field of the result if it contains a non-null value. </p>
<p>The table has around 70 columns and a time period can contain >100k entries.</p>
<p>I wonder if there if there is a faster way to do this (using only standard sql). </p>
<p>EDIT:
Unfortunately, refactoring the table design is not an option for me.</p>
| <p>The EXISTS operation may be faster since it can stop searching as soon as it finds any row that matches the criteria (vs. the MAX which you are using). It depends on your data and how smart your SQL server is. If most of your columns have a high rate of non-null data then this method will find rows quickly and it should run quickly. If your columns are mostly NULL values then your method may be faster. I would give them both a shot and see how they are each optimized and how they run. Also keep in mind that performance may change over time if the distribution of your data changes significantly.</p>
<p>Also, I've only tested this on MS SQL Server. I haven't had to code strict ANSI compatible SQL in over a year, so I'm not sure that this is completely generic.</p>
<pre><code>SELECT
CASE WHEN EXISTS (SELECT * FROM Series WHERE t_stamp BETWEEN @x AND @y AND field1 IS NOT NULL) THEN 1 ELSE 0 END AS field1,
CASE WHEN EXISTS (SELECT * FROM Series WHERE t_stamp BETWEEN @x AND @y AND field2 IS NOT NULL) THEN 1 ELSE 0 END AS field2,
...
</code></pre>
<p>EDIT: Just to clarify, the MAX method might be faster since it could determine those values with a single pass through the data. Theoretically, the method here could as well, and potentially with less than a full pass, but your optimizer may not recognize that all of the subqueries are related, so it might do separate passes for each. That still might be faster, but as I said it depends on your data.</p>
| <p>Edit: I think I misread the question... this will give you all the <em>rows</em> with a non-null value. I'll leave it here in case it helps someone but it's not the answer to your question. Thanks @Pax</p>
<p>I think you want to use <a href="http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce" rel="nofollow noreferrer"><code>COALESCE</code></a>:</p>
<p><code>SELECT ... WHERE COALESCE(fild1, field2, field3) IS NOT NULL</code></p>
| 42,831 |
<p>I have inherited a Java applet (an actual <APPLET>) which throws an OutOfMemory exception after about 4 days of runtime. The nature of the applet is such that people really will leave it open for long periods of time.</p>
<p>After almost two days running, jmap -histo shows the top heap consumers as:</p>
<pre>
num #instances #bytes class name
--- ---------- ------ ----------
1: 14277 7321880 <constantPoolKlass>
2: 59626 5699968 <constMethodKlass>
3: 14047 5479424 <constantPoolCacheKlass>
4: 14277 5229744 <instanceKlassKlass>
5: 59626 4778944 <methodKlass>
6: 71026 3147624 <symbolKlass>
</pre>
<p>The trouble is, I don't understand what any of these things are. There are at least two things going on: constantPoolKlass+constantPoolCacheKlass+instanceKlassKlass appear related, as do constMethodKlass+methodKlass. From the names, they appear related to a class loader.</p>
<p>If I had to guess I'd say the applet has creating about 14,277 objects where each object has about 4 methods, for about 59626 methods total. Yet the jmap output doesn't show any class with such a large number of instances, nor does it look like the sum total of other class objects add up to 14277. So maybe I'm incorrect about what these objects do. Can someone explain?</p>
| <p>Yup, looks like you are leaking class loaders. If you're not actually creating class loaders in you own code (typically through URLClassLoader.newInstance or XSLT) then it may be related to reloading the applet (although you would usually get back the same class loader). Possible causes of leaks are ThreadLocal, JDBC drivers and java.beans.</p>
| <p>Yup, looks like you are leaking class loaders. If you're not actually creating class loaders in you own code (typically through URLClassLoader.newInstance or XSLT) then it may be related to reloading the applet (although you would usually get back the same class loader). Possible causes of leaks are ThreadLocal, JDBC drivers and java.beans.</p>
| 44,304 |
<p>Is there a way to view the register contents in each stack frame in a crash dump?
The registers window seems to contain the registers when the exception occurred but it would be useful to be able to see their contents in each stack frame.</p>
| <p>Depending on the calling convention, you can get some of the registers which are saved on the stack. For example, in the <a href="http://en.wikipedia.org/wiki/X86_calling_conventions#cdecl" rel="nofollow noreferrer">cdecl calling convention</a>, all of the registers except for EAX, ECX, and EDX are required to be saved, either by the caller or the callee. Those three registers are clobberable, so you generally won't be able to get their values from higher up in the call stack. If a function doesn't use a register that must be saved, then it won't save it, but since it doesn't use it, that register has the same value in the next higher stack frame.</p>
| <p>I don't think you can get it either when debugging. The only value you can get from registers is their value at the current instruction.</p>
| 46,632 |
<p>I'm curious to know whether the PDFKit framework is available for use within the iPhone OS, in order to build a PDF reader a bit more sophisticated than the one available by simply opening PDF documents with UIWebView.</p>
<p>Just wondering if this is an option or not.</p>
| <p>The PDFKit is not available on iPhone at this time. Certainly the functionality is there, but Apple has not opened it up in an available framework. You should file a bug on this if you'd like to see it in the future.</p>
<p>If you want more control over PDF, there are many ways to manipulate PDF content using Quartz graphics.</p>
| <p>Grab the official sample code called QuartzDemo which has an example on how to manipulate a PDF file using Quartz graphics. The output seems faster than the UIWebView.</p>
| 36,819 |
<p>Having a computer with multiple NICs, I need to specify somehow the one to use for the connection to SQL Server.</p>
| <p>Following on from @pzycoman, SqlConnection (and SQL OLEDB/SQL Server ODBC) has no explicit connection string semantic to express the bound NIC other than to specify the destination server host address (which in turn triggers the route metrics discussion). Splitting out services or applications onto different subnets can work - but equally can also generate the utilization asymmetry similar what you see today. </p>
<p>Another potential option would be NIC teaming if your adapters support it. Teaming software bonds multiple NICs into a single logical channel for increased throughput with less NetOps complexity. This happens at a much lower level in the OSI and as such is transparent to your applications and services.</p>
<p>Teaming used to be frowned on for a number of reasons (predominantly NLB issues and driver quality), but those have been largely mitigated in the last couple of years.</p>
<p>As always engineering mentality will help - test <em>everything</em>.</p>
| <p>If the NIC's have diffrent subnets, windows should automatically route the request through the right NIC (running "route print" from the command line will show you what gets routed where)</p>
| 22,195 |
<p>When sockets are created or files are opened/created in C, is the file descriptor that's assigned to the socket/file guaranteed to be the lowest-valued descriptor available? What does the C spec say about file descriptor assignment in this regard, if anything?</p>
| <p>It's not guaranteed to be the lowest, and is implementation dependent <em>(1)</em>. In general, however, the routine that assigns open file descriptors uses a method that gives you the first open on. It could be that immediately after several lower ones free, leaving you with a higher descriptor than you might expect though.</p>
<p>The only reason I can think of to know this, though, is for the select function, which is sped up if you pass it the highest file descriptor you need to check for.</p>
<p><em>(1)</em> Note that those implementations that follow the IEEE standard do guarantee the lowest unused descriptor for files, but this may not apply to sockets. Not every implementation follows the IEEE standard for open(), so if you're writing portable software it is best not to depend on it.</p>
| <p>Steve M is right; C has no notion of sockets, and its file I/O functions use a [pointer to a] FILE object, not a descriptor.</p>
| 7,479 |
<p>Where can I find a free, lightweight YUI-like compressor for PHP?</p>
<p>I am sure it will decrease the file size but will compressing PHP code boost its performance?</p>
<p>Is this the same thing as an obfuscator?</p>
| <p>There is a product called PHP Encoder by ionCube (<a href="http://www.ioncube.com/sa_encoder.php" rel="noreferrer">http://www.ioncube.com/sa_encoder.php</a>) which is enterprise grade compression and obfuscater.</p>
<p>PHP Encoder is a PHP extension to create and run compiled bytecodes for accelerated runtime performance and maximum security.</p>
<p>It will shrink the file size, and speed up runtime because the code is already partially compiled</p>
| <p>NuSphere has also released <a href="http://www.nusphere.com/products/nucoder.htm" rel="nofollow noreferrer">Nu-Coder</a> for both securing code and accelerating it.</p>
| 27,218 |