instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
---|---|---|---|
<p>We are attempting to use a SQL Server 2003 database for our test records and want a quick way to take NUnit and NAnt output and produce SQL schema and data. Is there a simple way to generate SQL Schema using the XSD file describing these XML documents?</p>
| <p>You could use XSD. No, I'm serious. Go to a command prompt and type xsd and press Enter.</p>
<p>Here's what you will see (truncated):</p>
<pre><code>I:\>xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 1.0.3705.0]
Copyright (C) Microsoft Corporation 1998-2001. All rights reserved.
xsd.exe -
Utility to generate schema or class files from given source.
xsd.exe <schema>.xsd /classes|dataset [/e:] [/l:] [/n:] [/o:] [/uri:]
xsd.exe <assembly>.dll|.exe [/outputdir:] [/type: [...]]
xsd.exe <instance>.xml [/outputdir:]
xsd.exe <schema>.xdr [/outputdir:]
</code></pre>
<p>Just follow the instructions.</p>
| <p>There's a tool called <a href="http://shrex.sourceforge.net/" rel="nofollow noreferrer">ShreX</a> that can can makes schemas from xsd and inserts from XML. It tries to do this by itself (you can annotade the xsd to steer it). If you want to decide the structure yourself it might not be what you want.</p>
| 13,102 |
<p>Reporting Services 2000 Standard Edition (currently RTM but hope to have SP2 soon).</p>
<p>I have a report which takes in a parameter - PlantID</p>
<p>I'd like to email a pdf of this report every month to the 80 different plant managers</p>
<p>So I have a table:</p>
<pre><code>PlantID ManagerEmail
1 [email protected]
2 [email protected]
3 [email protected]
</code></pre>
<p>I can currently setup a subscription to email a report to multiple users each month (which uses the SQL agent).</p>
<p>However I want to specify the input parameter of the report (PlantID) to the recipient of the email (ManagerEmail).</p>
<p>Ideas on how to do this? My current thought is to build a C# app which calls the URL of the RS with the correct input parameter in it. Then gets the pdf back, then emails from C#.</p>
<p>Many thanks</p>
| <p>A Data-Driven Subscription would be the ideal answer, but I see that Data-Driven Subscriptions are not available in RS 2000 Standard.</p>
<p><a href="http://www.codeproject.com/KB/database/DataDrivenSubscriptions.aspx" rel="nofollow noreferrer">This Article</a> discusses how to use a stored procedure to tweak a Reporting Services subscription and insert your own values into the respective fields.</p>
| <p>That would be my first thought on how to do it also.</p>
<p>You might also be able to set up a scheduled stored proc to execute it for you, but that's more of a guess than an experienced suggestion.</p>
| 29,905 |
<p>Is it ever OK to use <code>Environment.TickCount</code>to calculate time spans?</p>
<pre><code>int start = Environment.TickCount;
// Do stuff
int duration = Environment.TickCount - start;
Console.WriteLine("That took " + duration " ms");
</code></pre>
<p>Because <code>TickCount</code> is signed and will rollover after 25 days (it takes 50 days to hit all 32 bits, but you have to scrap the signed bit if you want to make any sense of the math), it seems like it's too risky to be useful. </p>
<p>I'm using <code>DateTime.Now</code> instead. Is this the best way to do this?</p>
<pre><code>DateTime start = DateTime.Now;
// Do stuff
TimeSpan duration = DateTime.Now - start;
Console.WriteLine("That took " + duration.TotalMilliseconds + " ms");
</code></pre>
| <p>Use Stopwatch class. There is a decent example on msdn: <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx</a></p>
<pre><code> Stopwatch stopWatch = Stopwatch.StartNew();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
</code></pre>
| <p>You should use the <a href="https://stackoverflow.com/questions/28637/is-datetimenow-the-best-way-to-measure-a-functions-performance">Stopwatch</a> class instead.</p>
| 30,147 |
<p>By default, in C++, a single-argument constructor can be used as an implicit conversion operator. This can be suppressed by marking the constructor as explicit.</p>
<p>I'd prefer to make "explicit" be the default, so that the compiler cannot silently use these constructors for conversion.</p>
<p>Is there a way to do this in standard C++? Failing that, is there a pragma (or similar) that'll work in Microsoft C++ to do this? What about g++ (we don't use it, but it might be useful information)?</p>
| <p>Nope, you have to do it all by hand. It's a pain, but you certainly should get in the habit of making single argument constructors explicit. I can't imagine the pain you would have if you did find a solution and then had to port the code to another platform. You should usually shy away from compiler extensions like this because it will make the code less portable.</p>
| <p>I think the answer is no!</p>
<p>Sorry, its not a very constructive answer. I hope somebody else might know more!</p>
| 21,007 |
<p>I only know a small amount about .NET MVC and haven't used it barely at all so far but I was wondering how would you create re-useable controls that can be spread across different applications?</p>
<p>We have various controls that have been created in external libraries and we reference the assembly if we want to use them. An example would be a date range selector for reports, the user can select two dates which they then post back the page and the controls changed date event is fired and the report is updated.</p>
<p>How would you accomplish this in MVC? I know you can still use the control like you would do normally but this doesn't seem like the way MVC should be used. I thought that normally you would post the form data to a new view, validate the form data and then do whatever is required next. However when this is all encapsulated inside a control how can you possibly split it out over multiple views?</p>
<p>Some points I'm hoping to get out of this question are:</p>
<ul>
<li>How do you get around this?</li>
<li>What sort of work flow do your controls have?</li>
<li>Do your forms actually post to other pages or do they post back to the same page?</li>
</ul>
<p>**** Update:****</p>
<p>I have found this blog entry from Rob Conery but it doesn't deal with controls it deals with usercontrols. Even with the below method of rendering a control how would you use it to render a control which dealt with a form?</p>
<p><a href="http://blog.wekeroad.com/2008/01/07/aspnet-mvc-using-usercontrols-usefully/" rel="nofollow noreferrer">http://blog.wekeroad.com/2008/01/07/aspnet-mvc-using-usercontrols-usefully/</a></p>
| <p>For reuse of view elements, user controls and extensions of HtmlHelper should suit your needs. I have created a project that extends view pages to generate view elements using a fluent interface. Read about it <a href="http://lunaverse.wordpress.com/2008/11/24/mvcfluenthtml-fluent-html-interface-for-ms-mvc/" rel="nofollow noreferrer">here</a>. </p>
<p>However, these are all view-only approaches. For reuse of UI element that include server side processing <a href="http://www.codeplex.com/MVCContrib" rel="nofollow noreferrer">MvcContrib</a> has developed the concept of sub-controllers. Read about it <a href="http://mhinze.com/subcontrollers-in-aspnet-mvc/" rel="nofollow noreferrer">here</a>. Here's another <a href="http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/" rel="nofollow noreferrer">blog post</a> that describes an alternative approach that claims to be less complex using "partial requests." I have not ventured into this territory myself yet.</p>
| <p>You can use pure javascript controls which can then "post back" via ajax. On the server side you have a controller + action which handles the date range changes.</p>
<p><a href="http://developer.yahoo.com/yui/examples/calendar/multi.html" rel="nofollow noreferrer">A calendar example</a></p>
| 45,058 |
<p>I'm trying to pass one method to another in elisp, and then
have that method execute it. Here is an example:</p>
<pre><code>(defun t1 ()
"t1")
(defun t2 ()
"t1")
(defun call-t (t)
; how do I execute "t"?
(t))
; How do I pass in method reference?
(call-t 't1)
</code></pre>
| <p>First, I'm not sure that naming your function <code>t</code> is helping as 't' is used as the <a href="http://www.mcs.vuw.ac.nz/cgi-bin/info2www?(elisp)nil+and+t" rel="noreferrer">truth value</a> in lisp.</p>
<p>That said, the following code works for me:</p>
<pre><code>(defun test-func-1 () "test-func-1"
(interactive "*")
(insert-string "testing callers"))
(defun func-caller (callee)
"Execute callee"
(funcall callee))
(func-caller 'test-func-1)
</code></pre>
<p>Please note the use of 'funcall', which triggers the actual function call.</p>
| <p>Above answers are okey, but you can do something more interesting with defmacro, wich evaluates functions later for some reason:</p>
<pre><code>(defun n1 ()
"n1")
(defmacro call-n (n)
(apply n))
(call-n (n1))
</code></pre>
<p>A practical example with a for loop that takes any amount of functions and their arguments:</p>
<pre><code>(defmacro for (i &optional i++ &rest body)
"c-like for-loop"
(unless (numberp i++) (push i++ body) (setq i++ 1))
(while (/= i 0)
(let ((args 0))
(while (nth args body)
(apply (car (nth args body))
(cdr (nth args body)))
(setq args (1+ args))))
(setq i (- i i++))
)
)
</code></pre>
| 26,213 |
<p>During an ASP.NET page load I'm opening and closing multiple System.Data.SqlClient.SqlConnections inside multiple controls contained in the page. I thought it would be a good idea instead to create a "pool" of connections and when opening a connection check to see if the connection string matches that of an open connection in the pool, and return that connection. I was expecting to see a difference in the page load times, but I haven't seen any change. I know that with PHP if you attempt to open a new connection with a connection string that has already been used in that page request it won't attempt to open a new connection and will return the existing open connection instead. Is this true with .NET?</p>
| <p>Connection pooling is an essential feature of ADO.NET.</p>
<p>Read this <a href="http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx" rel="nofollow noreferrer">MSDN article</a> or some of the other resources available on the net, like this <a href="http://weblogs.asp.net/sjoseph/archive/2005/03/23/395601.aspx" rel="nofollow noreferrer">blog post</a></p>
| <p>Yes, that is basically how connection pooling works in ADO.NET.</p>
<p>When you call <code>Open()</code> on a Connection-instance, it doesn't necessarily open a connection. It fetches an open connection from the pool, matching the connection string. <code>Close()</code> releases the connection back into the pool.</p>
| 21,426 |
<p>I have a class named Page with a private property currently called <code>_pageData</code> which stores all the information (such as title, content, keywords etc). </p>
<p>However, this to me doesn't look so good when I refer to it <code>$this->_pageData</code>. I want to think of a better name, and I'd imagine there would probably be a standard or 'best practice' name/prefix/suffix for these sorts of things. I thought about '_assets'. </p>
<p>May I ask what you have used in the past, an unambiguous name that hasn't made you down the track add some data to it and go "Oh no, now my array has data in it that's outside the scope of the variable name". This has happened to me a few times so I'd like to see what has been proven to work.</p>
| <pre><code>class Page {
public $title = '';
public $keywords = array();
public $content = '';
// etc.
}
$page = new Page();
echo '<title>' . $page->title . '</title>';
echo $page->content;
</code></pre>
<p>Or you can use accessors/get-set and the like to protect your data, allow it to be modified with persistence, or whatever. This allows for lazy initialization and lazy writing (not sure if there's a proper term for the latter). Example:</p>
<pre><code>class Page {
private $data = array('title' => '', 'keywords' => array(), 'content' => '');
public __get($name) {
if(isset($this->data[$name]))
return $this->data[$name];
/* You probably want to throw some sort of PHP error here. */
return 'ERROR!';
}
}
$page = new Page();
echo '<title>' . $page->title . '</title>';
echo $page->content;
</code></pre>
<p>(See <a href="http://php.net/manual/en/language.oop5.overloading.php" rel="nofollow noreferrer">overloading in the PHP5 manual</a> for more details.)</p>
<p>Note you can hide $data members or even modify them or add new ones ($page->contentHTML could transform markdown to HTML, for example).</p>
<p>Using the name <code>_pageData</code> is redundant for a Page class. You already know it's a page, so you're repeating information ($currentPage->_pageData vs. $currentPage->data).</p>
<p>I also find associative arrays a little messier for this kind of thing, but they may be needed if you want a really dynamic system. Regardless, you can implement your template system to access class members by name (<code>$member = 'title'; echo $page->$member; // echoes $page->title</code>), assuming this is what you wanted the array for (other than an easy database query, which you can use list() for).</p>
| <p>That's very specific and I don't think there is a "standard" or "best practice". Just call it whatever it feels best in your opinion. In my own, I would simply call it "data" as Page is the class, $this = Page, so Page->Data. This would suffice for me.</p>
<p>I can't think of a better name... Maybe it sounds weird because you use the _ prefix? I don't like to use those kinds of prefixes, specially in PHP, it doesn't make much sense, but that's just me.</p>
| 49,294 |
<p>I have a problem with <strong>scandir()</strong>: The manpage contains this as prototype:</p>
<pre><code>int scandir(const char *dir, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **));
</code></pre>
<p>Therefore I have this:</p>
<pre><code>static inline int
RubyCompare(const struct dirent **a,
const struct dirent **b)
{
return(strcmp((*a)->d_name, (*b)->d_name));
}
</code></pre>
<p>And here's the call:</p>
<pre><code>num = scandir(buf, &entries, NULL, RubyCompare);
</code></pre>
<p>Finally the compiler says this:</p>
<pre><code>warning: passing argument 4 of ‘scandir’ from incompatible pointer type
</code></pre>
<p>Compiler is <strong>gcc-4.3.2</strong>, my CFLAGS are following: </p>
<pre><code>-Wall -Wpointer-arith -Wstrict-prototypes -Wunused -Wshadow -std=gnu99
</code></pre>
<p>What is the meaning of this warning? The declaration of RubyCompare looks correct for me and besides the warning the code works completely.</p>
| <p>Actually, there's no such constraint that you can't pass a pointer to an inline function. The inline keyword serves only as a hint to the compiler to inline calls when it can.</p>
<p>The problem is that the manpage for scandir() is a little misleading. The prototype in for the 4th parameter is actually int (*cmp)(const void *, const void *).</p>
<p>Therefore you need to change the code like so:</p>
<pre><code>static inline int RubyCompare(const void *a, const void *b)
{
return(strcmp((*(struct dirent **)a)->d_name,
(*(struct dirent **)b)->d_name));
}
</code></pre>
<p>I'm not actually sure why you're writing this function, though, because you can use the provided alphasort compare function:</p>
<pre><code>num = scandir(buf, &entries, NULL, alphasort);
</code></pre>
| <p>You're giving it a pointer to an inline function? That doesn't make sense, actually I wonder that it even compiles with only a warning.</p>
<p><strong>EDIT</strong>: Chris above is right, the inline keyword is just ignored silently when it doesn't make sense / is not applicable.</p>
| 17,617 |
<p>I am sure a responsive UI is something that everyone strives for and the reccomended way to do stuff is to use the BackgroundWorker for this. </p>
<p>Do you find it easy to work with ? Do you use it often ? Or do you have your own frameworks for lengthy tasks and reporting process.</p>
<p>I have found that I am using it quite a lot and even using its delegates wherever I need some sort of progress reporting.</p>
| <p>Multithreaded programming is hard to grasp in the beginning (and veterans still fail sometimes) and BackgroundWorker makes it a bit easier to use. I like the fact that BackgroundWorker has functionality which is easy to implement but even easier to wrongly implement in a subtle way, like cancellation.
I use it if I have and need a progress update, so I can display a meaningful progress bar. </p>
<p>If not, I use a Thread (or borrow from the ThreadPool), because I don't need all the functionality of BackgroundWorker and am proficient enough with threads to start a Thread and wait for it to stop.</p>
<p>As for delegates for non-related tasks, I use those of the Thread classes, like plain <code>void ThreadStart()</code>, or I create my own.</p>
| <p>My biggest issue with the background worker class is that there really is no way to know when the worker has finished due to cancellation. The BackgroundWorker does not expose the thread it uses so you can't use the standard techniques for synchronizing thread termination (join, etc.). You also can't just wait in a loop on the UI thread for it to end because the RunWorkerCompleted event will never end up firing. The hack I've always had to use is to simply set a flag and then start a timer that will continue checking for the background worker to end. But it's very messy and complicates the business logic.</p>
<p>So it is great as long as you don't need to support deterministic cancellation.</p>
| 7,240 |
<p>One challenge with Silverlight controls is that when properties are bound to code, they're no longer really editable in Blend. For example, if you've got a ListView that's populated from a data feed, there are no elements visible when you edit the control in Blend.</p>
<p>I've heard that the MVVM pattern, originated by the WPF development community, can also help with keeping Silverlight controls "blendable". I'm still wrapping my head around it, but here are some explanations:</p>
<ul>
<li><a href="http://www.nikhilk.net/Silverlight-ViewModel-Pattern.aspx" rel="noreferrer">http://www.nikhilk.net/Silverlight-ViewModel-Pattern.aspx</a></li>
<li><a href="http://mark-dot-net.blogspot.com/2008/11/model-view-view-model-mvvm-in.html" rel="noreferrer">http://mark-dot-net.blogspot.com/2008/11/model-view-view-model-mvvm-in.html</a></li>
<li><a href="http://www.ryankeeter.com/silverlight/silverlight-mvvm-pt-1-hello-world-style/" rel="noreferrer">http://www.ryankeeter.com/silverlight/silverlight-mvvm-pt-1-hello-world-style/</a></li>
<li><a href="http://jonas.follesoe.no/YouCardRevisitedImplementingTheViewModelPattern.aspx" rel="noreferrer">http://jonas.follesoe.no/YouCardRevisitedImplementingTheViewModelPattern.aspx</a> </li>
</ul>
<p>One potential downside is that the pattern requires additional classes, although not necessarily more code (as shown by the second link above). Thoughts?</p>
| <p>I definitely think you should use the MVVM pattern for Silverlight applications - and one of the benefits of the pattern is that you can actually make your application really blendable through some simple techniques. I often refer to "blendability" as "design for designability" - that you use certain techniques to make sure your application looks great in Blend.</p>
<p>One of the techniques - like Torbjørn points out - is to use a dependency injection framework and supply different implementations of your external services depending on wether the code is being executed in Blend or in the Browser. So I configure my container to use a dummy data provider when the code is executing in Blend, and that way you get design time support for your list boxes, data grids etc.</p>
<p>The challenge is often how to set the DataContext declaratively - so I often end up using a service locator class a a "front end" to the IoC container. That way I can bind the data context to a property on the service locator.</p>
<p>Another technique is create some kind of ObjectDataSource control (non visual) that has two properties: Design Time DataContext and RunTime Data Context. The control does the job of detecting where is being executing, and then setting the Parent DataContext to the right object.</p>
| <p>I've always thought MVVM and PresntationModel <a href="http://martinfowler.com/eaaDev/PresentationModel.html" rel="nofollow noreferrer">http://martinfowler.com/eaaDev/PresentationModel.html</a> are essentially the same thing. PresentationModel is a lot easier to say.
I've used it succesfully in java swing, windows forms, WPF and silverlight. If you think in terms of separation of concerns a Presentation Model makes a lot of sense. You have one class whose only concern is providing a Presentation friendly Model.It really doesn't matter what technology is used to show it on the screen. It might change some implementation details but splitting the concerns apart is a good idea no matter how you show the information.
Because of that separation you can easily write tests against your presentation model regardless of the view technology. So that's a plus.</p>
| 49,109 |
<p>Say I have a class called PermissionManager which should only exist once for my system and basically fulfills the function of managing various permissions for various actions in my application. Now I have some class in my application which needs to be able to check a certain permission in one of its methods. This class's constructor is currently public, i.e. used by API users.</p>
<p>Until a couple of weeks ago, I would have simply had my class call the following pseudo-code somewhere:</p>
<pre><code> PermissionManager.getInstance().isReadPermissionEnabled(this)
</code></pre>
<p>But since I have noticed everyone here hating singletons + this kind of coupling, I was wondering what the better solution would be, since the arguments I have read against singletons seem to make sense (not testable, high coupling, etc.).</p>
<p>So should I actually require API users to pass in a PermissionManager instance in the constructor of the class? Even though I only want a single PermissionManager instance to exist for my application?</p>
<p>Or am I going about this all wrong and should have a non-public constructor and a factory somewhere which passes in the instance of PermissionManager for me?</p>
<hr>
<p><strong>Additional info</strong> Note that when I say "Dependency Injection", I'm talking about the DI <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">Pattern</a>...I am not using any DI framework like Guice or Spring. (...yet)</p>
| <p>If you are using a dependency-injection framework, then the common way to handle this is to either pass in a PermissionsManager object in the constructor or to have a property of type PermissionsManager that the framework sets for you. </p>
<p>If this is not feasible, then having users get an instance of this class via factory is a good choice. In this case, the factory passes the PermissionManager in to the constructor when it creates the class. In your application start-up, you would create the single PermissionManager first, then create your factory, passing in the PermissionManager.</p>
<p>You are correct that it is normally unwieldy for the clients of a class to know where to find the correct PermissionManager instance and pass it in (or even to care about the fact that your class uses a PermissionManager).</p>
<p>One compromise solution I've seen is to give your class a property of type PermissionManager. If the property has been set (say, in a unit test), you use that instance, otherwise you use the singleton. Something like:</p>
<pre><code>PermissionManager mManager = null;
public PermissionManager Permissions
{
if (mManager == null)
{
return mManager;
}
return PermissionManager.getInstance();
}
</code></pre>
<p>Of course, strictly speaking, your PermissionManager should implement some kind of IPermissionManager interface, and <strong>that's</strong> what your other class should reference so a dummy implementation can be substituted more easily during testing.</p>
| <p>The singleton pattern is not bad by itself, what makes it ugly is the way it's commonly used, as being the requirement of only wanting a single instance of a certain class, which I think it's a big mistake.</p>
<p>In this case I'd make PermissionManager a static class unless for any reason you need it to be an instanciable type.</p>
| 30,666 |
<p>Perl has several built-in functions for accessing /etc/passwd on Unix systems (and elsewhere when supported) for user and group information. For instance,</p>
<pre><code>my $name = getpwuid($uid);
</code></pre>
<p>will return the user name given the user ID, or undef if there is no such user.</p>
<p>If a Perl script needs to be portable and run on Unices and Windows, how should one access user and group information? ActivePerl seems to support User::grent and User::pwent modules, which provide by-field access to /etc/passwd -- even in Windows. Curiously they do not support the built-in functions getpw* and getgr*. What other alternatives are there?</p>
| <p>You could use the <a href="http://aspn.activestate.com/ASPN/CodeDoc/libwin32/NetAdmin/NetAdmin.html" rel="nofollow noreferrer"><code>Win32::NetAdmin</code> module</a>.</p>
<p><code>UserGetAttributes</code> and <code>GroupIsMember</code> look like they do what you need.</p>
| <p>Oddly enough, Interix's build of Perl that ships with Microsoft's Services for Unix does support getpw* and friends.</p>
| 21,413 |
<p>We have a COM object implemented with C++/ATL that includes a method which will return a DIB. We are also writing a .NET application that will use this COM object. Since we are writing both, we have the liberty of deciding how best to return this DIB from the COM object. To clarify, would it be best to return a native windows handle to a DIB or a byte array or is there some other way to easily transition a windows DIB into a .NET Image object? And, related to that question: once I have this returned DIB how can I get it into a .NET Image object?</p>
| <p>COM/OLE has a standard interface for representing graphical images called <a href="http://msdn.microsoft.com/en-us/library/ms680761(VS.85).aspx" rel="nofollow noreferrer">IPicture</a> (and its scripting-friendly version <a href="http://msdn.microsoft.com/en-us/library/ms680762(VS.85).aspx" rel="nofollow noreferrer">IPictureDisp</a>).</p>
<p>COM provides an implementation of these interfaces for you. You can get it to build one for you by calling <a href="http://msdn.microsoft.com/en-us/library/ms694511(VS.85).aspx" rel="nofollow noreferrer">OleCreatePictureIndirect()</a>. You just hand it a <a href="http://msdn.microsoft.com/en-us/library/ms693798(VS.85).aspx" rel="nofollow noreferrer">PICTDESC structure</a> with the graphic you have, and it gives you back an interface. You should be able to hand that interface back to the calling program. This will also make your object compatible with other COM clients like VB6.</p>
<p>Back in .NET land you can turn an IPicture into an Image using <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.compatibility.vb6.support.ipicturetoimage.aspx" rel="nofollow noreferrer">Microsoft.VisualBasic.Compatibility.VB6.IPictureToImage()</a>.</p>
| <p>Have a look at the article <a href="http://www.codeproject.com/KB/GDI-plus/DIBtoBitmap.aspx" rel="nofollow noreferrer">DIB to System.Bitmap</a> on CodeProject. It has the code to convert from a DIB to a Bitmap. The idea is that the DIB is represented using a IntPtr.</p>
| 33,353 |
<p>I moved a bunch of projects to Solution Folders to chop up our list of projects into manageable folders, now each of the folders projects are not in alphabetical order. This only occurs on machines other than my own. Any ideas how to alleviate this?</p>
| <p>See the following bug information on MS Connect:
<a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=312252&wa=wsignin1.0" rel="nofollow noreferrer">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=312252&wa=wsignin1.0</a></p>
<p>To summarize:
"
The order they show up in solution explorer is the order in which they were written to the solution file. However, if the folder is collapsed on startup it will be sorted when you expand it.
"</p>
<p>Therefore, the fast solution would be to hand edit the solution file and put the projects in the order you wish.</p>
| <p>I found a tool that seems to do the trick:
<a href="http://solutionsorter.codeplex.com/" rel="nofollow noreferrer">http://solutionsorter.codeplex.com/</a></p>
| 37,186 |
<p>My boss has come to me and asked how to enure a file uploaded through web page is safe. He wants people to be able to upload pdfs and tiff images (and the like) and his real concern is someone embedding a virus in a pdf that is then viewed/altered (and the virus executed). I just read something on a procedure that could be used to destroy stenographic information emebedded in images by altering least sifnificant bits. Could a similar process be used to enusre that a virus isn't implanted? Does anyone know of any programs that can scrub files? </p>
<p>Update:
So the team argued about this a little bit, and one developer found a post about letting the file download to the file system and having the antivirus software that protects the network check the files there. The poster essentially said that it was too difficult to use the API or the command line for a couple of products. This seems a little kludgy to me, because we are planning on storing the files in the db, but I haven't had to scan files for viruses before. Does anyone have any thoughts or expierence with this?</p>
<p><a href="http://www.softwarebyrob.com/2008/05/15/virus-scanning-from-code/" rel="nofollow noreferrer">http://www.softwarebyrob.com/2008/05/15/virus-scanning-from-code/</a></p>
| <p>I'd recommend running your uploaded files through antivirus software such as <a href="http://www.clamav.net/" rel="nofollow noreferrer">ClamAV</a>. I don't know about scrubbing files to remove viruses, but this will at least allow you to detect and delete infected files before you view them.</p>
| <p>Yes, ClamAV should scan the file regardless of the extension.</p>
| 5,307 |
<p>I've created some fairly simple XAML, and it works perfectly (at least in KAXML). The storyboards run perfectly when called from within the XAML, but when I try to access them from outside I get the error:</p>
<pre><code>'buttonGlow' name cannot be found in the name scope of 'System.Windows.Controls.Button'.
</code></pre>
<p>I am loading the XAML with a stream reader, like this:</p>
<pre><code>Button x = (Button)XamlReader.Load(stream);
</code></pre>
<p>And trying to run the Storyboard with: </p>
<pre><code>Storyboard pressedButtonStoryboard =
Storyboard)_xamlButton.Template.Resources["ButtonPressed"];
pressedButtonStoryboard.Begin(_xamlButton);
</code></pre>
<p>I think that the problem is that fields I am animating are in the template and that storyboard is accessing the button. </p>
<p>Here is the XAML:</p>
<pre><code><Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:customControls="clr-namespace:pk_rodoment.SkinningEngine;assembly=pk_rodoment"
Width="150" Height="55">
<Button.Resources>
<Style TargetType="Button">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Background="#00FFFFFF">
<Grid.BitmapEffect>
<BitmapEffectGroup>
<OuterGlowBitmapEffect x:Name="buttonGlow" GlowColor="#A0FEDF00" GlowSize="0"/>
</BitmapEffectGroup>
</Grid.BitmapEffect>
<Border x:Name="background" Margin="1,1,1,1" CornerRadius="15">
<Border.Background>
<SolidColorBrush Color="#FF0062B6"/>
</Border.Background>
</Border>
<ContentPresenter HorizontalAlignment="Center"
Margin="{TemplateBinding Control.Padding}"
VerticalAlignment="Center"
Content="{TemplateBinding ContentControl.Content}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"/>
</Grid>
<ControlTemplate.Resources>
<Storyboard x:Key="ButtonPressed">
<Storyboard.Children>
<DoubleAnimation Duration="0:0:0.4"
FillBehavior="HoldEnd"
Storyboard.TargetName="buttonGlow"
Storyboard.TargetProperty="GlowSize" To="4"/>
<ColorAnimation Duration="0:0:0.6"
FillBehavior="HoldEnd"
Storyboard.TargetName="background"
Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
To="#FF844800"/>
</Storyboard.Children>
</Storyboard>
<Storyboard x:Key="ButtonReleased">
<Storyboard.Children>
<DoubleAnimation Duration="0:0:0.2"
FillBehavior="HoldEnd"
Storyboard.TargetName="buttonGlow"
Storyboard.TargetProperty="GlowSize" To="0"/>
<ColorAnimation Duration="0:0:0.2"
FillBehavior="Stop"
Storyboard.TargetName="background"
Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
To="#FF0062B6"/>
</Storyboard.Children>
</Storyboard>
</ControlTemplate.Resources>
<ControlTemplate.Triggers>
<Trigger Property="ButtonBase.IsPressed" Value="True">
<Trigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource ButtonPressed}"/>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard Storyboard="{StaticResource ButtonReleased}"/>
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Resources>
<DockPanel>
<TextBlock x:Name="TextContent" FontSize="28" Foreground="White" >Test</TextBlock>
</DockPanel>
</Button>
</code></pre>
<p>Any suggestions from anyone who understands WPF and XAML a lot better than me?</p>
<p>Here is the error stacktrace:</p>
<pre><code>at System.Windows.Media.Animation.Storyboard.ResolveTargetName(String targetName, INameScope nameScope, DependencyObject element)
at System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer)
at System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer)
at System.Windows.Media.Animation.Storyboard.BeginCommon(DependencyObject containingObject, INameScope nameScope, HandoffBehavior handoffBehavior, Boolean isControllable, Int64 layer)
at System.Windows.Media.Animation.Storyboard.Begin(FrameworkElement containingObject)
at pk_rodoment.SkinningEngine.ButtonControlWPF._button_MouseDown(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at ControlTestbed.App.Main() in C:\svnprojects\rodomont\ControlsTestbed\obj\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
</code></pre>
| <p>Finally found it. When you call Begin on storyboards that reference elements in the ControlTemplate, you must pass in the control template as well.</p>
<p>Changing:</p>
<pre><code>pressedButtonStoryboard.Begin(_xamlButton);
</code></pre>
<p>To:</p>
<pre><code>pressedButtonStoryboard.Begin(_xamlButton, _xamlButton.Template);
</code></pre>
<p>Fixed everything.</p>
| <p>(@ Sam Meldrum) To get STOP working, add 'true for "isControllable" at the begin</p>
<pre><code>pressedButtonStoryboard.Begin(_xamlButton, _xamlButton.Template);
</code></pre>
<p>change to</p>
<pre><code>pressedButtonStoryboard.Begin(_xamlButton, _xamlButton.Template,true);
</code></pre>
<p>and now </p>
<pre><code>pressedButtonStoryboard.Stop(xamlButton)
</code></pre>
<p>will work</p>
| 18,287 |
<p>Are there any optimizations to consider when connecting to Oracle with NHibernate? My calls to Oracle are taking an extremely long time. If I run the NHibernate query (copied from my output window in Visual Studio) directly against Oracle, it comes right back in under a second. Here is my config file for NHibernate. I can post the mapping files if needed.</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="DefaultSessionFactory">
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.OracleDialect</property>
<property name="connection.driver_class">NHibernate.Driver.OracleClientDriver</property>
<property name="connection.connection_string">Data Source=****;Persist Security Info=True;User ID=******;Password=*******;Unicode=True</property>
<property name="show_sql">true</property>
<mapping assembly="AQTool.BL"/>
</session-factory>
</hibernate-configuration>
</code></pre>
<p>Update:
summarizing all the discussion here:</p>
<p>If I remove all the many-to-one relationships and just run my unit test against the single entity with no joins, the query still runs for over 2 minutes. If I copy the sql generated by nhibernate and run it directly against oracle, the query returns in under a second. I am posting my mapping file here as well. Is there anything I am missing that might be causing this disparity? The only thing I am doing is selecting by Account Id. Although the table is large (over 5M rows), the customer account id field is indexed, and the raw query comes back very quickly.</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="AQTool.BL" assembly="AQTool.BL" default-lazy="true">
<class name="AQTool.BL.EmailAddress,AQTool.BL" table="EMAIL_CUSTOMER_ADDRESSES">
<id name="EmailAddressId" column="EMAIL_ADDRESS_ID" type="int">
<generator class="native" />
</id>
<property name="CustomerAccountId" column="CUSTOMER_ACCOUNT_ID" type="string" />
<property name="EmailAddressText" column="EMAIL_ADDRESS_TX" type="string" />
<property name="EmailAddressTypeId" column="EMAIL_ADDRESS_TYPE_ID" type="int" />
<property name="EmailAddressTypeIdInternal" column="EMAIL_ADDRESS_TYPE_ID_INTERNAL" type="int" />
</class>
</hibernate-mapping>
</code></pre>
| <p>You may consider using this tool for "debugging NHibernate"
<a href="http://ayende.com/projects/nhibernate-query-analyzer.aspx" rel="nofollow noreferrer">NHibernate Query Analyzer</a></p>
| <p>Make sure your connection pool is sufficiently large. Also, if you try debugging your code, you should be able to see where Hibernate is spending the majority of its time. It may be with processing the results, as someone commented earlier, especially if you have cascading relationships. If you do, try running those queries using subselect instead of lazy=false or fetch=join, as that will likely be significantly faster.</p>
| 42,883 |
<p>I'm using C# with <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> 3.5. Is it possible to serialize a block of code, transmit it somewhere, deserialize it, and then execute it?</p>
<p>An example usage of this would be:</p>
<pre><code>Action<object> pauxPublish = delegate(object o)
{
if (!(o is string))
{
return;
}
Console.WriteLine(o.ToString());
};
Transmitter.Send(pauxPublish);
</code></pre>
<p>With some remote program doing:</p>
<pre><code>var action = Transmitter.Recieve();
action("hello world");
</code></pre>
<p>My end goal is to be able to execute arbitrary code in a different process (which has no prior knowledge of the code).</p>
| <p><strong>YES!!!</strong></p>
<p>We have done this for a very real case of performance. Doing this at runtime or using a DSL was not an option due to performance. </p>
<p>We compile the code into an assembly, and rip the IL out of the method. We then get all the metadata associated with this method and serialize the whole mess via XML, compress it, and put it in our database.</p>
<p>At re-hydration time, we re-constitute the IL with the metadata using the <strong>DynamicMethod</strong> class, and execute it.</p>
<p>We do this because of speed. We have thousands of little blocks of code. Unfortunately, to compile a block of code and run it on the fly takes at least 250 ms, which is way too slow for us. We took this approach, and it is working REALLY well. At run-time, it takes an unmeasurable amount of time to reconstitute the method and run it.</p>
<p>Only thing to keep an eye on... Signed assemblies and Unsigned assemblies cannot mix the serialized method data.</p>
| <p>Another option is using the <a href="http://en.wikipedia.org/wiki/Dynamic_Language_Runtime" rel="nofollow noreferrer">DLR</a>, and constraining the code to execute...</p>
| 45,038 |
<p>We just added an autoupdater in our software and got some bug report saying
that the autoupdate wouldn't complete properly because the downloaded file's sha1 checksum wasn't matching. We're hosted on Amazon S3...</p>
<p>That's either something wrong with my code or something wrong with S3.</p>
<p>I reread my code for suspicious stuff and wrote a simple script downloading and checking the checksum of the downloaded file, and indeed got a few errors once in while (1 out of 40 yesterday). Today it seems okay.</p>
<p>Did you experience that kind of problem? Is there some kind of workaround ?</p>
<p>extra info: test were ran in Japan.</p>
| <p>Amazon's S3 will occasionally fail with errors during uploads or downloads -- generally "500: Internal Server" errors. The error rate is normally pretty low, but it can spike if the service is under heavy load. The error rate is never 0%, so even at the best of times the occasional request will fail.</p>
<p>Are you checking the HTTP response code in your autoupdater? If not, you should check that your download succeeded (HTTP 200) before you perform a checksum. Ideally, your app should retry failed downloads, because transient errors are an unavoidable "feature" of S3 that clients need to deal with.</p>
<p>It is worth noting that if your clients are getting 500 errors, you will probably not see any evidence of these in the S3 server logs. These errors seem to occur before the request reaches the service's logging component.</p>
| <p>More than sending bad data, I think I got an ERROR403. If I just try again it's usually ok.</p>
<p>And I agree : I saw a lot of report about people talking about amazon being totally down, but nobody talking about a "sometimes my access is refused" error, so I guess there might be an error on my side. I just set up the log on amazon.</p>
<p>Anyway thank you! I'll follow your advise and stop blaming "the other guy".</p>
| 5,141 |
<p>I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?</p>
<p>I'd prefer something using the standard library, but I can install a third-party package if necessary.</p>
| <p>I am assuming you mean using XSD files. Surprisingly there aren't many python XML libraries that support this. lxml does however. Check <a href="http://lxml.de/validation.html" rel="noreferrer">Validation with lxml</a>. The page also lists how to use lxml to validate with other schema types.</p>
| <pre class="lang-py prettyprint-override"><code>import xmlschema
def get_validation_errors(xml_file, xsd_file):
schema = xmlschema.XMLSchema(xsd_file)
validation_error_iterator = schema.iter_errors(xml_file)
errors = list()
for idx, validation_error in enumerate(validation_error_iterator, start=1):
err = validation_error.__str__()
errors.append(err)
print(err)
return errors
errors = get_validation_errors('sample3.xml', 'sample_schema.xsd')
</code></pre>
| 38,390 |
<p>Are there any utilities that can examine a set of managed assemblies and tell you whether any of the types in one namespace depend on any in another? For example, say I have a <code>MyApp.BusinessRules</code> namespace and don't want it to access directly anything in <code>MyApp.GUI</code>, but both namespaces are in the same assembly. My goal is to be able to write a custom MSBuild task that verifies that various coupling rules have not been broken.</p>
<p>So far the only tool I have come across that looks like it might do this is <a href="http://www.ndepend.com/" rel="noreferrer">NDepend</a>, but I am wondering if there is a simpler solution.</p>
| <blockquote>
<p>So far the only tool I have come across that looks like it might do this is NDepend, but I am wondering if there is a simpler solution.</p>
</blockquote>
<p>I am one of the developer of the tool <a href="http://www.NDepend.com" rel="nofollow noreferrer">NDepend</a>. Please could you let us know what do you find complicated in NDepend and how you imagine a simpler solution for you?</p>
<p>NDepend comes with 3 different ways to do what you want: <a href="http://www.ndepend.com/Doc_Matrix.aspx" rel="nofollow noreferrer">Dependency Matrix</a>, <a href="http://www.ndepend.com/Doc_VS_Arch.aspx" rel="nofollow noreferrer">Dependency Graph</a> and also you can write some <a href="http://www.ndepend.com/Features.aspx#CQL" rel="nofollow noreferrer">Code Rule over LINQ Query (CQLinq)</a> and rules to <a href="http://www.ndepend.com/DefaultRules/webframe.html?Q_Avoid_namespaces_dependency_cycles.html" rel="nofollow noreferrer">detect cycle between namespaces</a>, or enforce some particular dependencies.</p>
<blockquote>
<p>For example, say I have a MyApp.BusinessRules namespace and don't want it to access directly anything in MyApp.GUI, but both namespaces are in the same assembly. </p>
</blockquote>
<p>For that, the following CQLinq rule can be written, could it be any simpler than that?:</p>
<pre><code>warnif count > 0
let businessRules = Application.Namespaces.WithNameLike("^MyApp.BusinessRules")
let gui = Application.Namespaces.WithNameLike("^MyApp.GUI")
from n in businessRules.UsingAny(gui)
let guidNamespacesUsed = n.NamespacesUsed.Intersect(gui)
select new { n, guidNamespacesUsed }
</code></pre>
| <p>Reflector does this.</p>
<p>Right click namespace, click Analyze, viola! :)</p>
| 39,211 |
<p>I am new to Java and am trying to run a program using Eclipse. But I have no idea how to get the command prompt running in with Eclipse...</p>
<p>I did some online research and couldn't get anything consolidated!</p>
<h3>Update:</h3>
<p>I'm not using an applet. It's a normal Java program trying to read a line from command prompt. I'm trying to do system programming.</p>
| <p>Check out this lesson plan on how to get started with Eclipse programs:</p>
<p><a href="http://www.ics.uci.edu/~thornton/ics22/LabManual/Lab0/" rel="nofollow noreferrer">Lesson</a></p>
<p>Specifically, see this image:</p>
<p><img src="https://www.ics.uci.edu/~thornton/ics22/LabManual/Lab0/Eclipse-ConsoleTab-Stopped.png" width="640" alt="Picture of Eclipse Console with Standard Input"></p>
<p>If the Console tab is not visible in your Eclipse, go to Window -> Show View -> Console in the menu bar.</p>
| <p>If you downloaded the Eclipse/Java package, and you wrote a Java program in Eclipse in a project, just click compile and run, it will run in the output window in Eclipse.</p>
| 24,304 |
<p>Has anyone attempted this? Is it possible, and if so, what kind of problems will I run into if I try to accomplish it?</p>
| <p>I have put an additional layer between the AppController and some special controllers in an app.</p>
<p>The only problem you'll run into is the merging of the $helpers and $components class attributes. In CakePHP, overriding those variables in your controllers will <em>not</em> overwrite those set by the AppController, but it will merge them. </p>
<p>This is done by a special method named __mergeVars() in the Controller base class, and it unfortunately does it only for the default controller structure. Your additional layer will not be merged correctly, if you want $helpers and $controllers inheritance from AppController down to your controllers.</p>
| <p>Why not try? At least, it's already being done with the Controller -> AppController -> MyController classes.</p>
| 47,020 |
<p>I have a problem with how ASP.Net generates the <strong>img</strong> tag.
I have a server control like this: </p>
<pre><code><asp:Image runat="server" ID="someWarning" ImageUrl="~/images/warning.gif" AlternateText="Warning" />
</code></pre>
<p>I expect it to generate this: </p>
<pre><code><img id="ctl00_ContentPlaceHolder1_ctl00_someWarning" src="../images/warning.gif" />
</code></pre>
<p>but instead it generates this:</p>
<pre><code><img alt="" src="/Image.ashx;img=%2fimages%2fwarning.gif"</img>
</code></pre>
<p>This give me errors when I execute the following js:</p>
<pre><code>document.getElementById('ctl00_ContentPlaceHolder1_someWarning')
</code></pre>
<p>Any idea why it won't generate the expected html?</p>
| <p>Looks like it's trying to use a custom handler (ashx) to deliver the image. Do you have any additional modules that may be overriding the default behaviour of the asp:Image?</p>
<p>Your JavaScript won't work because the image tag has not been given an ID in the HTML that was generated.</p>
| <p>You can get the actual ID that is generated by using ClientID. I use this to get the ID of a control for use in JavaScript using syntax similar to the following:</p>
<pre><code>document.getElementById('<%=ddlCountry.ClientID%>').style.display = "block";
</code></pre>
<p>However you can also use it in your code-behind to get the same thing.</p>
| 30,562 |
<p>Is there any Visual Studio Add-In that can do the remove method refactoring?<br>
Suppose you have the following method: </p>
<pre><code>Result DoSomething(parameters)
{
return ComputeResult(parameters);
}
</code></pre>
<p>Or the variant where Result is void.</p>
<p>The purpose of the refactoring is to replace all the calls to DoSomething with calls to ComputeResult or the expression that uses the parameters if ComputeResult is not a method call.</p>
| <p>If I understand the question, then Resharper calls this 'inline method' - <kbd>Ctrl</kbd> - <kbd>R</kbd> + <kbd>I</kbd></p>
| <p>You can also right click the method name and click "Find all References" in Visual Studio.</p>
<p>I personally would just do a <kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>H</kbd> to <code>Find & Replace</code></p>
| 3,000 |
<p>I've been researching memory mapped files for a project and would appreciate any thoughts from people who have either used them before, or decided against using them, and why?</p>
<p>In particular, I am concerned about the following, in order of importance:</p>
<ul>
<li>concurrency</li>
<li>random access</li>
<li>performance</li>
<li>ease of use</li>
<li>portability</li>
</ul>
| <p>I think the advantage is really that you reduce the amount of data copying required over traditional methods of reading a file.</p>
<p>If your application can use the data "in place" in a memory-mapped file, it can come in without being copied; if you use a system call (e.g. Linux's pread() ) then that typically involves the kernel copying the data from its own buffers into user space. This extra copying not only takes time, but decreases the effectiveness of the CPU's caches by accessing this extra copy of the data.</p>
<p>If the data actually have to be read from the disc (as in physical I/O), then the OS still has to read them in, a page fault probably isn't any better performance-wise than a system call, but if they don't (i.e. already in the OS cache), performance should in theory be much better.</p>
<p>On the downside, there's no asynchronous interface to memory-mapped files - if you attempt to access a page which isn't mapped in, it generates a page fault then makes the thread wait for the I/O.</p>
<hr>
<p>The obvious disadvantage to memory mapped files is on a 32-bit OS - you can easily run out of address space.</p>
| <p>Concurrency would be an issue.
Random access is easier
Performance is good to great.
Ease of use. Not as good.
Portability - not so hot.</p>
<p>I've used them on a Sun system a long time ago, and those are my thoughts.</p>
| 23,392 |
<p>Parameterized Queries in .Net always look like this in the examples:</p>
<pre><code>SqlCommand comm = new SqlCommand(@"
SELECT *
FROM Products
WHERE Category_ID = @categoryid
",
conn);
comm.Parameters.Add("@categoryid", SqlDbType.Int);
comm.Parameters["@categoryid"].Value = CategoryID;
</code></pre>
<p>But I'm running into a brick wall trying to do the following:</p>
<pre><code>SqlCommand comm = new SqlCommand(@"
SELECT *
FROM Products
WHERE Category_ID IN (@categoryids)
OR name LIKE '%@name%'
",
conn);
comm.Parameters.Add("@categoryids", SqlDbType.Int);
comm.Parameters["@categoryids"].Value = CategoryIDs;
comm.Parameters.Add("@name", SqlDbType.Int);
comm.Parameters["@name"].Value = Name;
</code></pre>
<p>Where</p>
<ul>
<li>CategoryIDs is a comma separated list of numbers "123,456,789" (without quotes)</li>
<li>Name is a string, possibly with single quotes and other bad characters</li>
</ul>
<p>What's the right syntax for this?</p>
| <p>Let's say that you have your category ids in an integer array and Name is a string. The trick is to create the command text to allow you to enter all of your category ids as individual parameters and construct the fuzzy match for name. To do the former, we use a loop to construct a sequence of parameter names @p0 through @pN-1 where N is the number of category ids in the array. Then we construct a parameter and add it to the command with the associated category id as the value for each named parameter. Then we use concatenation on the name in the query itself to allow the fuzzy search on name.</p>
<pre><code>string Name = "someone";
int[] categoryIDs = new int[] { 238, 1138, 1615, 1616, 1617,
1618, 1619, 1620, 1951, 1952,
1953, 1954, 1955, 1972, 2022 };
SqlCommand comm = conn.CreateCommand();
string[] parameters = new string[categoryIDs.Length];
for(int i=0;i<categoryIDs.Length;i++)
{
parameters[i] = "@p"+i;
comm.Parameters.AddWithValue(parameters[i], categoryIDs[i]);
}
comm.Parameters.AddWithValue("@name",$"%{Name}%");
comm.CommandText = "SELECT * FROM Products WHERE Category_ID IN (";
comm.CommandText += string.Join(",", parameters) + ")";
comm.CommandText += " OR name LIKE @name";
</code></pre>
<p>This is a fully parameterized query that should make your DBA happy. I suspect that since these are integers, though it would not be much of a security risk just to construct the command text directly with the values, while still parameterizing the name. If your category ids are in a string array, just split the array on commas, convert each to an integer, and store it in the integer array.</p>
<p><strong>Note:</strong> I say array and use it in the example, but it should work for any collection, although your iteration will probably differ.</p>
<p>Original idea from <a href="http://www.tek-tips.com/viewthread.cfm?qid=1502614&page=9" rel="noreferrer">http://www.tek-tips.com/viewthread.cfm?qid=1502614&page=9</a></p>
| <p>This approach will not work. Period.</p>
<p>The IN clause expects a list of parameters itself, so when you bind <em>one</em> parameter to it, you have the chance to pass in <em>one</em> value.</p>
<p>Build your statement string dynamically, with the exact amount of individual IN clause placeholders you intend to pass in, and then add parameters and bind values to them in a loop.</p>
| 38,944 |
<p>I would like to create data visualizations in desktop apps, using frameworks, languages and libraries that help with this kind of task. Visualizations should be interactive: clickable, draggable, customizable, animated...</p>
<p>What I would like to create is something similar to the examples seen here: <a href="http://www.visualcomplexity.com/vc/" rel="nofollow noreferrer">http://www.visualcomplexity.com/vc/</a></p>
<p>These are the links I already know: <a href="http://delicious.com/laura_laura/visualization?setcount=100" rel="nofollow noreferrer">http://delicious.com/laura_laura/visualization?setcount=100</a></p>
<p>The preferred language is C++/Visual C++ (MFC) because I'm familiar with it, but any other technology is welcome, I would like to make a list from "as similar as possible" to Visual C++ to "very different" from Visual C++.</p>
<p>WPF, flex, Adobe Air, flare, JavaScript (running in a browser as client-side apps with access to local files or as desktop apps) are possibilities, post any good links to examples, tutorials, how-tos, etc. that you know of.</p>
<p>What are the learning curves and complexity for the different options? Which one would you choose and why? Which one have you already worked with and how was your experience? How would you start with a project of this characteristics?</p>
| <p>Your post has far too many questions in it to be answered easily in one response, so you might try re-posting with specific questions. Data visualization is a HUGE area of study and it's not significantly different for web applications versus desktop applications. </p>
<p>Put simply, it's the display of data in a way that visually tells the story of the data. It's most useful in cases where the volume of data is such that tabular display isn't effective. Trends, outliers, and abnormal occurrences can sometimes only be seen when data is represented visually. Visually can be a simple chart, or it can be more advanced visualizations such as treemaps or thematic mapping/GIS presentations.</p>
<p>If it's an area you're interested in studying, look into:</p>
<p><a href="http://www.edwardtufte.com/tufte/" rel="noreferrer">Edward Tufte</a> - Author, professor, and all-around guru for the display of information</p>
<p><a href="http://services.alphaworks.ibm.com/manyeyes/home" rel="noreferrer">Many Eyes</a> - from IBM AlphaWorks</p>
<p><a href="http://www.processing.org" rel="noreferrer">Processing</a> - A visual "sketching" language based on Java</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0596514557" rel="noreferrer" rel="nofollow noreferrer">Visualizing Data</a> - An O'Reilly book by Ben Fry, one of the co-creators of Processing</p>
<p>Beyond that, I think specifics would depend on what you want to accomplish -- what data is being analyzed, who the audience is, and what the desired "message" is.</p>
| <p>If you're willing to use the Flash/Flex/ActionScript/AIR development platform, then take a look at the "flare" library, from the prefuse project:</p>
<p><a href="http://flare.prefuse.org/" rel="nofollow noreferrer">http://flare.prefuse.org/</a></p>
<p>I've only gotten my feet wet with it at this point, but so far I like what I see.</p>
| 15,887 |
<p>How can I setup a shared ccache without falling into a permissions problem?</p>
<p>I would like to run a nightly or CI build with latest changes and share all created binaries throughout the R&D using a large ccache repository.</p>
| <p>See the newly written <a href="https://ccache.dev/manual/3.7.11.html#_sharing_a_cache" rel="nofollow noreferrer">Sharing a cache</a> section in ccache's manual. In essence, use the same <code>CCACHE_DIR</code> setting, set <code>CCACHE_UMASK</code> appropriately and consider using <code>CCACHE_BASEDIR</code>.</p>
| <p>If you also use the related <a href="http://distcc.samba.org/" rel="nofollow noreferrer">distcc</a>, then the permission problems would largely go away, as the compilations would be run under it's control on whatever compile-farm hosts you set.</p>
<p>You could also include the developers desktop machines among the distcc hosts, though at the expense of having some duplicated work where a file would potentially be compiled on more than one machine - though it would never return an out of date compiled object file. It would also speed up day to day recompilations.</p>
| 14,592 |
<p>I am looking for a very fast way to filter down a collection in C#. I am currently using generic <code>List<object></code> collections, but am open to using other structures if they perform better.</p>
<p>Currently, I am just creating a new <code>List<object></code> and looping thru the original list. If the filtering criteria matches, I put a copy into the new list.</p>
<p>Is there a better way to do this? Is there a way to filter in place so there is no temporary list required?</p>
| <p>If you're using C# 3.0 you can use linq, which is way better and way more elegant:</p>
<pre class="lang-c# prettyprint-override"><code>List<int> myList = GetListOfIntsFromSomewhere();
// This will filter ints that are not > 7 out of the list; Where returns an
// IEnumerable<T>, so call ToList to convert back to a List<T>.
List<int> filteredList = myList.Where(x => x > 7).ToList();
</code></pre>
<p>If you can't find the <code>.Where</code>, that means you need to import <code>using System.Linq;</code> at the top of your file.</p>
| <p>If your list is very big and you are filtering repeatedly - you can sort the original list on the filter attribute, binary search to find the start and end points.</p>
<p>Initial time O(n*log(n)) then O(log(n)).</p>
<p>Standard filtering will take O(n) each time.</p>
| 4,581 |
<p>Are there are good uses of Partial Classes outside the webforms/winforms generated code scenarios? Or is this feature basically to support that?</p>
| <p>It is in part to support scenarios (WebForms, WinForms, LINQ-to-SQL, etc) mixing generated code with programmer code.</p>
<p>There are more reasons to use it. For example, if you have big classes in large, unwieldy files, but the classes have groups of logically related methods, partial classes may be an option to make your file sizes more manageable.</p>
| <p>Correction, as Matt pointed out, both sides of the partial need to be in the same assembly.
my bad.</p>
| 19,406 |
<p>I have a php page that displays rows from a mysql db as a table. One of the fields contains HTML markup, and I would like to amke this row clickable and the html would open in a new popup window. What is the best way to do it, and is there a way to do it without writing the html to a file?</p>
<p>edit: this php page is actually part of an ajax app, so that is not a problem. I do not want to use jquery, as I would have to rewrite the application.</p>
<p>edit:</p>
<p>I have tried this again using the example below, and have failed. I know my script tag is wrong, but I am just echoing out row2 at the moment, so I think my logic is wrong before it ever gets to the javascript.</p>
<pre><code>$sql="SELECT * FROM Auctions WHERE ARTICLE_NO ='$pk'";
$sql2="SELECT ARTICLE_DESC FROM Auctions WHERE ARTICLE_NO ='$pk'";
$htmlset = mysql_query($sql2);
$row2 = mysql_fetch_array($htmlset);
echo $row2;
/*echo '<script> child1 = window.open ("about:blank")
child1.document.write("$row2['ARTICLE_DESC']");
child1.document.close()*/
</code></pre>
| <pre><code>child1 = window.open ("about:blank")
child1.document.write("Moo!");
child1.document.close()
</code></pre>
| <p>If you don't require a browser window (this suggestion involves a css modal box), you might want to consider one of the "lightbox" variations. </p>
<p><a href="http://jquery.com/demo/thickbox/" rel="nofollow noreferrer">Thickbox</a> can be used to load inline content from the page into a modal window. The link provides demo/details in how to implement inline content as well as other variations.</p>
| 42,208 |
<p>I'm doing some maintenance coding on a webapp and I am getting a javascript error of the form: "[elementname] has no properties"</p>
<p>Part of the code is being generated on the fly with an AJAX call that changes innerHTML for part of the page, after this is finished I need to copy a piece of data from a hidden input field to a visible input field.
So we have the destination field: <code><input id="dest" name="dest" value="0"></code>
<br>And the source field: <code><input id="source" name="source" value="1"></code>
<br>Now when the ajax runs it overwrites the innerHTML of the div that source is in, so the source field now reads: <code><input id="source" name="source" value="2"></code></p>
<p>Ok after the javascript line that copies the ajax data to innerHTML the next line is:
<code>document.getElementById('dest').value = document.getElementById('source').value;</code></p>
<p>I get the following error: <code>Error: document.getElementById("source") has no properties</code></p>
<p>(I also tried <code>document.formname.source</code> and <code>document.formname.dest</code> and same problem)</p>
<p>What am I missing?</p>
<p>Note1: The page is fully loaded and the element exists. The ajax call only happens after a user action and replaces the html section that the element is in.</p>
<p>Note2: As for not using innerHTML, this is how the codebase was given to me, and in order to remove it I would need to rewrite all the ajax calls, which is not in the scope of the current maintenance cycle.</p>
<p>Note3: the innerHTML is updated with the new data, a whole table with data and formatting is being copied, I am trying to add a boolean to the end of this big chunk, instead of creating a whole new ajax call for one boolean. It looks like that is what I will have to do... as my hack on the end then copy method is not working.</p>
<p>Extra pair of eyes FTW.</p>
<p>Yeah I had a couple guys take a look here at work and they found my simple typing mistake... I swear I had those right to begin with, but hey we live and learn...</p>
<p>Thanks for the help guys.</p>
| <p>"[elementname] has no properties" is javascript error speak for "the element you tried to reference doesn't exist or is nil"</p>
<p>This means you've got one or more of a few possible problems:</p>
<ol>
<li>Your page hasn't rendered yet and you're trying to reference it before it exists</li>
<li>You've got a spelling error</li>
<li>You've named your id the same as a reserved word (submit on a submit button for instance)</li>
<li>What you think you're referencing you're really not (a passed variable that isn't what you think you're passing)</li>
</ol>
| <p>Generally you shouldn't use innerHTML, but create elements using DOM-methods. I cannot say if this is your problem.</p>
| 17,031 |
<p>I have a C++ DLL including bitmap resources created by Visual Studio.</p>
<p>Though I can load the DLL in VB6 using LoadLibrary, I cannot load the image resources either by using LoadImage or by using LoadBitmap. When I try to get the error using GetLastError(), it doesnot return any errors.</p>
<p>I have tried using LoadImage and LoadBitmap in another C++ program with the same DLL and they work without any problems.</p>
<p>Is there any other way of accessing the resource bitmaps in C++ DLLs using VB6?</p>
| <p>Since you are using the numeric ID of the bitmap as a string, you have to add a "#" in front of it:</p>
<pre><code>DLLHandle = LoadLibrary("Mydll.dll")
myimage = LoadBitmap(DLLHandle, "#101") ' note the "#"
</code></pre>
<p>In C++ you could also use the MAKEINTRESOURCE macro, which is simply a cast to LPCTSTR:</p>
<pre><code>imagehandle = LoadBitmap(DLLHandle, MAKEINTRESOURCE(101));
</code></pre>
| <p>You've got the right idea. You probably have the call wrong. Perhaps you could show a bit of code as I can't guess as to what you're passing.</p>
| 44,893 |
<p>I would like to use anti virus integration with my .net application when uploading files using the application. Has any anti virus API available for .Net?</p>
| <p>I don't want to resurrect an old question, but I was in need of a solution that the question was asking about. I evaluated a lot of things and came to the conclusion that there was really not one good .NET library for this. So I made my own.</p>
<p>The library is called nClam, and it connects to a ClamAV server. It is open-source (Apache License 2.0) library which has a very simple API. You can obtain it here: <a href="https://github.com/tekmaven/nClam" rel="noreferrer">https://github.com/tekmaven/nClam</a>. There is also a nuget package: nClam.</p>
<p>I hope someone who stumbles on this question in the future benefits from my library! </p>
| <p>I recommend you a nuget called anti-virus scanner, with that you can do it with ease <a href="https://www.nuget.org/packages/AntiVirusScanner/" rel="nofollow noreferrer">https://www.nuget.org/packages/AntiVirusScanner/</a>
This nuget basically calls microsoft windows defender apis.</p>
| 23,575 |
<p>I'm calling a WebService exposed by Oracle that accepts an input of an ItemID and returns to me the corresponding Item Number. I want to grab the Item Number that has been returned out of the XML contained in the response.</p>
<p>The XML looks like this:</p>
<pre><code><env:Envelope
xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ns0="http://dev1/MyWebService1.wsdl">
<env:Header>
<wsse:Security
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
env:mustUnderstand="1"/>
</env:Header>
<env:Body>
<ns0:getItemNbrByItemIdResponseElement>
<ns0:result>1010603</ns0:result>
</ns0:getItemNbrByItemIdResponseElement>
</env:Body>
</env:Envelope>
</code></pre>
<p>I'm interested in grabbing only the <code><ns0:result>1010603</ns0:result></code> particularly only the 1010603.</p>
<p>I haven't done a lot of work parsing XML using C# and I'm playing around with a few different methods so far. What is the recommended way to do this?</p>
<p>I'm on VS2008 (so XPath is available etc.)</p>
| <p>I'd personally use LINQ to XML, because I find that easier to deal with than XPath, particularly when namespaces are involved. You'd do something like:</p>
<pre><code>XNamespace ns0 = "http://dev1/MyWebService1.wsdl";
String result = doc.Descendants(ns0 + "result").First().Value;
</code></pre>
<p>Note that <code>doc</code> here is expected to be an <a href="http://msdn.microsoft.com/en-us/library/bb345449.aspx" rel="nofollow noreferrer"><code>XDocument</code></a>, <em>not</em> an <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx" rel="nofollow noreferrer"><code>XmlDocument</code></a>. (My guess is that this is why it wasn't showing up for you.)</p>
| <p>There are very good and complete answers to this question.</p>
<p>I'd add <strong>just out of curiosity, that an extremely simple XPath expression does the job</strong> in this particular case:</p>
<p> <strong><code>normalize-space(/)</code></strong></p>
<p>This is easily done in C# using something like the two lines below:</p>
<pre><code> XPathNavigator navigator = document.CreateNavigator();
string res = (string)navigator.Evaluate("normalize-space(/)");
</code></pre>
<p>With the good optimization of the .NET XPath engine, its evaluation may even be efficient.</p>
| 49,014 |
<p>What's a good way to survive abnormally high traffic spikes?</p>
<p>My thought is that at some trigger, my website should temporarily switch into a "low bandwidth" mode: switch to basic HTML pages, minimal graphics, disable widgets that might put unnecessary load on the database, and so-on.</p>
<p>My thoughts are:</p>
<ul>
<li>Monitor CPU usage</li>
<li>Monitor bandwidth</li>
<li>Monitor requests / minute</li>
</ul>
<p>I am familiar with options like caching, switching to static content or a content delivery network, and so on as a means to survive, so perhaps the question should focus more on how one detects when the website is about to become overloaded. (Although answers on other survival methods are of course still more than welcome.) Lets say that the website is running Apache on Linux and PHP. This is probably the most common configuration and should allow the maximum number of people to gain assistance from the answers. Lets also assume that expensive options like buying another server and load balancing are unavailable - for most of us at least, a mention on Slashdot is going to be a once-in-a-lifetime occurrence, and not something we can spend money preparing for.</p>
| <p>The basics:</p>
<ol>
<li>Don't try to host high-volume sites on Windows unless you are a <em>true</em> Windows guru. It can be done, but it's a time versus cost issue.</li>
<li>Use static content (i.e., no database queries) everywhere you can.</li>
<li>Learn about cache-control headers and use them properly for images and other static assets.</li>
<li>At the very least, use Apache, but if you can, use lighttpd or another high-performance webserver.</li>
</ol>
<p>The real answers:</p>
<ol>
<li>Really know your SQL, and spend time analyzing slow queries. Most page loads shouldn't require more than a second of straight queries.</li>
<li>Determine where your load really is. If it's a media-heavy site, consider hosting content elsewhere (like Akamai, or some other service). If it's a database-heavy site, consider replication.</li>
<li>Know what kind of replication will work for you. If you have a read-heavy site, standard MySQL master/slave replication should be fine. If you have a lot of writes going on, you'll need some kind of multi-master setup, like MySQL Cluster (or investigate 'cascading' or 'waterfall' replication).</li>
<li>If you can, avoid calling PHP - i.e. have a cached static (HTML) copy of the page (which is what most of the Wordpress caching plugins do). Apache is much faster serving static files than even the simplest hello world PHP script.</li>
</ol>
| <p>No one has mentioned load balancing... haproxy, etc. Optimize, cache and load balance should survive almost anything. That being said, I'm not sure if stackoverflow is behind a load balancer ;)</p>
| 26,856 |
<p>I need to move entire tables from one MySQL database to another. I don't have full access to the second one, only phpMyAdmin access. I can only upload (compressed) sql files smaller than 2MB. But the compressed output from a mysqldump of the first database's tables is larger than 10MB.</p>
<p>Is there a way to split the output from mysqldump into smaller files? I cannot use split(1) since I cannot cat(1) the files back on the remote server.</p>
<p>Or is there another solution I have missed?</p>
<p><strong>Edit</strong></p>
<p>The --extended-insert=FALSE option to mysqldump suggested by the first poster yields a .sql file that can then be split into importable files, provided that split(1) is called with a suitable --lines option. By trial and error I found that bzip2 compresses the .sql files by a factor of 20, so I needed to figure out how many lines of sql code correspond roughly to 40MB.</p>
| <p>First dump the schema (it surely fits in 2Mb, no?)</p>
<pre><code>mysqldump -d --all-databases
</code></pre>
<p>and restore it.</p>
<p>Afterwards dump only the data in separate insert statements, so you can split the files and restore them without having to concatenate them on the remote server</p>
<pre><code>mysqldump --all-databases --extended-insert=FALSE --no-create-info=TRUE
</code></pre>
| <p>Try csplit(1) to cut up the output into the individual tables based on regular expressions (matching the table boundary I would think).</p>
| 16,100 |
<p>I am working with some CSS that is poorly written to say the least. I am not a design/CSS expert, but I at least understand the <strong>C</strong> in CSS. While the builtin CSS support inside of VS-2008 is far improved over previous versions, it still doesn't quite do what I am looking for.</p>
<p>I was wondering if anyone know of a good program or utility that will help me to refactor and clean up my CSS like what ReSharper allows to do with C#.</p>
<p>Some features that would be nice to have:</p>
<ul>
<li>Examine CSS files and determine ways to extract common styles like font-style, color, etc... </li>
<li>Plugin to VS-2008 would be awesome!</li>
<li>Examine markup files and make some suggestions on improving the current use of classes and styles.</li>
</ul>
| <p>The <a href="https://addons.mozilla.org/en-US/firefox/addon/5392" rel="noreferrer">Dust-Me Selectors Firefox extension</a> can scan a website and tell you what CSS is used and what is not. Removing unused CSS is one good first step in refactoring.</p>
<p>I have often found that when some section is removed from a website, the HTML is removed but the CSS is not.</p>
| <p>I like Expression Web's CSS facilities. But it doesn't do much for minimizing or unifying your CSS. You have to understand how CSS works to use it properly.</p>
| 13,957 |
<p>Using Flex 3, I have a Button which is skinned using PNGs specified in a CSS style sheet.</p>
<pre><code>Button.addextra {
downSkin : Embed( source="img/add-extra-icon.png" );
overSkin : Embed( source="img/add-extra-icon.png" );
upSkin : Embed( source="img/add-extra-icon.png" );
disabledSkin : Embed( source="img/add-extra-icon-disabled.png" );
}
</code></pre>
<p>My designer colleague would like to add a rollover effect of a hairline #999999 line outside the image. Is this possible (without creating a new overSkin png) using the standard Flex styles?</p>
| <p>I believe you will need to change the overSkin, i think that would be the only way.</p>
| <p>I believe you will need to change the overSkin, i think that would be the only way.</p>
| 38,125 |
<p>Pretty basic question, I'm trying to write a regex in Vim to match any phrase starting with <code>"abc "</code> directly followed by anything other than <code>"defg"</code>. </p>
<p>I've used <code>"[^defg]"</code> to match any single character other than d, e, f or g.</p>
<p>My first instinct was to try <code>/abc [^\(defg\)]</code> or <code>/abc [^\<defg\>]</code> but neither one of those works.</p>
| <p>Here's the search string.</p>
<pre><code>/abc \(defg\)\@!
</code></pre>
<p>The concept you're looking for is called a negative look-ahead assertion. Try this in vim for more info:</p>
<pre><code>:help \@!
</code></pre>
| <p>/abc\ [^d][^e][^f][^g]</p>
<p>It's pretty cumbersome for larger words, but works like a charm.</p>
| 12,232 |
<pre><code>
class C {
public
T x;
};
</code></pre>
<p>Is there an elegant way for the constructor of x to know <strong>implicitly</strong> in what instance of C it is constructing?
<hr>
I've implemented such behavior with some dirty inelegant machinery. I need this for my sqlite3 wrapper. I don't like all wrappers I've seen, their API IMO ugly and inconvenient. I want something like this:</p>
<pre><code>
class TestRecordset: public Recordset {
public:
// The order of fields declarations specifies column index of the field.
// There is TestRecordset* pointer inside Field class,
// but it goes here indirectly so I don't have to
// re-type all the fields in the constructor initializer list.
Field<__int64> field1;
Field<wstring> field2;
Field<double> field3;
// have TestRecordset* pointer too so only name of parameter is specified
// in TestRecordset constructor
Param<wstring> param;
virtual string get_sql() {
return "SELECT 1, '1', NULL FROM test_table WHERE param=:PARAM";
}
// try & unlock are there because of my dirty tricks.
// I want to get rid of them.
TestRecordset(wstring param_value)
try : Recordset(open_database(L"test.db")), param("PARAM") {
param = param_value;
// I LOVE RAII but i cant use it here.
// Lock is set in Recordset constructor,
// not in TestRecordset constructor.
unlock(this);
fetch();
} catch(...) {
unlock(this);
throw;
}
};
<code></pre>
<p>I want to clarify the fact - it is a part of the <i>working</i> code. You <i>can</i> do this in C++. I just want to do it in a more nice way.
<hr>
I've found a way to get rid of unlock and try block. I've remembered there is such a thing as thread local storage. Now I can write constructor as simple as that:</p>
<pre>
TestRecordset(wstring param_value):
Recordset(open_database(L"test.db")), param("PARAM") {
param = param_value;
fetch();
}
</code></pre>
<p><hr>
to dribeas:
My objective is to avoid redundant and tedious typing. Without some tricks behind the scene I will have to type for each Field and Param:</p>
<pre>
TestRecordset(wstring param_value): Recordset(open_database(L"test.db")), param(this, "PARAM"),
field1(this, 0), field2(this, 1), field3(this, 2) { ... }
</code></pre>
<p>It is redundant, ugly and inconvenient. For example, if I'll have to add new field in the
middle of SELECT I'll have to rewrite all the column numbers.
Some notes on your post:</p>
<ol>
<li>Fields and Params <i>are</i> initialized by their default constructors.</li>
<li>Order of initializers in constructor is irrelevant. Fields are always initialized in order of their declaration. I've used this fact to track down column index for fields</li>
<li>Base classes are constructed first. So when Fields are constructed internal field list in Recordset are ready to use by Filed default constructor.</li>
<li>I CAN'T use RAII here. I need to acquire lock in Recorset constructor and release it obligatory in TestRecordset constructor <i>after all Fields are constructed</i>.</li>
</ol>
| <p>No. Objects aren't supposed to need to know where they're being used from in order to work. As far as x is concerned, it's an instance of T. That's it. It doesn't behave differently according to whether it's a member of class C, a member of class D, an automatic, a temporary, etc.</p>
<p>Furthermore, even if the T constructor did know about the instance of C, that instance of C would be incomplete since of course it has not finished construction yet, because its members haven't been constructed. C++ offers you plenty of chances to shoot yourself in the foot, but offering you a reference to an incomplete object in another class's constructor isn't one of them.</p>
<p>The only thing I can think of to approximate your code example is to do something like</p>
<pre><code>#define INIT_FIELDS field1(this), field2(this), field3(this)
</code></pre>
<p>immediately after the list of fields, then use INIT_FIELDS in the initializer list and #undef it. It's still duplication, but at least it's all in one place. This will probably surprise your colleagues, however.</p>
<p>The other way to make sure you don't forget a field is to remove the zero-arg constructor from Field. Again, you still have to do the typing, but at least if you forget something the compiler will catch it. The non-DRY nature of initializer lists is, I think, something C++ just has to live with.</p>
| <p>I experiment with things like this in C# all the time - I use reflection to do it.</p>
<p>Consider getting a reflection or code generation library for C++ to help you do what you want to.</p>
<p>Now, I can't tell you how to find a good reflection or code generation library for C++, but that's a different question!</p>
| 43,908 |
<p>I ran accross a CSR file (Certificate Signing Request) and I need to extract some information from it.</p>
<p>There's a way to decode it using .NET Framework?</p>
| <p>It's not .NET, but for interactive use, try the OpenSSL utilities. Specifically:</p>
<pre><code>openssl req -text -in request.csr
</code></pre>
| <p>Try <a href="http://lipingshare.com/Asn1Editor/" rel="nofollow noreferrer">Liping Dai's website</a>. His LCLib has ASN1 Parser which wrote in C#. It can decode CSR. Work for me. </p>
| 24,547 |
<p>I am using Context.RewritePath() in ASP.NET 3.5 application running on IIS7.</p>
<p>I am doing it in application BeginRequest event and everything works file.</p>
<p>Requests for /sports are correctly rewritten to default.aspx?id=1, and so on.</p>
<p>The problem is that in my IIS log I see GET requests for /Default.aspx?id=1 and not for /sports.</p>
<p>This kind of code worked perfectly under IIS6.</p>
<p>Using Microsoft Rewrite module is not an option, due to some business logic which has to be implemented.</p>
<p>Thanks.</p>
<p>EDIT: </p>
<p>It seems my handler is too early in the pipeline, but if I move the logic to a later event, than the whole rewrite thing doesn't work (it's too late, StaticFileHandler picks up my request). </p>
<p>I googled and googled, asked around, can't believe that nobody has this problem?</p>
<p>EDIT:</p>
<p>Yikes! Here's what I found on the IIS forum:</p>
<p>"This is because in integrated mode, IIS and asp.net share a common pipeline and the RewritePath is now seen by IIS, while in IIS6, it was not even seen by IIS - you can workaround this by using classic mode which would behave like IIS6."</p>
<p><strong>Final update</strong>: Please take a look at <a href="https://stackoverflow.com/questions/353541/iis7-rewritepath-and-iis-log-files/579141#579141">my answer below</a>, I've updated it with results after more than a year in production environment.</p>
| <p>After some research, I've finally found a solution to the problem.</p>
<p>I have replaced the calls to Context.RewritePath() method with the new (introduced in ASP.NET 3.5) <strong>Context.Server.TransferRequest()</strong> method.</p>
<p>It seems obvious now, but not event Senior Dev Engineer on IIS Core team thought of that.</p>
<p>I've tested it for session, authentication, postback, querystring, ... issues and found none.</p>
<p>Tommorow I'll deploy the change to a very hight traffic site, and we'll soon know how it actually works. :) </p>
<p>I'll be back with the update.</p>
<p><strong>The update:</strong> the solution is still not entirely on my production servers but it's tested and it does work and as far as I can tell so far, it's a solution to my problem. If I discover anything else in production, I will post an update.</p>
<p><strong>The final update:</strong> I have this solution in production for over a year and it has proven to be a good and stable solution without any problems.</p>
| <p>Old question, but I found I did not encounter your problem when I did the following:</p>
<p>a) A rewrite rule in web.config to direct all requests to /default.aspx, eg:</p>
<pre><code> <rule name="all" patternSyntax="Wildcard" stopProcessing="true">
<match url="*"/>
<action type="Rewrite" url="/default.aspx"/>
</rule>
</code></pre>
<p>b) Called RewritePath in the <code>Page_PreInit</code> event of default.aspx, to rewrite the URL and querystring as what was passed in the request (ie. the location that doesn't exist).</p>
<p>For example, I request "/somepage/?x=y" (which doesn't exist).</p>
<p>a) Web.config rule maps it to /default.aspx</p>
<p>b) Page_PreInit rewrites it back to "/somepage/?x=y".</p>
<p>The result of this, in IIS 7 (Express and production) is that the server log reflects "/somepage" for stub and "x=y" for query, and all the Request object properties reflect the requested (non-existent) URL (which is what I wanted).</p>
<p>The only weird effect is, in IIS Express, the log item is written twice. However this doesn't happen in production (Windows Server 2008 R2).</p>
| 46,045 |
<p>In Oracle we can print output by <code>dbms_output.put_line()</code> but I don't know to do the same thing in DB2.</p>
<p>I currently use <code>signal</code> for printing some messages when I debug.</p>
| <p>With Sharepoint Designer you can edit the CAML of your XSLT List View. </p>
<p>If you set the Scope attribute of the View element to <em>Recursive</em> or <em>RecursiveAll</em>, which returns all Files and Folders, you can filter the documents by <em>FileDirRef</em>:</p>
<pre><code><Where>
<Contains>
<FieldRef Name='FileDirRef' />
<Value Type='Lookup'>MyFolder</Value>
</Contains>
</Where>
</code></pre>
<p>This returns all documents which contain the string 'MyFolder' in their path. </p>
<p>I found infos about this on <a href="http://platinumdogs.wordpress.com/2009/07/21/querying-document-libraries-or-pulling-teeth-with-caml/" rel="noreferrer">http://platinumdogs.wordpress.com/2009/07/21/querying-document-libraries-or-pulling-teeth-with-caml/</a> and useful information abouts fields at <a href="http://blog.thekid.me.uk/archive/2007/03/21/wss-field-display-amp-internal-names-for-lists-amp-document-libraries.aspx" rel="noreferrer">http://blog.thekid.me.uk/archive/2007/03/21/wss-field-display-amp-internal-names-for-lists-amp-document-libraries.aspx</a> </p>
| <p>What kind of document library information do you want in the view?
How do you want the user to filter the view?</p>
<p>In general the most powerful way of creating views in sharepoint is with the data view web part.
<a href="http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx" rel="nofollow noreferrer">http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx</a></p>
<p>You will need Microsoft Office SharePoint Designer. </p>
<p>You can present different views of you folders using the data view filter and sorting controls.</p>
<p>You can use web part connections to filter a dataview.
You can use any datasource linked to say a drop down to filter a dataview.
<a href="https://stackoverflow.com/questions/177076/how-to-tie-a-dropdown-list-to-a-gridview-in-sharepoint-2007">How to tie a dropdown list to a gridview in Sharepoint 2007?</a></p>
| 37,760 |
<p>I'm currently working on a very short project on Prolog, and just got stuck trying to apply a "filter" I have created to a list. I have what you could call the filter ready, but I can't apply it. It'd be better if I illustrate:</p>
<pre><code>filter(A, B)
</code></pre>
<p>...outputs 'true' if certain conditions are met.</p>
<pre><code>filterList(A, [X, Y, Z])
</code></pre>
<p>...outputs a list which includes all elements from the second argument that make the filter output <strong>false</strong>. (So if filter(A, X) is true, the output is [Y, Z] ).</p>
<p>I have the "filter" function ready, but now I need to apply it to a list as shown on the second example, excluding all elements for which the filter returns true when applied with the first argument. </p>
<p>So, if the filter is a simple A == B, the function is supposed to receive A [A,B,A,C,D,A] and output [B,C,D], having removed all the elements for which the filter applies, obviously.</p>
<p>I'm having trouble with the basic structure of the function, so if anyone could supply a basic outline for a function such as this it would be of great help. I've simplified my situation as much as possible so I can take whatever you may be able to provide and modify it for my needs.</p>
<p>Thanks in advance!</p>
| <p>If you are searching for higher-order functions in Prolog, you should definetly consult <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.35.4505" rel="noreferrer">Naish (1995)</a>, a very good resource on this.</p>
<p><P>His definition of <code>filter/3</code> is the following (he uses difference-list notation, therefore escapes having to define <code>filter/4</code>):</P></p>
<pre><code>
filter(_,[],[]).
filter(P, A0-As0, As) :-
(
call(P, A0) -> As = A0-As1
;
As = As1
)
, filter(P, As0, As1).
</code></pre>
<p>I you have questions about this predicate, please ask me in the comment. Reading the paper is also highly recommended, it also definess <code>map</code>, <code>foldr</code> and <code>compose</code>! Note that many of the limitations he mentions (like, for example a missing <code>call/3</code> or a higher-order <code>apply</code> do not apply anymore. SWI-Prolog has the <code>=..</code> operator, which addresses all of his concerns and makes arbitrary n-order logic possible.</p>
| <p>Well what'd you know I just figured it out. So, here's me submitting an answer to my own question, as expected a really short function did the job:</p>
<pre><code>filterList(_,[],R,R). % Returns answer when the list is exhausted.
filterList(L,[A|List],Temp,Res) :-
filterList(L,List,New,Res), % Recursive call, New is either the same list
( filter(L,A), % in case the filter outputs true, or the list
New = Temp
; New = [A|Temp] % plus the current element otherwise.
).
</code></pre>
| 38,135 |
<p>I have a class library with all my database logic. My DAL/BLL. </p>
<p>I have a few web projects which will use the same database and classes, so I thought it was a good idea to abstract the data layer into its own project.</p>
<p>However, when it comes to adding functionality to classes for certain projects I want to add methods to certain classes.</p>
<p>For example, my data layer has Product and SomeItem objects:</p>
<pre><code>// Data Access Layer project
namespace DAL {
public class Product {
//implementation here
}
public class SomeItem {
//implementation here
}
}
</code></pre>
<p>In one project I want to add an interface that is used by different content items, so I have a class called:</p>
<pre><code>// This is in Web Project
namespace DAL {
public partial class Product : ICustomBehaviour {
#region ICustomBehaviour Implementation
TheSharedMethod();
#endregion
}
}
</code></pre>
<p><strong>Is it a good idea to write a partial class in a separate project (creating a dependency) using the <em>same</em> namespace? If it's a bad idea, how can I get this type of functionality to work?</strong></p>
<p>It doesn't seem to want to merge them at compile time, so I'm not sure what I'm doing wrong.</p>
| <p>You can't write a partial class across projects. A partial class is a compile-time-only piece of syntactic sugar - the whole type ends up in a single assembly, i.e. one project.</p>
<p>(Your original DAL file would have to declare the class to be partial as well, by the way.)</p>
| <p>While I agree with you Neil when it comes to pre-linq development, I also wish I could be able to do this in order to split up bussiness logic from partial classes generated by Linq2SQL designer.
For example:</p>
<pre><code>Northind.DAL (prj)
-NorthindDataContext (EntityNamespace set to "Northwind.BLL")
--Product() (Entity, partial class auto-generated)
--Category() (Entity, partial class auto-generated)
--Supplier() (Entity, partial class auto-generated)
Northind.BLL (prj)
-Product() : IMyCustomEnityInterface, BaseEntity (override OnValidate(), etc)
-Category() : IMyCustomEnityInterface, BaseEntity (override OnValidate(), etc)
-Supplier() : IMyCustomEnityInterface, BaseEntity (override OnValidate(), etc)
</code></pre>
<p>Unfortunately, we can not do this... actually I'd love to know what the recommended way of splitting up layers/tiers when using LINQ.</p>
| 39,932 |
<p>Is Eclipse the best <code>IDE</code> for Java? </p>
<p>If not, is there something better? </p>
<p>I want to know and possibly try it out. Thanks.</p>
| <p>Let me just start out by saying that Eclipse is a <em>fantastic</em> IDE for Java and many other languages. Its plugin architecture and its extensibility are hard to rival and the fact that it's free is a huge plus for smaller teams or tight budgets.</p>
<p>A few things that I <em>hate</em> about Eclipse.</p>
<ul>
<li>The documentation is really lacking. I don't know who writes the stuff, but if it's not just flatly missing, it's incomplete. If it's not incomplete, then it's just flat out wrong. I have wasted many precious hours trying to use a given feature in Eclipse by walking through its documentation only to discover that it was all trash to begin with.</li>
<li>Despite the size of the project, I have found the community to be very lacking and/or confusing enough to be hard to participate in. I have tried several times to get help on a particular subject or plugin only to be sent to 3 or 4 different newsgroups who all point to the other newsgroup or just plain don't respond. This can be very frustrating, as much smaller open source products that I use are <em>really</em> good about answering questions I have. Perhaps it's simply a function of the size of the community.</li>
<li>If you need functionality beyond the bundled functionality of one of their distros (for instance, the Eclipse for Java EE Developers distro which bundles things like the WTP), I have found the installation process for extra plugins <em>excruciatingly painful</em>. I don't know why they can't make that process simpler (or maybe I'm just spoiled on my Mac at home and don't know how bad it really is out in the 'real' world) but if I'm not just unsuccessful, oftentimes it's a process of multiple hours to get a new plugin installed. This was supposedly one of their goals in 3.4 (to make installation of new projects simpler); if they succeeded, I can't tell.</li>
<li>Documentation in the form of books and actual tutorials is sorely lacking. I want a master walkthrough for something as dense and feature-rich as Eclipse; something that says, 'hey, did you know about this feature and how it can really make you more productive?'. As far as I've found, <em>nothing</em> like that exists. If you want to figure out Eclipse, you've got one option, sit down and play with it (literally play with it, not just see a feature and go and read the documentation for it, because that probably doesn't exist or is wrong).</li>
</ul>
<p>Despite these things, Eclipse really is a great IDE. Its refactoring tooling works tremendously well. The handling of Javadoc works perfectly. All of features we've come to expect of an IDE are their (code completion, templates, integration with various SCMSs, integration with build systems). Its code formatting and cleanup tools are very powerful. I find its build system to work well and intuitively. I think these are the things upon which its reputation is really built.</p>
<p>I don't have enough experience with other IDEs or with other distros of Eclipse (I've seen RAD at work quite a few times; I can't believe <em>anyone</em> would pay what they're charging for that) to comment on them, but I've been quite happy with Eclipse for the most part. One tip I have heard from multiple places is that if you want Eclipse without a lot of the hassle that can come with its straight install, go with a for-pay distro of it. <a href="http://www.myeclipseide.com/" rel="noreferrer">My Eclipse</a> is a highly recommended version that I've seen all over the net that is really <em>very</em> affordable (last I heard, $50 for the distro plus a year of free upgrades). If you have the budget and need the added functionality, I'd go with something like that.</p>
<p>Anyway, I've tried to be as detailed as I can. I hope this helps and good luck on your search! :)</p>
| <p>This is not really an answer, just an anecdote. I worked with guys who used emacs heavily loaded with macros and color coded. Crazy! Why do that when there are so many good IDEs out there?</p>
| 18,421 |
<p>I have an internal web app with an image at the top of the page, currently containing some english text with drop shadows. I now need to provide localized versions of this page for various languages. My main choices are:</p>
<p><UL>
<LI>Have a different graphic per supported language, containing the localized text.</LI>
<LI>Use CSS to position localized text over a plain image, with a <A HREF="http://www.workingwith.me.uk/articles/css/cross-browser-drop-shadows" rel="nofollow noreferrer">complex CSS technique</A> to get drop shadows in most current browsers.</LI>
</UL></p>
<p>Are there other options? This is for an educational environment, I don't get to control the browser used by the students.</p>
<p>I did try both removing the drop shadows from the graphic, and also moving the text into in a header in the HTML, but neither was appealing. People said it looked like a cheap knockoff of the current page, which wounds my pride.</p>
| <p>Personally I'm a big fan of CSS techniques for visual effects like this. The big benefit is that you are offloading the processing of the effect to the client side, saving you bandwith and content creation time (custom text images for each locale is a big order!), and making the page download faster for the user. </p>
<p>The only reason to avoid it is if you absolutely MUST have the drop shadows on very old (IE5) browsers with next to no CSS support. </p>
<p>Edit: Just thought of something - I a few cases like this where I need a specific font or some exact text effect I've used PHP to render the text, with effects, to an image and cache it server side. That way you avoid the content creation process and gain wider browser support in exchange for bandwidth and server CPU time. It's your call if the tradeoff is acceptable. </p>
| <p>Maintaining images with text can be a pain - even without localization, I'd avoid it.</p>
<p>Two choices that I would attempt before going with your options are:</p>
<ul>
<li>Looking for a free program that generates drop-shadow images that you can have your program utilize whenever it detects that new text is available for the title</li>
<li>Using a shadow image that can be repeated as a background image underneath the text</li>
</ul>
<p>If those don't work, I'd try the CSS, but test it in as many browsers as you can yourself before going live with it.</p>
| 22,120 |
<p>I display some objects that have thumbnails in two ways: one in a DataGridView, and one in a custom control.</p>
<p>In the DataGridView, the thumbnail is displayed in a DataGridViewImageCell. If the thumbnail is missing, the cell displays an error icon.</p>
<p>I want to show that icon in my custom control, too. How do I get hold of it? Preferably without pinvoke, but beggars can't be choosers.</p>
| <p>I'd recommend turning this problem on its head: make sure the grid <strong>never</strong> displays the error icon. You should be able to do this by catching the cell data display event. If the image is missing, display an image from your resource segment (and use the same image in the custom control, obviously).</p>
<p>The problem with attempting to match the grid's built-in error image is that if the image gets changed in a future version, you'll have to modify your application.</p>
| <p>I think, this icon is available in "%visual_studio_directory"\Common7\VS2005ImageLibrary" directory.</p>
| 35,975 |
<p>How do you extract an HD and Bios Unique ID, using python script?</p>
| <p>Solutions that come to my mind:</p>
<ol>
<li>use <a href="http://python.net/crew/mhammond/win32/Downloads.html" rel="nofollow noreferrer">Win32 Python Extensions</a> and call Windows APIs to do that directly</li>
<li>Use a WMI-wrapper for Python</li>
</ol>
<p>(some <a href="http://www.microsoft.com/technet/scriptcenter/scripts/python/misc/wmi/mswmpy01.mspx?mfr=true" rel="nofollow noreferrer">WMI interface code</a> for reference)</p>
<p><em>Edit</em>: I assumed your OS was MS Windows :)</p>
| <p>On Linux, look in the /proc directory. You'll have to parse the files to find what you are looking for.</p>
<p><a href="http://www.linux.com/feature/126718" rel="nofollow noreferrer">This</a> might help.</p>
| 28,115 |
<p>What's the best way to do it in .NET?
I always forget what I need to <code>Dispose()</code> (or wrap with <code>using</code>).</p>
<p>EDIT: after a long time using <code>WebRequest</code>, I found out about customizing <code>WebClient</code>. Much better.</p>
| <p>Syncronous Way:</p>
<pre><code>var request = HttpWebRequest.Create("http://www.contoso.com");
request.Timeout = 50000;
using (var response = request.GetResponse())
{
//your code here
}
</code></pre>
<p>You can also have the asynchronous way:</p>
<pre><code>using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;
public class RequestState
{
// This class stores the State of the request.
const int BUFFER_SIZE = 1024;
public StringBuilder requestData;
public byte[] BufferRead;
public HttpWebRequest request;
public HttpWebResponse response;
public Stream streamResponse;
public RequestState()
{
BufferRead = new byte[BUFFER_SIZE];
requestData = new StringBuilder("");
request = null;
streamResponse = null;
}
}
class HttpWebRequest_BeginGetResponse
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout
// Abort the request if the timer fires.
private static void TimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
HttpWebRequest request = state as HttpWebRequest;
if (request != null)
{
request.Abort();
}
}
}
static void Main()
{
try
{
// Create a HttpWebrequest object to the desired URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest.ReadWriteTimeout = DefaultTimeout;
// Create an instance of the RequestState and assign the previous myHttpWebRequest
// object to its request field.
RequestState myRequestState = new RequestState();
myRequestState.request = myHttpWebRequest;
// Start the asynchronous request.
IAsyncResult result =
(IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
// this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), myHttpWebRequest, DefaultTimeout, true);
// The response came in the allowed time. The work processing will happen in the
// callback function.
allDone.WaitOne();
// Release the HttpWebResponse resource.
myRequestState.response.Close();
}
catch (WebException e)
{
Console.WriteLine("\nMain Exception raised!");
Console.WriteLine("\nMessage:{0}", e.Message);
Console.WriteLine("\nStatus:{0}", e.Status);
Console.WriteLine("Press any key to continue..........");
}
catch (Exception e)
{
Console.WriteLine("\nMain Exception raised!");
Console.WriteLine("Source :{0} ", e.Source);
Console.WriteLine("Message :{0} ", e.Message);
Console.WriteLine("Press any key to continue..........");
Console.Read();
}
}
private static void RespCallback(IAsyncResult asynchronousResult)
{
try
{
// State of request is asynchronous.
RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;
HttpWebRequest myHttpWebRequest = myRequestState.request;
myRequestState.response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult);
// Read the response into a Stream object.
Stream responseStream = myRequestState.response.GetResponseStream();
myRequestState.streamResponse = responseStream;
// Begin the Reading of the contents of the HTML page and print it to the console.
IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
return;
}
catch (WebException e)
{
Console.WriteLine("\nRespCallback Exception raised!");
Console.WriteLine("\nMessage:{0}", e.Message);
Console.WriteLine("\nStatus:{0}", e.Status);
}
allDone.Set();
}
private static void ReadCallBack(IAsyncResult asyncResult)
{
try
{
RequestState myRequestState = (RequestState)asyncResult.AsyncState;
Stream responseStream = myRequestState.streamResponse;
int read = responseStream.EndRead(asyncResult);
// Read the HTML page and then print it to the console.
if (read > 0)
{
myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read));
IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
return;
}
else
{
Console.WriteLine("\nThe contents of the Html page are : ");
if (myRequestState.requestData.Length > 1)
{
string stringContent;
stringContent = myRequestState.requestData.ToString();
Console.WriteLine(stringContent);
}
Console.WriteLine("Press any key to continue..........");
Console.ReadLine();
responseStream.Close();
}
}
catch (WebException e)
{
Console.WriteLine("\nReadCallBack Exception raised!");
Console.WriteLine("\nMessage:{0}", e.Message);
Console.WriteLine("\nStatus:{0}", e.Status);
}
allDone.Set();
}
}
</code></pre>
| <p>Run System.Net.WebClient in a seperate thread, set a timer to kill it after your maximum time.</p>
| 37,772 |
<p>Is it possible to create a SQL query which will return one column which contains the dates from a given date range (e.g. all dates from last year till today). E.g.</p>
<pre><code>dat
----
2007-10-01
2007-10-02
2007-10-03
2007-10-04
...
</code></pre>
<p>I am wondering if this is possible as an alternative to creating a table which holds all those dates precalculated.</p>
<p><strong>Updated:</strong> I need a solution for MYSQL. I am not interested in any other DBs in this case.</p>
| <p>AFAIK you cannot do that with a single SQL query. However the following block of code will do the job.</p>
<p>Currently in Transact-SQL (for SQL Server). I do not know how this translates to MySQL.</p>
<pre><code>DECLARE @start datetime
DECLARE @end datetime
DECLARE @results TABLE
(
val datetime not null
)
set @start = '2008-10-01'
set @end = getdate()
while @start < @end
begin
insert into @results values(@start)
SELECT @start = DATEADD (d, 1, @start)
end
select val from @results
</code></pre>
<p>This outputs:</p>
<pre><code>2008-10-01 00:00:00.000
2008-10-02 00:00:00.000
2008-10-03 00:00:00.000
</code></pre>
| <p>AFAIK you cannot do that with a single SQL query. However the following block of code will do the job.</p>
<p>Currently in Transact-SQL (for SQL Server). I do not know how this translates to MySQL.</p>
<pre><code>DECLARE @start datetime
DECLARE @end datetime
DECLARE @results TABLE
(
val datetime not null
)
set @start = '2008-10-01'
set @end = getdate()
while @start < @end
begin
insert into @results values(@start)
SELECT @start = DATEADD (d, 1, @start)
end
select val from @results
</code></pre>
<p>This outputs:</p>
<pre><code>2008-10-01 00:00:00.000
2008-10-02 00:00:00.000
2008-10-03 00:00:00.000
</code></pre>
| 20,084 |
<p>I'm trying to write a simple audio player for a website, and am using the EMBED... tag to embed the audio and setting HIDDEN="true" and using various javascript commands to control the audio playback. It works fine for realplayer and mplayer but the quicktime plugin doesn't respond to javascript if the hidden bit is set - is there any workaround for this?</p>
| <p>First, i suggest you to use the <code>object</code> html tag which is standardized, <code>embed</code> is not.</p>
<p>Then you could simply hide your embeded audio using CSS instead of this <code>hidden</code> param.</p>
<p>Even better, you should hide it using CSS through JavaScript, because if you do it this way, people who don't have JavaScript enabled but support CSS are able use the plugin player directly.</p>
| <p>I found that setting height=0 width=0 worked the same as hidden=true and solved the problem</p>
| 9,745 |
<p>I have an action like this:</p>
<pre><code>public class News : System.Web.Mvc.Controller
{
public ActionResult Archive(int year)
{
/ *** /
}
}
</code></pre>
<p>With a route like this:</p>
<pre><code>routes.MapRoute(
"News-Archive",
"News.mvc/Archive/{year}",
new { controller = "News", action = "Archive" }
);
</code></pre>
<p>The URL that I am on is:</p>
<pre><code>News.mvc/Archive/2008
</code></pre>
<p>I have a form on this page like this:</p>
<pre><code><form>
<select name="year">
<option value="2007">2007</option>
</select>
</form>
</code></pre>
<p>Submitting the form should go to News.mvc/Archive/2007 if '2007' is selected in the form.</p>
<p>This requires the form 'action' attribute to be "News.mvc/Archive".</p>
<p>However, if I declare a form like this:</p>
<pre><code><form method="get" action="<%=Url.RouteUrl("News-Archive")%>">
</code></pre>
<p>it renders as:</p>
<pre><code><form method="get" action="/News.mvc/Archive/2008">
</code></pre>
<p>Can someone please let me know what I'm missing?</p>
| <p>You have a couple problems, I think.</p>
<p>First, your route doesn't have a default value for "year", so the URL "/News.mvc/Archive" is actually not valid for routing purposes.</p>
<p>Second, you're expect form values to show up as route parameters, but that's not how HTML works. If you use a plain form with a select and a submit, your URLs will end up having "?year=2007" on the end of them. This is just how GET-method forms are designed to work in HTML.</p>
<p>So you need to come to some conclusion about what's important.</p>
<ul>
<li>If you want the user to be able to select something from the dropdown and that changes the submission URL, then you're going to have to use Javascript to achieve this (by intercepting the form submit and formulating the correct URL).</li>
<li>If you're okay with /News.mvc/Archive?year=2007 as your URL, then you should remove the {year} designator from the route entirely. You can still leave the "int year" parameter on your action, since form values will also populate action method parameters.</li>
</ul>
| <p>I think I've worked out why - the route includes {year} so the generated routes always will too..</p>
<p>If anyone can confirm this?</p>
| 7,165 |
<p>One of the sites I maintain relies heavily on the use of <code>ViewState</code> (it isn't my code). However, on certain pages where the <code>ViewState</code> is extra-bloated, Safari throws a <code>"Validation of viewstate MAC failed"</code> error.</p>
<p>This appears to only happen in Safari. Firefox, IE and Opera all load successfully in the same scenario.</p>
| <p>I've been doing a little research into this and whilst I'm not entirely sure its the cause I believe it is because Safari is not returning the full result set (hence cropping it).</p>
<p>I have been in dicussion with another developer and found the following post on Channel 9 as well which recommends making use of the SQL State service to store the viewstate avoiding the postback issue and also page size.</p>
<p><a href="http://channel9.msdn.com/forums/TechOff/250549-ASPNET-ViewState-flawed-architecture/?CommentID=270477#263702" rel="nofollow noreferrer">http://channel9.msdn.com/forums/TechOff/250549-ASPNET-ViewState-flawed-architecture/?CommentID=270477#263702</a></p>
<p>Does this seem like the best solution?</p>
| <p>My first port of call would be to go through the elements on the page and see which controls:</p>
<ol>
<li>Will still work when I switch ViewState off</li>
<li>Can be moved out of the page and into an AJAX call to be loaded when required</li>
</ol>
<p>Failing that, and here's the disclaimer - I've never used this solution on a web-facing site - but in the past where I've wanted to eliminate massive ViewStates in limited-audience applications I have stored the ViewState in the Session.</p>
<p>It has worked for me because the hit to memory isn't significant for the number of users, but if you're running a fairly popular site I wouldn't recommend this approach. However, if the Session solution works for Safari you could always detect the user agent and fudge appropriately.</p>
| 2,361 |
<p>I was happily using Eclipse 3.2 (or as happy as one can be using Eclipse) when for a forgotten reason I decided to upgrade to 3.4. I'm primarily using PyDev, Aptana, and Subclipse, very little Java development.</p>
<p>I've noticed 3.4 tends to really give my laptop a hernia compared to 3.2 (vista, core2duo, 2G). Is memory usage on 3.4 actually higher than on 3.2, and if so is there a way to reduce it?</p>
<p>EDIT: I tried disabling plugins (I didn't have much enabled anyway) and used the jvm monitor; the latter was interesting but I couldn't figure out how to use the info in any practical way. I'm still not able to reduce its memory footprint. I've also noticed every once in a while Eclipse just hangs for ~30 seconds, then magically comes back.</p>
| <p>Yes memory usage can get real high and you might run into problems with your JVM, as the default setting is a bit to low.
Consider using this startup parameters when running eclipse:</p>
<pre><code>-vmargs -XX:MaxPermSize=1024M -Xms256M -Xmx1024M
</code></pre>
| <p>Yes memory usage can get real high and you might run into problems with your JVM, as the default setting is a bit to low.
Consider using this startup parameters when running eclipse:</p>
<pre><code>-vmargs -XX:MaxPermSize=1024M -Xms256M -Xmx1024M
</code></pre>
| 12,535 |
<p>I'm going to make my monthly trip to the bookstore soon and I'm kind of interested in learning some user interface and/or design stuff - mostly web related, what are some good books I should look at? One that I've seen come up frequently in the past is <a href="https://rads.stackoverflow.com/amzn/click/com/0321344758" rel="nofollow noreferrer" rel="nofollow noreferrer">Don't Make Me Think</a>, which looks promising.</p>
<p>I'm aware of the fact that programmers often don't make great designers, and as such this is more of a potential hobby thing than a move to be a professional designer.</p>
<p>I'm also looking for any good web resources on this topic. I subscribed to Jakob Nielsen's <a href="http://www.useit.com/alertbox/" rel="nofollow noreferrer">Alertbox newsletter</a>, for instance, although it seems to come only once a month or so.</p>
<p>Thanks!</p>
<p>Somewhat related questions:</p>
<p><a href="https://stackoverflow.com/questions/75863/what-are-the-best-resources-for-designing-user-interfaces">https://stackoverflow.com/questions/75863/what-are-the-best-resources-for-designing-user-interfaces</a>
<a href="https://stackoverflow.com/questions/7973/user-interface-design">User Interface Design</a></p>
| <p><a href="http://www.sensible.com/dmmt.html" rel="nofollow noreferrer">Don't Make Me Think</a> is the one!</p>
<p>Also check out <a href="http://www.sensible.com/" rel="nofollow noreferrer">Steve Krug's website</a> for tips and sample forms for usability testing.</p>
| <p>"Don't Make Me Think" is great. After sitting in on several usability studies I can safely say that several of his biggest points are the kinds of things drilled in your head over and over.</p>
<p>Joel Spolsky's book on user interfaces is also decent.</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/1893115941" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/User-Interface-Design-Programmers-Spolsky/dp/1893115941</a></p>
| 27,369 |
<p>I have printed two objects with my new 3D printer (Anycubic Mega S) and everytime, my prints are stuck to my bed (sort of glued to it). I cannot remove them by hand. I have tried waiting until it cools off, but the only thing that works is scraping really hard the bed with the spatula.</p>
<p>I'm scared that if I have to do that for my next prints, I will break the bed (maybe peel off the element that keeps the plastic and the bed glued together while printing). </p>
<p>What is the safest way to remove a print from the bed ?</p>
| <p>One method that works at our makerspace and also has worked for a user on another 3d printing forum is to use a 50:50 mix of water and denatured alcohol. While the print bed is warm, apply some to the perimeter of the print at the bed surface. Allow it to cool, try to remove the print. If it does not work, reheat the bed and repeat until you are able to release it.</p>
| <p>I have had good luck using dental floss. If you can get it under the edge of the print, then you can pull it all the way through and prints come off easily. </p>
| 1,548 |
<p>Is there any way to detect, through WSH, which workstations, in a windows domain, has a locked session?</p>
| <p><a href="http://www.microsoft.com/technet/scriptcenter/resources/qanda/nov04/hey1115.mspx" rel="nofollow noreferrer">http://www.microsoft.com/technet/scriptcenter/resources/qanda/nov04/hey1115.mspx</a></p>
<p>If you scroll down, there is a check if computer is locked script on the page. The script basically grabs the running processes for the machine and looks for the scrnsave.exe.</p>
<p>It is also worth noting that the author of this script states that he does not know of a foolproof way to determine if a computer is locked. Hope this helps or at least points you in the right direction.</p>
| <p>Not sure if you are using locked as in locked or as in hung but I use pstools to check for systems with the screen lock turned on. My command line is:</p>
<p>pslist \machinename > machinename.txt</p>
<p>then check the machine_name.txt file for logon.scr if present the screen is locked.</p>
| 42,353 |
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
| <p>Starting with Version 1.3.6 (released Aug-17-2010) you <strong>CAN</strong> </p>
<p><a href="http://code.google.com/p/googleappengine/wiki/SdkReleaseNotes#Version_1.3.6_-_August_17,_2010" rel="noreferrer">From the changelog:</a></p>
<blockquote>
<p>Results of datastore count() queries <strong>and offsets for all datastore queries are no longer capped at 1000</strong>.</p>
</blockquote>
| <p>To add the contents of the two queries together:</p>
<pre><code>list1 = first query
list2 = second query
list1 += list2
</code></pre>
<p>List 1 now contains all 2000 results.</p>
| 33,081 |
<p>I'm trying to script the shutdown of my VM Servers in a .bat.
if one of the vmware-cmd commands fails (as the machine is already shutdown say), I'd like it to continue instead of bombing out.</p>
<pre><code>c:
cd "c:\Program Files\VMWare\VmWare Server"
vmware-cmd C:\VMImages\TCVMDEVSQL01\TCVMDEVSQL01.vmx suspend soft -q
vmware-cmd C:\VMImages\DevEnv\DevEnv\DevEnv.vmx suspend soft -q
vmware-cmd C:\VMImages\DevEnv\TCVMDEV02\TCVMDEV02.vmx suspend soft =q
robocopy c:\vmimages\ \\tcedilacie1tb\VMShare\DevEnvironmentBackups\ /mir /z /r:0 /w:0
vmware-cmd C:\VMImages\TCVMDEVSQL01\TCVMDEVSQL01.vmx start
vmware-cmd C:\VMImages\DevEnv\DevEnv\DevEnv.vmx start
vmware-cmd C:\VMImages\DevEnv\TCVMDEV02\TCVMDEV02.vmx start
</code></pre>
| <p>Run it inside another command instance with <code>CMD /C</code></p>
<pre><code>CMD /C vmware-cmd C:\...
</code></pre>
<p>This should keep the original BAT files running.</p>
| <p>You could write a little Program that executes the command an returns a value (say -1 for an error). This value can then be used in your Batch-File.</p>
| 9,994 |
<p>I'm looking for a Java profiler that works well with the JVM coming with WebSphere 6.0.2 (IBM JVM 1.4.2). I use yourkit for my usual profiling needs, but it specifically refuses to work with this old jvm (I'm sure the authors had their reasons...).</p>
<p>Can anybody point to a decent profiler that can do the job? Not interested in a generic list of profilers, BTW, I've seen the other stackoverflow theread, but I'd rather not try them one by one.</p>
<p>I would prefer a free version, if possible, since this is a one-off need (I hope!) and I would rather not pay for another profiler just for this. </p>
| <p>Update: I found out that <a href="http://www.ej-technologies.com/products/jprofiler/overview.html" rel="nofollow noreferrer">JProfiler</a> integrates smoothly with WAS 6.0.2 (IBM JDK 1.4). </p>
| <p>What are you looking to profile? Is it stuff in the JVM or the App Server? If it's the latter, there's loads of stuff in WAS 6 GUI to help with this. Assuming you really want to see stuff like the heap etc, then the IBM <a href="http://alphaworks.ibm.com/tech/heapanalyzer" rel="nofollow noreferrer">HeapAnalyzer</a> might help. There are other tools listed off the bottom of this page.</p>
<p>Something else I've learned, ideally, youll be able to connect your IDE's profiler to the running JVM. Some let you do this to a remote one as well as the local one you are developing on. Is the JVM you wish to profile in live or remote? If so, you might have to force dumps and take them out of the live environment to look at at your leisure. Otherwise, set up something local and get the info from it that way. </p>
| 8,711 |
<p>I have a DLL written in C++ that needs to be used by an application in C#. It works great under Vista x86, but under x64 it fails to load. So I build an x64 version of the DLL and I detect whether the OS is x86 or x64 and use the appropriate interop call to the appropriate DLL. This works fine under Vista x86, but under Vista x64 I get a "side-by-side" error when it tries to load the DLL. Why exactly is it failing to load it, and what can be done to correct this? (Please let me know if you need more information, I'm not sure what information is relevant in trouble-shooting this issue.)</p>
| <p>The redist for VC90 for x64 will need to be installed on the client machine. As far as the manifest goes, I think you can alter it to remove the processorArchitecture tag. Either that or have it say "any".</p>
| <p>The side by side error is more then likely caused by you c++ dll manifest file settings either they are not getting embedded or you have chosen to not embed the manifest and is using the 32bit versions manifest.</p>
<p>The simple solution is to mark your c# application as for the x86 cup and run with the 32bit dll.</p>
| 44,269 |
<p>I've evaluated some plugins from official IntelliJ repository, but none of them seems to provide more then basic syntax highlighting. Even highlighting is limited. For example, Database Navigator doesn't highlight IF. It would be great to have proper highlighting. And if it would have auto-complete feature and provide file structure view I would be completely happy.
I use SQL Query Plugin when I need to post some little stuff to database or to query something from it. I use PL/SQL Developer when I need to make more complex things, or when I need to modify PL/SQL. But most of the time I need to navigate through mix of Java, JavaScript and PL/SQL code. Unfortunately, SQL Query Plugin doesn't help with that as well as PL/SQL Developer.</p>
| <p>Have you tried <a href="http://java.sstiller.de/sql/index.html" rel="nofollow noreferrer" title="KiwiSoft - SQL Query Plugin">SQL Query Plugin</a>? It comes with a great host of features, including multiple query windows, direct editing of tables, and of course, proper highlighting for PL/SQL syntax and a browser of the internal database structure.</p>
<p>It also integrates well with the main editor: you can right-click on any selected Java string containing SQL and "Send to SQLPlugin" to strip out all of the quotes and non-SQL syntax.</p>
| <p>I've started using the <a href="http://plugins.intellij.net/plugin/?objc&pluginId=4486" rel="nofollow">SQL Code Assistant</a> plugin that instantly has recognised my PL/SQL packages and all these PL/SQL constructs (cursors etc) which the out-of-the-box IntelliJ functionality couldn't understand and was marking red. As of now it cannot only recognise dblinks but that's fair enough. Of course you'll have to associate *.sql file types with the plugin but it will intellij-ently inform you after you install/restart the IDE.</p>
| 20,224 |
<p>If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys? I have heard that using <code>each</code> may in some way have unintended side effects. So, is that true, and is one of the two following methods best, or is there a better way?</p>
<pre><code># Method 1
while (my ($key, $value) = each(%hash)) {
# Something
}
# Method 2
foreach my $key (keys(%hash)) {
# Something
}
</code></pre>
| <p>The rule of thumb is to use the function most suited to your needs.</p>
<p>If you just want the keys and do not plan to ever <em>read</em> any of the values, use keys():</p>
<pre><code>foreach my $key (keys %hash) { ... }
</code></pre>
<p>If you just want the values, use values():</p>
<pre><code>foreach my $val (values %hash) { ... }
</code></pre>
<p>If you need the keys <em>and</em> the values, use each():</p>
<pre><code>keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop
while(my($k, $v) = each %hash) { ... }
</code></pre>
<p>If you plan to change the keys of the hash in any way <em>except</em> for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys():</p>
<pre><code>%h = (a => 1, b => 2);
foreach my $k (keys %h)
{
$h{uc $k} = $h{$k} * 2;
}
</code></pre>
<p>producing the expected resulting hash:</p>
<pre><code>(a => 1, A => 2, b => 2, B => 4)
</code></pre>
<p>But using each() to do the same thing:</p>
<pre><code>%h = (a => 1, b => 2);
keys %h;
while(my($k, $v) = each %h)
{
$h{uc $k} = $h{$k} * 2; # BAD IDEA!
}
</code></pre>
<p>produces incorrect results in hard-to-predict ways. For example:</p>
<pre><code>(a => 1, A => 2, b => 2, B => 8)
</code></pre>
<p>This, however, is safe:</p>
<pre><code>keys %h;
while(my($k, $v) = each %h)
{
if(...)
{
delete $h{$k}; # This is safe
}
}
</code></pre>
<p>All of this is described in the perl documentation:</p>
<pre><code>% perldoc -f keys
% perldoc -f each
</code></pre>
| <p>I woudl say:</p>
<ol>
<li>Use whatever's easiest to read/understand for most people (so keys, usually, I'd argue)</li>
<li>Use whatever you decide consistently throught the whole code base. </li>
</ol>
<p>This give 2 major advantages:</p>
<ol>
<li>It's easier to spot "common" code so you can re-factor into functions/methiods.</li>
<li>It's easier for future developers to maintain.</li>
</ol>
<p>I don't think it's more expensive to use keys over each, so no need for two different constructs for the same thing in your code.</p>
| 2,517 |
<p>In the KornShell (ksh) on <b>AIX UNIX Version 5.3</b> with the editor mode set to vi using:</p>
<pre><code>set -o vi
</code></pre>
<p>What are the key-strokes at the shell command line to autocomplete a file or directory name?</p>
| <p>ESC\ works fine on AIX4.2 at least. One thing I noticed is that it only autocompletes to the unique part of the file name.</p>
<p>So if you have the files x.txt, x171go and x171stop, the following will happen:</p>
<pre><code>Press keys: Command line is:
x x
<ESC>\ x
1 x1
<ESC>\ x171
g<ESC>\ x171go
</code></pre>
| <p>Extending the other answers: <ESC>* will list all matching files on the command line. Then you can use the standard vi editing commands to remove the ones you don't care about. So to add to the above table:</p>
<pre><code><ESC><shift-8> x.txt x171 x171go
</code></pre>
<p>Then use backspace to go get rid of the last two, or hit <ESC> again and use the h or b to go backwards and dw to delete the ones you don't want.</p>
| 10,660 |
<p>I'm looking to perform a perspective transform on a UIView (such as seen in coverflow)</p>
<p>Does anyonew know if this is possible? </p>
<p>I've investigated using <code>CALayer</code> and have run through all the pragmatic programmer Core Animation podcasts, but I'm still no clearer on how to create this kind of transform on an iPhone.</p>
<p>Any help, pointers or example code snippets would be really appreciated!</p>
| <p>As Ben said, you'll need to work with the <code>UIView's</code> layer, using a <code>CATransform3D</code> to perform the <code>layer's</code> <code>rotation</code>. The trick to get perspective working, as <a href="http://watchingapple.com/2008/04/core-animation-3d-perspective/" rel="nofollow noreferrer">described here</a>, is to directly access one of the matrix <code>cells</code> of the <code>CATransform3D</code> (m34). Matrix math has never been my thing, so I can't explain exactly why this works, but it does. You'll need to set this value to a negative fraction for your initial transform, then apply your layer rotation transforms to that. You should also be able to do the following:</p>
<p><strong>Objective-C</strong></p>
<pre class="lang-objectivec prettyprint-override"><code>UIView *myView = [[self subviews] objectAtIndex:0];
CALayer *layer = myView.layer;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;
</code></pre>
<p><strong>Swift 5.0</strong></p>
<pre class="lang-swift prettyprint-override"><code>if let myView = self.subviews.first {
let layer = myView.layer
var rotationAndPerspectiveTransform = CATransform3DIdentity
rotationAndPerspectiveTransform.m34 = 1.0 / -500
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * .pi / 180.0, 0.0, 1.0, 0.0)
layer.transform = rotationAndPerspectiveTransform
}
</code></pre>
<p>which rebuilds the layer transform from scratch for each rotation.</p>
<p>A full example of this (with code) can be found <a href="http://www.sunsetlakesoftware.com/2008/10/22/3-d-rotation-without-trackball" rel="nofollow noreferrer">here</a>, where I've implemented touch-based rotation and scaling on a couple of <code>CALayers</code>, based on an example by Bill Dudney. The newest version of the program, at the very bottom of the page, implements this kind of perspective operation. The code should be reasonably simple to read.</p>
<p>The <code>sublayerTransform</code> you refer to in your response is a transform that is applied to the sublayers of your <code>UIView's</code> <code>CALayer</code>. If you don't have any sublayers, don't worry about it. I use the sublayerTransform in my example simply because there are two <code>CALayers</code> contained within the one layer that I'm rotating.</p>
| <p>You can get accurate Carousel effect using iCarousel SDK.</p>
<p>You can get an instant Cover Flow effect on iOS by using the marvelous and free iCarousel library. You can download it from <a href="https://github.com/nicklockwood/iCarousel" rel="nofollow noreferrer">https://github.com/nicklockwood/iCarousel</a> and drop it into your Xcode project fairly easily by adding a bridging header (it's written in Objective-C).</p>
<p>If you haven't added Objective-C code to a Swift project before, follow these steps:</p>
<ul>
<li>Download iCarousel and unzip it</li>
<li>Go into the folder you unzipped, open its iCarousel subfolder, then select iCarousel.h and iCarousel.m and drag them into your project navigation – that's the left pane in Xcode. Just below Info.plist is fine.</li>
<li>Check "Copy items if needed" then click Finish.</li>
<li>Xcode will prompt you with the message "Would you like to configure an Objective-C bridging header?" Click "Create Bridging Header"
You should see a new file in your project, named YourProjectName-Bridging-Header.h.</li>
<li>Add this line to the file: #import "iCarousel.h"</li>
<li>Once you've added iCarousel to your project you can start using it.</li>
<li>Make sure you conform to both the iCarouselDelegate and iCarouselDataSource protocols.</li>
</ul>
<p>Swift 3 Sample Code:</p>
<pre><code> override func viewDidLoad() {
super.viewDidLoad()
let carousel = iCarousel(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
carousel.dataSource = self
carousel.type = .coverFlow
view.addSubview(carousel)
}
func numberOfItems(in carousel: iCarousel) -> Int {
return 10
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
let imageView: UIImageView
if view != nil {
imageView = view as! UIImageView
} else {
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 128))
}
imageView.image = UIImage(named: "example")
return imageView
}
</code></pre>
| 45,254 |
<p>I am iterating though a TreeSet and printing it out:</p>
<pre><code>while (it.hasNext()) {
System.out.println(it.next());
}
</code></pre>
<p>output:</p>
<pre><code>after
explorers
giant
hoping
internet
into
.
.
.
virtual
world
</code></pre>
<p>However, I would like to <i>only</i> print out those strings who's first character is within the range m-z. I have been playing around with java.util.regex, with no success:</p>
<pre><code>String pattern = "[^m-z]";
</code></pre>
<p>Do I have the right idea here? Or is there a simpler way of doing this? All I want to do is make sure I <strong>only print out those Strings in the TreeSet who's first character is within the range m-z.</strong></p>
| <p>First of all, your regular expression is wrong. You want</p>
<pre><code>"^[m-z]"
</code></pre>
<p>Second of all, you don't show the code you're using to do the matching.</p>
<p>Third: If you're willing to do something besides regular expressions and iteration, you should look into SortedSet.tailSet. That's probably what your teacher wants.</p>
| <p>seems like an homework but anyhow,
the "[^m-z]" means NOT m-z</p>
<p>try putting the "^" outside the "[]"</p>
<p>Have a look at the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html" rel="nofollow noreferrer">Pattern</a> class
and BTW, try <code>String.matches()</code></p>
| 41,055 |
<p>I've just found out about Stack Overflow and I'm just checking if there are ideas for a constraint I'm having with some friends in a project, though this is more of a theoretical question to which I've been trying to find an answer for some time.</p>
<p>I'm not much given into cryptography but if I'm not clear enough I'll try to edit/comment to clarify any questions.</p>
<p>Trying to be brief, the environment is something like this:</p>
<ul>
<li><p>An application where the front-end as access to encrypt/decrypt keys and the back-end is just used for storage and queries.</p></li>
<li><p>Having a database to which you can't have access for a couple of fields for example let's say "address" which is text/varchar as usual.</p></li>
<li><p>You don't have access to the key for decrypting the information, and all information arrives to the database already encrypted.</p></li>
</ul>
<p>The main problem is something like this, how to consistently make queries on the database, it's impossible to do stuff like "where address like '%F§YU/´~#JKSks23%'". (IF there is anyone feeling with an answer for this feel free to shoot it).</p>
<p>But is it ok to do <code>where address='±!NNsj3~^º-:'</code>? Or would it also completely eat up the database? </p>
<p>Another restrain that might apply is that the front end doesn't have much processing power available, so already encrypting/decrypting information starts to push it to its limits. (Saying this just to avoid replies like "Exporting a join of tables to the front end and query it there".)</p>
<p>Could someone point me in a direction to keep thinking about it?</p>
<hr>
<p>Well thanks for so fast replies at 4 AM, for a first time usage I'm really feeling impressed with this community. (Or maybe I'm it's just for the different time zone)</p>
<p>Just feeding some information:</p>
<p>The main problem is all around partial matching. As a mandatory requirement in most databases is to allow partial matches. The main constraint is actually <strong>the database owner would not be allowed to look inside the database for information</strong>. During the last 10 minutes I've come up with a possible solution which extends again to possible database problems, to which I'll add here:</p>
<p>Possible solution to allow semi partial matching:</p>
<ul>
<li>The password + a couple of public fields of the user are actually the key for encrypting. For authentication the idea is to encrypt a static value and compare it within the database.</li>
<li>Creating a new set of tables where information is stored in a parsed way, meaning something like: "4th Street" would become 2 encrypted rows (one for '4th' another for 'Street'). This would already allow semi-partial matching as a search could already be performed on the separate tables.</li>
</ul>
<p>New question:</p>
<ul>
<li>Would this probably eat up the database server again, or does anyone think it is a viable solution for the partial matching problem?</li>
</ul>
<p><em>Post Scriptum: I've unaccepted the answer from Cade Roux just to allow for further discussion and specially a possible answer to the new question.</em></p>
| <p>You can do it the way you describe - effectively querying the hash, say, but there's not many systems with that requirement, because at that point the security requirements are interfering with other requirements for the system to be usable - i.e. no partial matches, since the encryption rules that out. It's the same problem with compression. Years ago, in a very small environment, I had to compress the data before putting it in the data format. Of course, those fields could not easily be searched.</p>
<p>In a more typical application, ultimately, the keys are going to be available to someone in the chain - probably the web server.</p>
<p>For end user traffic SSL protects that pipe. Some network switches can protect it between web server and database, and storing encrypted data in the database is fine, but you're not going to query on encrypted data like that.</p>
<p>And once the data is displayed, it's out there on the machine, so any general purpose computing device can be circumvented at that point, and you have perimeter defenses outside of your application which really come into play.</p>
| <p>You want do use md5 hashing. Basically, it takes your string and turns it into a hash that cannot be reproduced. You can then use it to validate against things later. For example:</p>
<pre><code>$salt = "123-=asd";
$address = "3412 g ave";
$sql = "INSERT INTO addresses (address) VALUES ('" . md5($salt . $address) . "')";
mysql_query($sql);
</code></pre>
<p>Then, to validate an address in the future:</p>
<pre><code>$salt = "123-=asd";
$address = "3412 g ave";
$sql = "SELECT address FROM addresses WHERE address = '" . md5($salt . $address) . "'";
$res = mysql_query($sql);
if (mysql_fetch_row($res))
// exists
else
// does not
</code></pre>
<p>Now it is encrypted on the database side so nobody can find it out - even if they looked in your source code. However, finding the salt will help them decrypt it though.</p>
<p><a href="http://en.wikipedia.org/wiki/MD5" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/MD5</a></p>
| 21,855 |
<p>How much data should be in a table so that reading is optimal? Assuming that I have 3 fields varchar(25). This is in MySQL.</p>
| <p>Number of rows should not matter. Make sure the fields your searching on are indexed properly. If you only have 3 varchar(25) fields, then you probably need to add a primary key that is not a varchar.</p>
| <p>For optimal reading you should have an index. A table exists to hold the rows it was designed to contain. As the number of rows increases, the value of the index comes into play and reading remains brisk.</p>
| 36,586 |
<p>While there appears to some documentation on how to expose JMX through various firewall and tunneling schemes, I sort of want the opposite. I want to ensure that JMX is only accessible to local machine. Unfortunately it appears that the "out of the box" management options do not allow restricting the ports to a local interface and netstat shows them listening on any/all interfaces.</p>
<p><a href="http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html#gdevf" rel="noreferrer">http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html#gdevf</a></p>
<p>I have to admit I am bewildered by the layers of indirection in JMX, the RMI registry, connectors, adapters, etc.</p>
<p>I would like to just turn it on and then tunnel through SSH as opposed to exposing it to the world and then having to perform arduous and superfluous user management and security configuration. It would be nice to be able to use a built in RMI registry and not have to run an external one.</p>
| <p>A bit late answer but if it is still a problem for you (or someone else), I think this will do the trick:</p>
<pre class="lang-java prettyprint-override"><code>import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.RMISocketFactory;
import javax.management.MBeanServer;
import javax.management.remote.*;
public class LocalJMXPort {
public static void main(String[] args) {
try {
int port = 12468;
// Create an instance of our own socket factory (see below)
RMISocketFactory factory = new LocalHostSocketFactory();
// Set it as default
RMISocketFactory.setSocketFactory(factory);
// Create our registry
LocateRegistry.createRegistry(port);
// Get the MBeanServer and setup a JMXConnectorServer
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://127.0.0.1:"+port+"/jndi/rmi://127.0.0.1:"+port+"/jmxrmi");
JMXConnectorServer rmiServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
rmiServer.start();
// Say something
System.out.println("Connect your jconsole to localhost:"+port+". Press a key to exit");
// Wait for a key press
int in = System.in.read();
//Exit
System.out.println("Exiting");
System.exit(0);
} catch(Exception ex) {
ex.printStackTrace();
}
}
static private class LocalHostSocketFactory extends RMISocketFactory {
public ServerSocket createServerSocket(int port) throws IOException {
ServerSocket ret = new ServerSocket();
ret.bind(new InetSocketAddress("localhost", port));
return ret;
}
public Socket createSocket(String host, int port) throws IOException {
return new Socket(host, port);
}
}
}
</code></pre>
<p>I just put it together and it is possible that I did something really stupid because my only objective was to have it binding to localhost:port instead of *:port and that part seems to work.</p>
<p>Feel free to comment if there are things that could be bettered or is just plain stupid.</p>
| <p>Can't help with the sun way of doing it. Even after jmx adapters started coming with the jdk (6 i think?) I kept using mx4j for the least-effort adapter setup. It is trivial to start up an mx4j http adapter on 127.0.0.1 or an internal-only interface. Then SOP was to ssh in with port forwards or use scripts with wget commands.</p>
<p><a href="http://mx4j.sourceforge.net/" rel="nofollow noreferrer">http://mx4j.sourceforge.net/</a></p>
| 45,155 |
<p>Windows Mobile devices have different behaviour for suspending when the device is on battery power, or on external power.</p>
<p>in my application, written using VB.net, I need to be able to determine whether the device has external power connected.</p>
<p>is there a method to get this status from the Compact framework?</p>
| <p>If you're using WIndowsMobile 5.0 and later only, the <a href="http://www.developer.com/ws/pc/article.php/3547381" rel="nofollow noreferrer">State and Notification Broker</a> is where to look, specifically at the <a href="http://msdn.microsoft.com/en-us/library/microsoft.windowsmobile.status.aspx" rel="nofollow noreferrer">Status namespace</a>.</p>
<p>For broader support, you can detect the state <em>transition</em> (to or from AC power) calling <a href="http://msdn.microsoft.com/en-us/library/aa932775.aspx" rel="nofollow noreferrer">CeRunAppAtEvent</a> (this can set a named event rather than just running an app) with the NOTIFICATION_EVENT_AC_APPLIED or NOTIFICATION_EVENT_AC_REMOVED event codes. This is what the <a href="http://opennetcf.com/library/sdf/html/2b12c039-26e1-14e2-afdd-36f55aa07c5b.htm" rel="nofollow noreferrer">DeviceManagement class</a> in the <a href="http://www.smartdeviceframework.com" rel="nofollow noreferrer">Smart Device Framework</a> does.</p>
<p>You can detect current state (instead of transitions) by calling <a href="http://msdn.microsoft.com/en-us/library/aa453173.aspx" rel="nofollow noreferrer">GetSystemPowerStatusEx2</a>.</p>
| <p>This may go beyond what you were asking but I wrote something on the Windows Mobile Powermanagement APIS. It uses the same APIs that Chris just referenced but is .Net oriented (sorry, it is in C#, not VB.Net). </p>
<p><a href="http://www.codeproject.com/KB/mobile/WiMoPower1.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/mobile/WiMoPower1.aspx</a></p>
| 47,398 |
<p>I've decided that I want to use Mercurial for a small, personal project. </p>
<p>Most of the help I've read about it talks about merging changes between multiple users. Since I'm solo, that's not going to happen.</p>
<p>Should I have multiple repositories? My development computer is already backed up nightly to my Windows Home Server, so it doesn't seem valuable to have a second repository elsewhere just for backup purposes.</p>
<p>Should I be branching every day? Or just around releases? Or when?</p>
<p>In general, what practices do you recommend for the lone developer using Mercurial?</p>
| <p>I use Mercurial to develop FsCheck, a unit testing framework hosted in codeplex. I am currently the only developer, but occasionally people send me patches.</p>
<p>Concretely, I have one folder in my filesystem called "FsCheck". In that, I have one repository, and thus folder, called main. Typically, I have a few folders next to that where I work on specific features or bug fixes or whatever, say bug-escapingexceptions and feat-statefulchecking and patch-userFoo. These are created using hg clone.</p>
<p>When I'm done with a feature or bugfix, I commit everything in that folder and push to main. Possibly merge in main. (hg commit, hg push, hg merge). Then I delete the folder (careful using hg status and hg outgoing that I'm not throwing away something useful).</p>
<p>I almost never work in main except right before a release, where I do final cleanup (say documentation). Before release, I tag in main with the release number (hg tag v0.5.1).</p>
<p>Codeplex uses svn as sourcecontrol. I only use it as to store releases, for which I use a locally checked out SVN working copy, to which I copy the Mercurial repository using hg archive. Then commit using svn. Primitive, but it works (using Mercurial as an SVN 'super client' on windows isn't very user-friendly yet in my opnion)</p>
<p>I haven't had to do maintenance on previous releases yet, but I would do that by cloning the main repository from that release's revision(this is easy, since I tagged it), and work in that separate repository. Merging back to the main trunk would be as easy as pushing the changes to main and merging.</p>
<p>In summary:</p>
<ul>
<li>One folder to store all your project's repositories, with the name of your project</li>
<li>In that folder one main repository, and one transient repository per "unit of work", with a descriptive name for the unit of work.</li>
</ul>
<p>It's nice cause your branches and what you're working on is intuitively visible in the filesystem.</p>
| <p>I think this depends on whether or not you are maintaining an existing application <em>and</em> adding features (or fixing large bugs) at the same time.</p>
<p>This way you can fix bugs in the main branch while creating a new feature in it's own branch.</p>
<p>I do exactly that with my applications, but with a local version of CVS. Also, if a new developer is added to your team, you are all set to go.</p>
<p>I agree that this is a separate issue from backups.</p>
<p>Good Luck,<br>
Randy Stegbauer</p>
| 34,978 |
<blockquote>
<p><strong>Possible Duplicate:</strong><br />
<a href="https://stackoverflow.com/questions/6457130/pre-post-increment-operator-behavior-in-c-c-java-c-sharp">Pre & post increment operator behavior in C, C++, Java, & C#</a></p>
</blockquote>
<p>Here is a test case:</p>
<pre><code>
void foo(int i, int j)
{
printf("%d %d", i, j);
}
...
test = 0;
foo(test++, test);
</code></pre>
<p>I would expect to get a "0 1" output, but I get "0 0"
What gives??</p>
| <p>This is an example of unspecified behavior. The standard does <strong>not</strong> say what order arguments should be evaluated in. This is a compiler implementation decision. The compiler is free to evaluate the arguments to the function in any order. </p>
<p>In this case, it looks like actually processes the arguments right to left instead of the expected left to right.</p>
<p>In general, doing side-effects in arguments is bad programming practice. </p>
<p>Instead of <strong>foo(test++, test);</strong> you should write <strong>foo(test, test+1); test++;</strong></p>
<p>It would be semantically equivalent to what you are trying to accomplish.</p>
<p>Edit:
As Anthony correctly points out, it is undefined to both read and modify a single variable without an intervening sequence point. So in this case, the behavior is indeed <strong>undefined</strong>. So the compiler is free to generate whatever code it wants.</p>
| <p>The compiler might not be evaluating the arguments in the order you'd expect.</p>
| 12,372 |
<p>I have got a button with an onclick javascript event that does some form validation. If the validation fails, false is returned. Otherwise nothing is returned, and the form should be submitted. </p>
<p>But what's happening is the url loads in the address bar but the page never loads. No headers are sent, no error messages display. Just a blank page. </p>
<p>This seems to only happen in IE. </p>
| <p>Check if you closed all your tags in the top of the page. In particular the head tag.</p>
| <p>Do you call submit() if validation passes?</p>
| 37,231 |
<p>I am trying to control a laser with the fan (D9) and ran into problems.
So I tried P44, no good then P6 also not good.\
What my problem is I am trying to "burn" a group of vertical lines spaced about 0.75" apart, and randomly the drive to the laser power supply is either "skipping" (missing the control pulse) or stretching the pulse.
This results in missed burns and/or "streaks" where the laser does not turn off.
I am using Marlin 1.1.4 on a RAMPS 1.4 board (clone) on an Arduino close also.
When I am not printing, the pulses are perfect and I can control the pulse width with M42 P6(or 44) S0 (to 255) and it follows just fine.
It is ONLY while I am printing and the steppers are moving that things go south.
This also occurs on D9 (fan) and that is why I am trying these other outputs.
These other outputs use different timers in the 2560 as well.
I have tried all sorts and combinations of firmware settings, different USB cable and different USB ports on my computer, with no change.
What might I be missing?</p>
| <p>Thank you all for your suggestions and help.</p>
<p>It appears that I was just running the printer too fast and slowing it down to about 10% of my original speed "fixed" my problem.
I don't know where i got the rediculous speed from, but 1200 mm/min is WAY too fast.
More like 150 to maybe 200 mm/min is what it should have been.</p>
<p>Oh well.. comes under the heading "pay attention" I guess!</p>
| <p>This is a stab in the dark but maybe the Arduino (clone or genuine) and RAMPS1.4 combination is not powerful enough to handle the calculations required to control the laser and printing simultaneously (although I can't really see why the additional processing to control a laser would be over taxing the processor. However your comment about slowing the printing seems to help alleviate the issue, does back up the hypothesis). I have read that the ATmega256, and lesser AVR microcontrollers, can be working at its limits, when controlling a 3D printer and having to deal with arcs, or something that requires complex calculations. </p>
<p>Some printer control boards, such as the Smoothie, use different processors (ARM?) in order to supersede these issues. From <a href="http://hackaday.com/2013/09/06/3d-printering-electronics-boards/" rel="nofollow noreferrer">3D Printering: Electronics boards</a>. </p>
<blockquote>
<p>The above boards use AVR microcontrollers. While they work for what they’re intended to do, there are a few limitations. Arcs and circles are a little weird to program, and using these boards for something other than a cartesian 3D printer – a CNC machine, or a laser cutter, for example – is a bit out of the ordinary. The Smoothie board is the solution to these problems.</p>
</blockquote>
<p>So, if you have discounted power issues, it could be due to computing power and it <em>may</em> be worth considering using a different, more powerful, controller?</p>
| 650 |
<p>I'm having quite a bit of pain inserting and deleting UITableViewCells from the same UITableView!</p>
<p>I don't normally post code, but I thought this was the best way of showing where I'm having the problem:</p>
<hr>
<pre><code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (iSelectedSection == section) return 5;
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//NSLog(@"drawing row:%d section:%d", [indexPath row], [indexPath section]);
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
if (iSelectedSection == [indexPath section]) {
cell.textColor = [UIColor redColor];
} else {
cell.textColor = [UIColor blackColor];
}
cell.text = [NSString stringWithFormat:@"Section: %d Row: %d", [indexPath section], [indexPath row]];
// Set up the cell
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic -- create and push a new view controller
if ([indexPath row] == 0) {
NSMutableArray *rowsToRemove = [NSMutableArray array];
NSMutableArray *rowsToAdd = [NSMutableArray array];
for(int i=0; i<5; i++) {
//NSLog(@"Adding row:%d section:%d ", i, [indexPath section]);
//NSLog(@"Removing row:%d section:%d ", i, iSelectedSection);
[rowsToAdd addObject:[NSIndexPath indexPathForRow:i inSection:[indexPath section]]];
[rowsToRemove addObject:[NSIndexPath indexPathForRow:i inSection:iSelectedSection]];
}
iSelectedSection = [indexPath section];
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:rowsToRemove withRowAnimation:YES];
[tableView insertRowsAtIndexPaths:rowsToAdd withRowAnimation:YES];
[tableView endUpdates];
}
}
</code></pre>
<hr>
<p>This code creates 5 sections, the 1st (indexed from 0) with 5 rows. When you select a section - it removes the rows from the section you had previously selected and adds rows to the section you just selected.</p>
<p>Pictorally, when I load up the app, I have something like this:</p>
<p><a href="http://www.freeimagehosting.net/uploads/1b9f2d57e7.png" rel="noreferrer">http://www.freeimagehosting.net/uploads/1b9f2d57e7.png http://www.freeimagehosting.net/uploads/1b9f2d57e7.png</a></p>
<p>Image here: <a href="http://www.freeimagehosting.net/uploads/1b9f2d57e7.png" rel="noreferrer">http://www.freeimagehosting.net/uploads/1b9f2d57e7.png</a></p>
<p>After selecting a table row 0 of section 2, I then delete the rows of section 1 (which is selected by default) and add the rows of section 2. But I get this:</p>
<p><a href="http://www.freeimagehosting.net/uploads/6d5d904e84.png" rel="noreferrer">http://www.freeimagehosting.net/uploads/6d5d904e84.png http://www.freeimagehosting.net/uploads/6d5d904e84.png</a></p>
<p>Image here: <a href="http://www.freeimagehosting.net/uploads/6d5d904e84.png" rel="noreferrer">http://www.freeimagehosting.net/uploads/6d5d904e84.png</a></p>
<p>...which isn't what I expect to happen! It seems like the first row of section 2 somehow remains - even though it definitly gets deleted.</p>
<p>If I just do a [tableView reloadData], everything appears as normal... but I obviously forefit the nice animations.</p>
<p>I'd really appreciate it if someone could shine some light here! It's driving me a little crazy!</p>
<p>Thanks again,
Nick.</p>
| <p>Struggled to get this to work. Here's my code to add a row to my tableView:</p>
<pre><code>NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[tableView beginUpdates];
[dataSource insertObject:[artistField text] atIndex:0];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
[tableView endUpdates];
</code></pre>
| <p>In the code you posted, your loop index runs from 0 to 4, which suggests that it would delete <i>all</i> of the rows in section 1, and then add five new rows to section 2. Since each section already has a row 0, this would add a <i>second</i> instance of section 2, row 0 to the table.</p>
<p>I would suggest having your loop run from 1 to 4:</p>
<pre><code>for (int i=1; i<5; i++)
{
// ...
}</code></pre>
| 43,010 |
<p>I've started working with ASP.net AJAX (finally ☺). and I've got an update panel together with a asp:UpdateProgress. My Problem: The UpdateProgress always forces a line-break, because it renders out as a div-tag.</p>
<p>Is there any way to force it being a span instead? I want to display it on the same line as some other controls without having to use a table or even <em>shudders</em> absolute positioning in CSS.</p>
<p>I'm stuck with ASP.net AJAX 1.0 and .net 3.0 if that makes a difference.</p>
| <p>I've had the same issue. There is no easy way to tell the updateProgress to render inline. You would be better off to roll your own updateProgress element. You can add a beginRequest listener and endRequest listener to show and hide the element you want to display inline. Here is simple page which shows how to do it:</p>
<p><strong>aspx</strong></p>
<pre><code><form id="form1" runat="server">
<div>
<asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="up1" UpdateMode="Always">
<ContentTemplate>
<asp:Label ID="lblTest" runat="server"></asp:Label>
<asp:Button ID="btnTest" runat="server" Text="Test" OnClick="btnTest_OnClick" />
</ContentTemplate>
</asp:UpdatePanel>
<img id="loadingImg" src="../../../images/loading.gif" style="display:none;"/><span>Some Inline text</span>
<script>
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function(sender, args) {
if (args.get_postBackElement().id == "btnTest") {
document.getElementById("loadingImg").style.display = "inline";
}
});
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) {
if (document.getElementById("loadingImg").style.display != "none") {
document.getElementById("loadingImg").style.display = "none";
}
});
</script>
</div>
</form>
</code></pre>
<p><strong>cs</strong></p>
<pre><code>public partial class updateProgressTest : System.Web.UI.Page
{
protected void btnTest_OnClick(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
this.lblTest.Text = "I was changed on the server! Yay!";
}
}
</code></pre>
| <p>You can make a div inline like this:</p>
<pre><code><div style="display:inline">stuff</div>
</code></pre>
<p>I'm skeptical of it rendering the div for you though... I don't remember having this problem on my pages...</p>
| 6,401 |
<p>Need some advice on working out the team velocity for a sprint.</p>
<p>Our team normally consists of about 4 developers and 2 testers. The scrum master insists that every team member should contribute equally to the velocity calculation i.e. we should not distinguish between developers and testers when working out how much we can do in a sprint. The is correct according to Scrum, but here's the problem.</p>
<p>Despite suggestions to the contrary, testers never help with non-test tasks and developers never help with non-dev tasks, so we are not cross functional team members at all. Also, despite various suggestions, testers normally spend the first few days of each sprint waiting for something to test. </p>
<p>The end result is that typically we take on far more dev work than we actually have capacity for in the sprint. For example, the developers might contribute 20 days to the velocity calculation and the testers 10 days. If you add up the tasks after sprint planning though, dev tasks add up to 25 days and test tasks add up to 5 days.</p>
<p>How do you guys deal with this sort of situation?</p>
| <p>Since Agile development is about transparency and accountability it sounds like the testers should have assigned tasks that account for their velocity. Even if that means they have a task for surfing the web waiting for testing (though I would think they would be better served developing test plans for the dev team's tasks). This will show the inefficiencies in your organization which isn't popular but that is what Agile is all about. The bad part of that is that your testers may be penalized for something that is a organizational issue.</p>
<p>The company I worked for had two separate (dev and qa) teams with two different iteration cycles. The qa cycle was offset by a week. That unfortunatey led to complexity when it came to task acceptance, since a product wasn't really ready for release until the end of the qa's iteration. That isn't a properly integrated team but neither is yours from the sound of it. Unfortunately the qa team never really followed scrum practices (No real planning, stand up, or retrospective) so I can't really tell if that is a good solution or not.</p>
| <p>Sounds to me like your system is working, just not as well as you'd like. Is this a paid project? If it is, you could make pay be a meritocracy. Pay people based on how much of the work they get done. This would encourage cross discipline work. Although, it might also encourage people to work on pieces that weren't theirs to begin with, or internal sabotage.</p>
<p>Obviously, you'd have to be on the lookout for people trying to game the system, but it might work. Surely testers wouldn't want to earn half of what devs do.</p>
| 7,080 |
<p>I hope this question does not come off as broad as it may seem at first. I am designing a software application that I would like to be both cross-platform and modular. I am still in the planning phase and can pick practically any language and toolset.</p>
<p>This makes things harder, not easier, because there are seemingly so many ways of accomplishing both of the goals (modularity, platform agnosticism).</p>
<p>My basic premise is that security, data storage, interaction with the operating system, and configuration should all be handled by a "container" application - but most of the other functionality will be supplied through plug-in modules. If I had to describe it at a high level (without completely giving away my idea), it would be a single application that can do many different jobs, all dedicated to the same goal (there are lots of disparate things to do, but all the data has to interact and be highly available).</p>
<p>I find myself wrestling with not so much how to do it (I can think of lots of ways), but which method is best.</p>
<p>For example, I know that Eclipse practically embodies what I am describing, but I find Java applications in general (and Eclipse is no exception) to be too large and slow for what I need. Ditto desktop apps written Python and Ruby (which are excellent languages!)</p>
<p>I don't mind recompiling the code base for different platforms as native exectables. Yet, C and C++ have their own set of issues.</p>
<p>As a C# developer, I have a preference for managed code, but I am not at all sold on Mono, yet (I could be convinced).</p>
<p>Does anyone have any ideas/experiences/ specific favorite frameworks to share?</p>
| <p>Just to cite an example: for .NET apps there are the CAB (Composite Application Block) and the Composite Application Guidance for WPF. Both are mainly implementations of a set of several design patterns focused on modularity and loose coupling between components similar to a plug-in architecture: you have an IOC framework, MVC base classes, a loosely coupled event broker, dynamic loading of modules and other stuff.</p>
<p>So I suppose that kind of pattern infrastructure is what you are trying to find, just not specifically for .NET. But if you see the CAB as a set of pattern implementations, you can see that almost every language and platform has some form of already built-in or third party frameworks for individual patterns. </p>
<p>So my take would be:</p>
<ol>
<li>Study (if you are not familiar with) some of those design patterns. You could take as an example the CAB framework for WPF documentation: <a href="http://msdn.microsoft.com/en-us/library/cc707841.aspx" rel="nofollow noreferrer">Patterns in the Composite Application Library</a></li>
<li>Design your architecture thinking on which of those patterns you think would be useful for what you want to achieve <b>first without thinking in specific pattern implementations or products</b>.</li>
<li>Once you have your 'architectural requirements' defined more specifically, look for individual frameworks that help accomplish each one of those patterns/features for the language you decide to use and put together your own application framework based on them.</li>
</ol>
<p>I agree that the hard part is to make all this platform independent. I really cannot think on any other solution to choose a mature platform independent language like Java.</p>
| <p>With my limited Mono experience I can say I'm quite sold on it. The fact that there is active development and a lot of ongoing effort to bring it up to spec with the latest .Net technologies is encouraging. It is incredibly useful to be able to use existing .Net skills on multiple platforms. I had similar issues with performance when attempting to accomplish some basic tasks in Python + PyGTK -- maybe they can be made to perform in the right hands but it is nice to not have to worry about performance 90% of the time.</p>
| 5,360 |
<p>I have the following component </p>
<pre><code>public class MyTimer : IMyTimer {
public MyTimer(TimeSpan timespan){...}
}
</code></pre>
<p>Where timespan should be provided by the property ISettings.MyTimerFrequency.</p>
<p>How do I wire this up in windsor container xml?
I thought I could do something like this:</p>
<pre><code> <component id="settings"
service="MySample.ISettings, MySample"
type="MySample.Settings, MySample"
factoryId="settings_dao" factoryCreate="GetSettingsForInstance">
<parameters><instance_id>1</instance_id></parameters>
</component>
<component id="my_timer_frequency"
type="System.TimeSpan"
factoryId="settings" factoryCreate="MyTimerFrequency" />
<component id="my_timer"
service="MySample.IMyTimer, MySample"
type="MySample.MyTimer, MySample">
<parameters><timespan>${my_timer_frequency}</timespan></parameters>
</code></pre>
<p>but I am getting an error because MyTimerFrequency is a property when the factory facility expects a method.</p>
<p>Is there a simple resolution here? Am I approaching the whole thing the wrong way?</p>
<p><strong>EDIT:</strong> There is definitely a solution, see my answer below.</p>
| <p>The solution actually came to me in a dream. Keep in mind that properties are not a CLR construct but rather C# syntactic sugar. If you don't believe me just try compiling</p>
<pre><code>public class MyClass {
public object Item {
get;
}
public object get_Item() {return null;}
}
</code></pre>
<p>results in a Error: <strong>Type 'TestApp.MyClass' already reserves a member called 'get_Item' with the same parameter types</strong></p>
<p>Since the Xml configuration is pursed at runtime after compilation, we can simply bind to a factoryCreate property by binding to the method that it compiles to so the above example becomes: </p>
<pre><code><component id="my_timer_frequency"
type="System.TimeSpan"
factoryId="settings" factoryCreate="get_MyTimerFrequency" />
</code></pre>
<p>And voila! </p>
<p>Someone vote this up since I can't mark it as an answer.</p>
| <p>Wouldn't the simplest solution be to add a method which wraps the property?</p>
| 23,311 |
<p>I have a table like so:</p>
<pre><code>keyA keyB data
</code></pre>
<p>keyA and keyB together are unique, are the primary key of my table and make up a clustered index.</p>
<p>There are 5 possible values of keyB but an unlimited number of possible values of keyA,. keyB generally increments.</p>
<p>For example, the following data can be ordered in 2 ways depending on which key column is ordered first:</p>
<pre><code>keyA keyB data
A 1 X
B 1 X
A 3 X
B 3 X
A 5 X
B 5 X
A 7 X
B 7 X
</code></pre>
<p>or</p>
<pre><code>keyA keyB data
A 1 X
A 3 X
A 5 X
A 7 X
B 1 X
B 3 X
B 5 X
B 7 X
</code></pre>
<p>Do I need to tell the clustered index which of the key columns has fewer possible values to allow it to order the data by that value first? Or does it not matter in terms of performance which is ordered first?</p>
| <p>You should order your composite clustered index with the most selective column first. This means the column with the most distinct values compared to total row count.</p>
<p>"B*TREE Indexes improve the performance of queries that select a small percentage of rows from a table." <a href="http://www.akadia.com/services/ora_index_selectivity.html" rel="noreferrer">http://www.akadia.com/services/ora_index_selectivity.html</a>?</p>
<p>This article is for Oracle, but still relevant. </p>
<p>Also, if you have a query that runs constantly and returns few fields, you may consider creating a composite index that contains all the fields - it will not have to access the base table, but will instead pull data from the index.</p>
<p>ligget78's comment on making sure to mention the first column in a composite index is important to remember.</p>
| <p>The best thing you can do is to try both solutions and measure the execution time.</p>
<p>In my experience, index tuning is all but exact-science.</p>
<p>Maybe having keyB before keyA in the index column order would be better</p>
| 44,751 |
<p>Are these two terms interchangeable?</p>
| <p>CIL is the term used in the <a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm" rel="noreferrer">CLI Standard</a>. MSIL is (I suppose) CIL created by MS tools. Effectively they are synonymous.</p>
<p><a href="http://blogs.msdn.com/brada/archive/2005/09/20/CILorMSIL.aspx" rel="noreferrer">Brad Abrams says this.</a></p>
| <p>Both the terms are similar but with following difference:</p>
<p>CIL – Common Intermediate Language – is the term used in the International Standard. </p>
<p>MSIL – Microsoft Intermediate Language – is the product term for the Microsoft implementation of that standard.</p>
| 37,504 |
<p>As a workaround for a problem, I think I have to handle KeyDown events to get the printable character the user actually typed.</p>
<p>KeyDown supplies me with a KeyEventArgs object with the properities KeyCode, KeyData, KeyValue, Modifiers, Alt, Shift, Control.</p>
<p>My first attempt was just to consider the KeyCode to be the ascii code, but KeyCode on my keyboard is 46, a period ("."), so I end up printing a period when the user types the delete key. So, I know my logic is inadequate.</p>
<p>(For those who are curious, the problem is that I have my own combobox in a DataGridView's control collection and somehow SOME characters I type don't produce the KeyPress and TextChanged ComboBox events. These letters include Q, $, %....</p>
<p>This code will reproduce the problem. Generate a Form App and replace the ctor with this code. Run it, and try typing the letter Q into the two comboxes.</p>
<pre><code>public partial class Form1 : Form
{
ComboBox cmbInGrid;
ComboBox cmbNotInGrid;
DataGridView grid;
public Form1()
{
InitializeComponent();
grid = new DataGridView();
cmbInGrid = new ComboBox();
cmbNotInGrid = new ComboBox();
cmbInGrid.Items.Add("a");
cmbInGrid.Items.Add("b");
cmbNotInGrid.Items.Add("c");
cmbNotInGrid.Items.Add("d");
this.Controls.Add(cmbNotInGrid);
this.Controls.Add(grid);
grid.Location = new Point(0, 100);
this.grid.Controls.Add(cmbInGrid);
}
</code></pre>
| <p>Many controls override the default key input events. For instance, a Panel won't respond to them by default at all. As for the case of simple controls, you could try:</p>
<pre><code>protected override bool IsInputKey(Keys keyData) {
// This snippet informs .Net that arrow keys should be processed in the panel (which is strangely not standard).
switch (keyData & Keys.KeyCode) {
case Keys.Left:
return true;
case Keys.Right:
return true;
case Keys.Up:
return true;
case Keys.Down:
return true;
}
return base.IsInputKey(keyData);
}
</code></pre>
<p>The IsInputKey function tells your program what keys to receive events from. There is a chance you'll get weird behaviour if you override keys that clearly have special functions, but experiment a little and see for yourself what works and what doesn't.</p>
<p>Now, for more advanced controls like a DataGridView or ComboBox, keyhandling can be even more complicated. The following resource should give you a few pointers about how to go about your problem:</p>
<p><a href="http://www.dotnet247.com/247reference/msgs/29/148332.aspx" rel="nofollow noreferrer">http://www.dotnet247.com/247reference/msgs/29/148332.aspx</a></p>
<p>Or this resource might perhaps solve your problem:</p>
<p><a href="http://dotnetperls.com/previewkeydown" rel="nofollow noreferrer">http://dotnetperls.com/previewkeydown</a></p>
| <p>Have a look at System.Text.Encoding.ASCII and System.Text.Encoding.Default</p>
| 24,216 |
<p>I'm working on a .NET web application and I'm using a CalendarExtender control within it to have the user specify a date. For some reason, when I click the icon to display the calendar, the background seems to be transparent.</p>
<p>I'm using the extender on other pages and do not run into this issue.</p>
<p>I'm not sure if it is worth mentioning, but the calendar is nested within a panel that has a rounded corner extender attached to it, as well as the panel below it (where the "From" is overlapping).</p>
<p>Within that panel, I do have a div layout setup to create two columns.</p>
<p>EDIT: The other thing to note here is that the section that has the name and "placeholders" for nickname are all ASP.NET label controls, if that matters.</p>
| <p>So some more poking around and I figured out the issue. Part of the problem arises from the fact that the div layout I setup to create two separate columns is using the position:relative and float:right/left attributes. </p>
<p>From what I've read, as soon as you start augmenting the position attribute of a div tag, it affects the z-index of the rendering, which only gets complicated when the calendar control is "popping up" dynamically.</p>
<p>Unfortunately there is no Z-Index attribute to the CalendarExtender, unless you want to write an entire style for the calendar, which I don't want to do. However, you can extend the default style by adding the following to your CSS file:</p>
<pre><code>.ajax__calendar_container { z-index : 1000 ; }
</code></pre>
<p>If you aren't using a CSS file, you can also add this into the head section of your page:</p>
<pre><code><style type="text/css">
.ajax__calendar_container { z-index : 1000 ; }
</style>
</code></pre>
<p>and that should do the trick. It worked for me. </p>
<p>If for some reason this doesn't work (and some people were still reporting problems), a little more "aggressive" approach was to wrap the input fields and CalendarExtender in a DIV tag and then add the following to your CSS file / HEAD section:</p>
<pre><code>.ajax__calendar {
position: relative;
left: 0px !important;
top: 0px !important;
visibility: visible; display: block;
}
.ajax__calendar iframe
{
left: 0px !important;
top: 0px !important;
}
</code></pre>
<p>...and hopefully that will work for you.</p>
| <p>That doesn't look transparent to me, it looks like it's rendering "behind" the other elements.
Do you have a "z-index" specified for any items?</p>
| 38,805 |
<p>This code was working properly before, basically I have a master page that has a single text box for searching, I named it <strong><code>searchBox</code></strong>. I have a method to pull the content of <strong><code>searchBox</code></strong> on form submit and set it to a variable <strong><code>userQuery</code></strong>. Here is the method:</p>
<pre><code>Public Function searchString(ByVal oTextBoxName As String) As String
If Master IsNot Nothing Then
Dim txtBoxSrc As New TextBox
txtBoxSrc = CType(Master.FindControl(oTextBoxName), TextBox)
If txtBoxSrc IsNot Nothing Then
Return txtBoxSrc.Text
End If
End If
Return Nothing
End Function
</code></pre>
<p>The results are displayed on <strong><code>search.aspx</code></strong>. Now, however, if <strong><code>searchBox</code></strong> is filled and submitted on a page other than <strong><code>search.aspx</code></strong>, the contents of the text box are not passed through. The form is very simple, just:</p>
<p><code><asp:TextBox ID="searchBox" runat="server"></asp:TextBox><br>
<asp:Button ID="searchbutton" runat="server" Text="search" UseSubmitBehavior="True" PostBackUrl="~/search.aspx" CssClass="searchBtn" /></code>.</p>
| <p>There is a feature in AD for Win2k3 and higher to mark an object to prevent accidental deletion. This check box on the object actually changes the underlying permissions for you to remove delete permissions. Therefore it is not tool specific and must be respected by other tools (like powershell and vbscript).</p>
| <p>You could deny the Delete privalge from Administrators through Delegation at the root level and then you would need to be an enterprise admin to perform deletions. Ensure that no admins are in the Enterprise Admins group for day-to-day usage.</p>
| 31,363 |
<p>I've recently asked a question on StackoverFlow about the MVC: <a href="https://stackoverflow.com/questions/305988/can-the-mvc-design-pattern-architectual-pattern-be-used-in-desktop-application">Can the MVC Design Pattern / Architectural pattern be used in Desktop Application Development?</a></p>
<p>Based on the answer provided I started research on how this would be implemented in a Windows form Application. I came upon the following CodeProject article: <a href="http://www.codeproject.com/KB/cs/model_view_controller.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/model_view_controller.aspx</a></p>
<p>In the comments below the article, certain users argue that (although this is a good article) it is actually the observer pattern. <strong>First, but less important, question is does anyone agree or disagree with that and why?</strong> </p>
<p>Regarding the second and more important question: I'm trying to build a small task list program in .NET. It will be very tiny and hopefully fast. <strong>In general, what would be a better architecture for such a project? The Observer Pattern or the MVC Pattern? Or another pattern?</strong> </p>
<p>Thank you</p>
| <p><em>(The article is not an example of MVC AFAIK for the simple reason that there is no controller.. it is more close to .net data binding if you ask me.)</em><br>
MVC is not the Observer pattern. MVC is concerned with separation of concerns. The Model, the View and the Controller all do one job and trust the others to do theirs. In a way, the Controller 'directs' the view and tells it how to react to a change (Pure MVC). The controller also interacts with the model appropriately (whose responsibility is to encapsulate data and enforce constraints/rules). In MVC, the controller is the starting point for all activities - user input is received by the controller first.. However there are variants like MVP, where the user is input is received by the view first and then pushed/synched with the presenter.</p>
<p>The Observer pattern is where you want to watch another object for a change in state. So you could say .net events follow the observer pattern</p>
<p>If its really tiny, forget about patterns and just code it up without worrying about the architecture... Follow the heuristics/principles of good design</p>
<ul>
<li><a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod" rel="nofollow noreferrer">http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod</a></li>
<li><a href="http://mmiika.wordpress.com/oo-design-principles/" rel="nofollow noreferrer">http://mmiika.wordpress.com/oo-design-principles/</a></li>
</ul>
<p>If you run into design issues or it starts to get all messy, then bring in the pattern battalions.</p>
| <p>I would agree that the article is not MVC. Its more of an implementation of observer pattern. Observer pattern in .NET can be implemented by using events, which was the case of the article. </p>
<p>MVC requires a controller class that controls what action to execute upon a request made from either the model, or the view. Applying MVC is a very good programming practice as it greatly promotes separation of concern. You will have a cleaner, more extensible, and more testable app with mvc. Another point to note, you can still apply observer pattern to an MVC app. They will not contradict each other.</p>
<p>===========</p>
<p>To answer your second question: which pattern is the best? I think the way you approach software development is rather wrong. You shouldn't worry too much about those things yet, not until you've hit a problem. e.g. If this object changes state I need these other objects to react to it, hence I would implement an observer pattern.</p>
<p>If I were you I would start on the model side first, and then takes things from there.</p>
| 39,649 |
<p>I'm experimenting with a personal finance application, and I'm thinking about what approach to take to update running balances when entering a transaction in an account.</p>
<p>Currently the way I'm using involves retrieving all records more recent than the inserted/modified one, and go one by one incrementing their running balance.</p>
<p>For example, given the following transactions:</p>
<p>t1 date = 2008-10-21, amount = 500, running balance = 1000</p>
<p>t2 date = 2008-10-22, amount = 300, running balance = 1300</p>
<p>t3 date = 2008-10-23, amount = 100, running balance = 1400
...</p>
<p>Now suppose I insert a transaction between t1 and t2, then t2 and all subsequent transactions would need their running balances adjusted.</p>
<p>Hehe, now that I wrote this question, I think I know the answer... so I'll leave it here in case it helps someone else (or maybe there's even a better approach?)</p>
<p>First, I get the running balance from the previous transaction, in this case, t1. Then I update all following transactions (which would include the new one):</p>
<pre><code>UPDATE transactions
SET running_balance = running_balance + <AMOUNT>
WHERE date > <t1.date>
</code></pre>
<p>The only issue I see is that now instead of storing only a date, I'll have to store a time too. Although, what would happen if two transactions had the exact same date/time?</p>
<p>PS: I'd prefer solutions not involving propietary features, as I'm using both PostgreSQL and SQLite... Although a Postgre-only solution would be helpful too.</p>
| <p>Some sort of Identity / Auto-increment columnn in there would be wise as well, purely for the transaction order if anything. </p>
<p>Also in addition to just the date of the transaction, a date that the transaction is inserted into the database (not always the same) would be wise / helpful as well. </p>
<p>These sort of things simply help you arrange things in the system and make it easier to change things i.e. for transactions, at a later time. </p>
| <p>If you have a large volume of transactions, then you are better off storing the running balance date-wise or even week/month-wise in a separate table.
This was if you are inserting rows for the same date you just need to change the running balance in one row.
The querying and reporting will be more trickier as using this running balance you would need to arrive at balances after each transaction, it would be more like taking the last days running balance and adding or subtracting the transaction value.</p>
| 27,694 |
<p>I want to copy the entire contents of a directory from one location to another in C#.</p>
<p>There doesn't appear to be a way to do this using <code>System.IO</code> classes without lots of recursion.</p>
<p>There is a method in VB that we can use if we add a reference to <code>Microsoft.VisualBasic</code>:</p>
<pre><code>new Microsoft.VisualBasic.Devices.Computer().
FileSystem.CopyDirectory( sourceFolder, outputFolder );
</code></pre>
<p>This seems like a rather ugly hack. Is there a better way?</p>
| <p>Much easier</p>
<pre><code>private static void CopyFilesRecursively(string sourcePath, string targetPath)
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
}
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);
}
}
</code></pre>
| <p>Better than any code (extension method to DirectoryInfo with recursion)</p>
<pre><code>public static bool CopyTo(this DirectoryInfo source, string destination)
{
try
{
foreach (string dirPath in Directory.GetDirectories(source.FullName))
{
var newDirPath = dirPath.Replace(source.FullName, destination);
Directory.CreateDirectory(newDirPath);
new DirectoryInfo(dirPath).CopyTo(newDirPath);
}
//Copy all the files & Replaces any files with the same name
foreach (string filePath in Directory.GetFiles(source.FullName))
{
File.Copy(filePath, filePath.Replace(source.FullName,destination), true);
}
return true;
}
catch (IOException exp)
{
return false;
}
}
</code></pre>
| 8,318 |
<p>I am building an application that is very similar to a shopping cart. The user selects a product from a list, and then based on that product, a few properties need to be set and saved.</p>
<p>Example.</p>
<p>If the user selects a type of paint that allows custom color matches, then I must allow them to enter in a formula number that they received through a color match process. So I have an Order Detail item for a Product that is a type of Paint, and that sku has the attribute of "AllowsCustomColorMatch", but I need to store the Formula Number somewhere also.</p>
<p>I'm not sure how to handle this elegantly throughout my code. Should I be creating subclasses or products? Right now I'm saving the data the user enters in an OrderDetails object that has a reference to the Product it is associated with.</p>
| <p>You can have a Product class with a collection of product properties </p>
<pre><code> public class Product
{
private Dictionary<string, string> properties;
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get;
set;
}
/// <summary>
/// Gets or sets the price.
/// </summary>
/// <value>The price.</value>
public double Price
{
get;
set;
}
public Dictionary<string, string> Properties
{
get;
}
public Product()
{
properties = new Dictionary<string, string>();
}
}
</code></pre>
<p>In the datasource you can have a table that defines the properties to each type of product. Then when you render the page you know what properties to show and the name to give in the dictionary.</p>
| <p>Depending on how you have you current objects setup; I would create 2 Paint classes. The first Paint class takes all the common properties/fields found in paint. I would then create a second class, we'll call it PaintSpecialize. PaintSpecialize will inherit from Paint (giving this class all of Paint's properties and methods). In PaintSpecialize you can then add the Formula property to the class. After which, it's just a matter of casting the objects.
C# ex:</p>
<pre><code>public class Paint {
private decimal _price;
private bool _allowFormula;
public Paint() { ... }
public Paint(int price) {
_price = price;
}
public ChangePrice(decimal p) {
_price = p;
}
}
</code></pre>
<p>And so on.</p>
<p>PaintSpecialize would look something like this:</p>
<pre><code>public class PaintSpecialize : Paint {
string _formula;
[...]
public PaintSpecialize(int price, string formula) : base(price) {
_formula=formula;
}
</code></pre>
<p>After in code it's possible to:</p>
<pre><code>PaintSpecialize ps = new PaintSpecialize(15.00, "FormulaXXYY");
ps.ChangePrice(12.00);
List<Paint> plist = new List<Paint>();
plist.Add((Paint)ps);
foreach(Paint p in plist) {
if(p.AllowFormula) {
PaintSpecialize tmp = (PaintSpecialize)p;
MessageBox.Show(tmp._formula);
}
</code></pre>
<p>The above code gives a simple (and not very complete) look at what you can do with paint. The list can now contain both Paint and PaintSpecialize as long as the latter is casted properly. You can manipulate the PaintSpecialize in the list at anytime simple by casting it form a simple Paint to a PaintSpecialize.</p>
<p>So if the customer wants regular paint, create a Paint object, if he wants a custom paint, create a PaintSpecialize. If the customer wants a regular and custom paint, create one of each. Refer to both of them as Paint until you need to use something from the PaintSpecialize class.</p>
<p>Note that the AllowsCustomColorMatch attribute should be set in the base class otherwise you'll probably have to work a little harder to figure out if the class is of the PaintSpecialize type.</p>
| 36,515 |
<p>I Have one entity [Project] that contains a collection of other entities [Questions].</p>
<p>I have mapped the relation with a cascade attribute of "all-delete-orphan".</p>
<p>In my DB the relation is mapped with a project_id (FK) field on the questions table. this field cannot be null since I don't want a Question without a Project.</p>
<p>When I do <code>session.delete(project)</code> it throws an exception saying that <code>project_id</code> cant be <code>null</code>, but if I remove the <code>not-null</code> constraint to that field, the deletion works nice.</p>
<p>Anyone knows how to solve this?</p>
| <p>Straight from the <a href="http://www.hibernate.org/hib_docs/nhibernate/html/example-parentchild.html#example-parentchild-cascades" rel="noreferrer">documentation</a>. This explains your problem exactly i believe:</p>
<p>However, this code</p>
<pre><code>Parent p = (Parent) session.Load(typeof(Parent), pid);
// Get one child out of the set
IEnumerator childEnumerator = p.Children.GetEnumerator();
childEnumerator.MoveNext();
Child c = (Child) childEnumerator.Current;
p.Children.Remove(c);
c.Parent = null;
session.Flush();
</code></pre>
<p>will not remove c from the database; it will only remove the link to p (and cause a NOT NULL constraint violation, in this case). You need to explicitly Delete() the Child.</p>
<pre><code>Parent p = (Parent) session.Load(typeof(Parent), pid);
// Get one child out of the set
IEnumerator childEnumerator = p.Children.GetEnumerator();
childEnumerator.MoveNext();
Child c = (Child) childEnumerator.Current;
p.Children.Remove(c);
session.Delete(c);
session.Flush();
</code></pre>
<p>Now, in our case, a Child can't really exist without its parent. So if we remove a Child from the collection, we really do want it to be deleted. For this, we must use cascade="all-delete-orphan".</p>
<pre><code><set name="Children" inverse="true" cascade="all-delete-orphan">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>
</code></pre>
<p>Edit: </p>
<p>With regards to the inverse stuff, i believe this only determines how the sql is generated, see this <a href="http://simoes.org/docs/hibernate-2.1/155.html" rel="noreferrer">doc</a> for more info.</p>
<p>One thing to note is, have you got </p>
<pre><code>not-null="true"
</code></pre>
<p>on the many-to-one relationship in your hibernate config?</p>
| <p>The delete is occurring on the Project first and cascading to the Question, but the Project delete includes a nulling of the project_id in the Questions (for referential integrity. You're not getting an exception on the deletion of the Question object, but because the cascade is trying to null the FK in the Question(s).</p>
<p>Looking at "<a href="http://www.manning.com/bauer2/" rel="nofollow noreferrer">Java Persistence with Hibernate</a>", I think that what you really want a cascade type of delete or remove, not delete-orphans.</p>
| 24,305 |
<p>I got this output when running <code>sudo cpan Scalar::Util::Numeric</code></p>
<pre>
jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$ sudo cpan Scalar::Util::Numeric
[sudo] password for jmm:
CPAN: Storable loaded ok
Going to read /home/jmm/.cpan/Metadata
Database was generated on Tue, 09 Sep 2008 16:02:51 GMT
CPAN: LWP::UserAgent loaded ok
Fetching with LWP:
ftp://ftp.perl.org/pub/CPAN/authors/01mailrc.txt.gz
Going to read /home/jmm/.cpan/sources/authors/01mailrc.txt.gz
Fetching with LWP:
ftp://ftp.perl.org/pub/CPAN/modules/02packages.details.txt.gz
Going to read /home/jmm/.cpan/sources/modules/02packages.details.txt.gz
Database was generated on Tue, 16 Sep 2008 16:02:50 GMT
There's a new CPAN.pm version (v1.9205) available!
[Current version is v1.7602]
You might want to try
install Bundle::CPAN
reload cpan
without quitting the current session. It should be a seamless upgrade
while we are running...
Fetching with LWP:
ftp://ftp.perl.org/pub/CPAN/modules/03modlist.data.gz
Going to read /home/jmm/.cpan/sources/modules/03modlist.data.gz
Going to write /home/jmm/.cpan/Metadata
Running install for module Scalar::Util::Numeric
Running make for C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz
CPAN: Digest::MD5 loaded ok
Checksum for /home/jmm/.cpan/sources/authors/id/C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz ok
Scanning cache /home/jmm/.cpan/build for sizes
Scalar-Util-Numeric-0.02/
Scalar-Util-Numeric-0.02/Changes
Scalar-Util-Numeric-0.02/lib/
Scalar-Util-Numeric-0.02/lib/Scalar/
Scalar-Util-Numeric-0.02/lib/Scalar/Util/
Scalar-Util-Numeric-0.02/lib/Scalar/Util/Numeric.pm
Scalar-Util-Numeric-0.02/Makefile.PL
Scalar-Util-Numeric-0.02/MANIFEST
Scalar-Util-Numeric-0.02/META.yml
Scalar-Util-Numeric-0.02/Numeric.xs
Scalar-Util-Numeric-0.02/ppport.h
Scalar-Util-Numeric-0.02/README
Scalar-Util-Numeric-0.02/t/
Scalar-Util-Numeric-0.02/t/pod.t
Scalar-Util-Numeric-0.02/t/Scalar-Util-Numeric.t
Removing previously used /home/jmm/.cpan/build/Scalar-Util-Numeric-0.02
CPAN.pm: Going to build C/CH/CHOCOLATE/Scalar-Util-Numeric-0.02.tar.gz
Checking if your kit is complete...
Looks good
Writing Makefile for Scalar::Util::Numeric
cp lib/Scalar/Util/Numeric.pm blib/lib/Scalar/Util/Numeric.pm
AutoSplitting blib/lib/Scalar/Util/Numeric.pm (blib/lib/auto/Scalar/Util/Numeric)
/usr/bin/perl /usr/share/perl/5.8/ExtUtils/xsubpp -typemap /usr/share/perl/5.8/ExtUtils/typemap Numeric.xs > Numeric.xsc && mv Numeric.xsc Numeric.c
cc -c -D_REENTRANT -D_GNU_SOURCE -DTHREADS_HAVE_PIDS -DDEBIAN -fno-strict-aliasing -pipe -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -O3 -DVERSION=\"0.02\" -DXS_VERSION=\"0.02\" -fPIC "-I/usr/lib/perl/5.8/CORE" Numeric.c
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:420:24: error: sys/types.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:451:19: error: ctype.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:463:23: error: locale.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:480:20: error: setjmp.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:486:26: error: sys/param.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:491:23: error: stdlib.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:496:23: error: unistd.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:776:23: error: string.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:925:27: error: netinet/in.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:929:26: error: arpa/inet.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:939:25: error: sys/stat.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:961:21: error: time.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:968:25: error: sys/time.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:975:27: error: sys/times.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:982:19: error: errno.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:997:25: error: sys/socket.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:1024:21: error: netdb.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:1127:24: error: sys/ioctl.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:1156:23: error: dirent.h: No such file or directory
In file included from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/syslimits.h:7,
from /usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:11,
from /usr/lib/perl/5.8/CORE/perl.h:1510,
from Numeric.xs:2:
/usr/lib/gcc/i486-linux-gnu/4.2.3/include/limits.h:122:61: error: limits.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/perl.h:2120,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/handy.h:136:25: error: inttypes.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/perl.h:2284,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/unixish.h:106:21: error: signal.h: No such file or directory
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:2421:33: error: pthread.h: No such file or directory
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:2423: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_os_thread’
/usr/lib/perl/5.8/CORE/perl.h:2424: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_mutex’
/usr/lib/perl/5.8/CORE/perl.h:2425: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_cond’
/usr/lib/perl/5.8/CORE/perl.h:2426: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘perl_key’
In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51,
from /usr/lib/perl/5.8/CORE/perl.h:2733,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perlio.h:65:19: error: stdio.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/iperlsys.h:51,
from /usr/lib/perl/5.8/CORE/perl.h:2733,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perlio.h:259: error: expected ‘)’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlio.h:262: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlio.h:265: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlio.h:268: error: expected declaration specifiers or ‘...’ before ‘FILE’
In file included from /usr/lib/perl/5.8/CORE/perl.h:2747,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/sv.h:389: error: expected specifier-qualifier-list before ‘DIR’
In file included from /usr/lib/perl/5.8/CORE/op.h:497,
from /usr/lib/perl/5.8/CORE/perl.h:2754,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/reentr.h:72:20: error: pwd.h: No such file or directory
/usr/lib/perl/5.8/CORE/reentr.h:75:20: error: grp.h: No such file or directory
/usr/lib/perl/5.8/CORE/reentr.h:85:26: error: crypt.h: No such file or directory
/usr/lib/perl/5.8/CORE/reentr.h:90:27: error: shadow.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/op.h:497,
from /usr/lib/perl/5.8/CORE/perl.h:2754,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/reentr.h:612: error: field ‘_crypt_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:620: error: field ‘_drand48_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:624: error: field ‘_grent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:635: error: field ‘_hostent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:654: error: field ‘_netent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:669: error: field ‘_protoent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:684: error: field ‘_pwent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:695: error: field ‘_servent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:710: error: field ‘_spent_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:721: error: field ‘_gmtime_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:724: error: field ‘_localtime_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:771: error: field ‘_random_struct’ has incomplete type
/usr/lib/perl/5.8/CORE/reentr.h:772: error: expected specifier-qualifier-list before ‘int32_t’
In file included from /usr/lib/perl/5.8/CORE/perl.h:2756,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/av.h:13: error: expected specifier-qualifier-list before ‘ssize_t’
In file included from /usr/lib/perl/5.8/CORE/perl.h:2759,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/scope.h:232: error: expected specifier-qualifier-list before ‘sigjmp_buf’
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:2931: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getuid’
/usr/lib/perl/5.8/CORE/perl.h:2932: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘geteuid’
/usr/lib/perl/5.8/CORE/perl.h:2933: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getgid’
/usr/lib/perl/5.8/CORE/perl.h:2934: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘getegid’
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:3238:22: error: math.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/perl.h:3881,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/thrdvar.h:85: error: field ‘Tstatbuf’ has incomplete type
/usr/lib/perl/5.8/CORE/thrdvar.h:86: error: field ‘Tstatcache’ has incomplete type
/usr/lib/perl/5.8/CORE/thrdvar.h:91: error: field ‘Ttimesbuf’ has incomplete type
In file included from /usr/lib/perl/5.8/CORE/perl.h:3883,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected specifier-qualifier-list before ‘time_t’
In file included from /usr/lib/perl/5.8/CORE/perl.h:3950,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘mode_t’
/usr/lib/perl/5.8/CORE/proto.h:128: error: expected declaration specifiers or ‘...’ before ‘uid_t’
/usr/lib/perl/5.8/CORE/proto.h:297: error: expected declaration specifiers or ‘...’ before ‘off64_t’
/usr/lib/perl/5.8/CORE/proto.h:299: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_sysseek’
/usr/lib/perl/5.8/CORE/proto.h:300: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_do_tell’
/usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘gid_t’
/usr/lib/perl/5.8/CORE/proto.h:411: error: expected declaration specifiers or ‘...’ before ‘uid_t’
/usr/lib/perl/5.8/CORE/proto.h:736: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_my_fork’
/usr/lib/perl/5.8/CORE/proto.h:1020: error: expected declaration specifiers or ‘...’ before ‘pid_t’
/usr/lib/perl/5.8/CORE/proto.h:1300: error: expected declaration specifiers or ‘...’ before ‘pid_t’
/usr/lib/perl/5.8/CORE/proto.h:1456: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/proto.h:2001: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_read’
/usr/lib/perl/5.8/CORE/proto.h:2002: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_write’
/usr/lib/perl/5.8/CORE/proto.h:2003: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_unread’
/usr/lib/perl/5.8/CORE/proto.h:2004: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘Perl_PerlIO_tell’
/usr/lib/perl/5.8/CORE/proto.h:2005: error: expected declaration specifiers or ‘...’ before ‘off64_t’
In file included from /usr/lib/perl/5.8/CORE/perl.h:3988,
from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_thr_key’
/usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_op_mutex’
/usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘PL_dollarzero_mutex’
/usr/lib/perl/5.8/CORE/perl.h:4485:24: error: sys/ipc.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:4486:24: error: sys/sem.h: No such file or directory
/usr/lib/perl/5.8/CORE/perl.h:4611:24: error: sys/file.h: No such file or directory
In file included from /usr/lib/perl/5.8/CORE/perlapi.h:38,
from /usr/lib/perl/5.8/CORE/XSUB.h:349,
from Numeric.xs:3:
/usr/lib/perl/5.8/CORE/intrpvar.h:66: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/intrpvar.h:237: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/intrpvar.h:238: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/intrpvar.h:239: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/intrpvar.h:240: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
In file included from /usr/lib/perl/5.8/CORE/perlapi.h:39,
from /usr/lib/perl/5.8/CORE/XSUB.h:349,
from Numeric.xs:3:
/usr/lib/perl/5.8/CORE/perlvars.h:31: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlvars.h:48: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
/usr/lib/perl/5.8/CORE/perlvars.h:52: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
In file included from Numeric.xs:4:
ppport.h:3042:1: warning: "PERL_UNUSED_DECL" redefined
In file included from Numeric.xs:2:
/usr/lib/perl/5.8/CORE/perl.h:163:1: warning: this is the location of the previous definition
Numeric.c: In function ‘XS_Scalar__Util__Numeric_is_num’:
Numeric.c:20: error: invalid type argument of ‘unary *’
Numeric.c:20: error: invalid type argument of ‘unary *’
Numeric.c:20: error: invalid type argument of ‘unary *’
Numeric.c:22: error: invalid type argument of ‘unary *’
Numeric.c:24: error: invalid type argument of ‘unary *’
Numeric.xs:16: error: invalid type argument of ‘unary *’
Numeric.xs:17: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.xs:20: error: invalid type argument of ‘unary *’
Numeric.c:36: error: invalid type argument of ‘unary *’
Numeric.c:36: error: invalid type argument of ‘unary *’
Numeric.c: In function ‘XS_Scalar__Util__Numeric_uvmax’:
Numeric.c:43: error: invalid type argument of ‘unary *’
Numeric.c:43: error: invalid type argument of ‘unary *’
Numeric.c:43: error: invalid type argument of ‘unary *’
Numeric.c:45: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.xs:26: error: invalid type argument of ‘unary *’
Numeric.c:51: error: invalid type argument of ‘unary *’
Numeric.c:51: error: invalid type argument of ‘unary *’
Numeric.c: In function ‘boot_Scalar__Util__Numeric’:
Numeric.c:60: error: invalid type argument of ‘unary *’
Numeric.c:60: error: invalid type argument of ‘unary *’
Numeric.c:60: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:63: error: invalid type argument of ‘unary *’
Numeric.c:65: error: invalid type argument of ‘unary *’
Numeric.c:65: error: invalid type argument of ‘unary *’
Numeric.c:66: error: invalid type argument of ‘unary *’
Numeric.c:66: error: invalid type argument of ‘unary *’
Numeric.c:67: error: invalid type argument of ‘unary *’
Numeric.c:67: error: invalid type argument of ‘unary *’
Numeric.c:67: error: invalid type argument of ‘unary *’
Numeric.c:67: error: invalid type argument of ‘unary *’
make: *** [Numeric.o] Error 1
/usr/bin/make -- NOT OK
Running make test
Can't test without successful make
Running make install
make had returned bad status, install seems impossible
jmm@freekbox:~/bfwsandbox/sa/angel/astroportal/dtu8e/resources$
</pre>
| <p>You're missing your C library development headers. You should install a package that has them. These are necessary to install this module because it has to compile some non-perl C code and needs to know more about your system.</p>
<p>I can't tell what kind of operating system you're on, but it looks like linux. If it's debian, you should be able to use apt-get to install the 'libc6-dev' package. That will contain the headers you need to compile this module. On other types of linux there will be a similarly named package.</p>
| <p>It can't find basic system headers. Either your include path is seriously messed up, or the headers are not installed.</p>
| 10,090 |
<p>These days, more languages are using unicode, which is a good thing. But it also presents a danger. In the past there where troubles distinguising between 1 and l and 0 and O. But now we have a complete new range of similar characters.</p>
<p>For example:</p>
<pre><code>ì, î, ï, ı, ι, ί, ׀ ,أ ,آ, ỉ, ﺃ
</code></pre>
<p>With these, it is not that difficult to create some very hard to find bugs.</p>
<p>At my work, we have decided to stay with the ANSI characters for identifiers. Is there anybody out there using unicode identifiers and what are the experiences?</p>
| <p>Besides the similar character bugs you mention and the technical issues that might arise when using different editors (w/BOM, wo/BOM, different encodings in the same file by copy pasting which is only a problem when there are actually characters that cannot be encoded in ASCII and so on), I find that it's not worth using Unicode characters in identifiers. English has become the lingua franca of development and you should stick to it while writing code. </p>
<p>This I find particularly true for code that may be seen anywhere in the world by any developer (open source, or code that is sold along with the product).</p>
| <p>It depends on the language you're using. In Python, for example, is easierfor me to stick to unicode, as my aplications needs to work in several languages. So when I get a file from someone (something) that I don't know, I assume Latin-1 and translate to Unicode. </p>
<p>Works for me, as I'm in latin-america.</p>
<p>Actually, once everithing is ironed out, the whole thing becomes a smooth ride.</p>
<p>Of course, this depends on the language of choice.</p>
| 37,577 |
<p>I am using XmlSerializer to write and read an object to xml in C#. I currently use the attributes <code>XmlElement</code> and <code>XmlIgnore</code> to manipulate the serialization of the object.</p>
<p>If my xml file is missing an xml element that I require, my object still deserializes (xml -> object) just fine. How do I indicate (preferably via Attributes) that a certain field is "required"?</p>
<p>Here is a sample method of what I am using currently:</p>
<pre><code>[XmlElement(ElementName="numberOfWidgets")]
public int NumberThatIsRequired {
set ...;
get ...;
}
</code></pre>
<p>My ideal solution would be to add something like an <code>XmlRequired</code> attribute. </p>
<p>Also, is there a good reference for what Attributes are available to manipulate the behavior of XmlSerializer?</p>
| <p>I've got an answer for the second part: <a href="http://msdn.microsoft.com/en-us/library/83y7df3e(VS.71).aspx" rel="nofollow noreferrer">"Attributes that control XML serialization"</a>.</p>
<p>Still investigating the first part...</p>
<p>EDIT: I strongly suspect you can't do this through XML deserialization itself. I've just run xsd.exe on a sample schema which includes a required attribute - and it's exactly the same if the attribute is marked as being optional. If there were a way of requiring properties to be set, I'd expect it to be implemented in that case.</p>
<p>I suspect you've basically got to just validate your tree of objects after deserializing it. Sorry about that...</p>
| <p>For extensibility reasons, <code>XmlSerializer</code> is very forgiving when it comes to deserialization; things like <code>[DefaultValue]</code>, <code>ShouldSerialize{Foo}</code> and <code>{Foo}Specified</code> are <em>mainly</em> used during <em>serialization</em> (the exception being <code>{Foo}Specified</code>, which is set during deserialization as well as queried during serialization).</p>
<p>As such; there isn't an easy way to do this, unless you implement <code>IXmlSerializable</code> and do it yourself. Richard shows an xsd option, which is also an option.</p>
| 32,453 |
<p>I have the task of developing an online examination software for a small university, I need to implement measures to prevent cheating...</p>
<p>What are your ideas on how to do this? </p>
<p>I would like to possibly disable all IE / firefox tabs, or some how log internet activity so I know if they are googling anwsers...is there any realistic way to do such things from a flex / web application?</p>
| <p>Simply put, <strong>no</strong> there is no realistic way to accomplish this if it is an online exam (assuming they are using their own computers to take the exam).</p>
| <p>Randomize questions, ask a random set of questions from a large bank... time the answers...</p>
<p>Unless you mean hacking your site, which is a different question.</p>
| 6,905 |
<p>Without the use of any external library, what is the simplest way to fetch a website's HTML content into a String?</p>
| <p>I'm currently using this:</p>
<pre><code>String content = null;
URLConnection connection = null;
try {
connection = new URL("http://www.google.com").openConnection();
Scanner scanner = new Scanner(connection.getInputStream());
scanner.useDelimiter("\\Z");
content = scanner.next();
scanner.close();
}catch ( Exception ex ) {
ex.printStackTrace();
}
System.out.println(content);
</code></pre>
<p>But not sure if there's a better way.</p>
| <p>Its not library but a tool named curl generally installed in most of the servers or you can easily install in ubuntu by </p>
<pre><code>sudo apt install curl
</code></pre>
<p>Then fetch any html page and store it to your local file like an example </p>
<pre><code>curl https://www.facebook.com/ > fb.html
</code></pre>
<p>You will get the home page html.You can run it in your browser as well.</p>
| 5,139 |
<p>Aside from trying</p>
<pre><code>perldoc <module name>
</code></pre>
<p>individually for any CPAN module that takes my fancy or going through the file system and looking at the directories I have no idea what modules we have installed. </p>
<p>What's the easiest way to just get a big list of every CPAN module installed? From the command line or otherwise.</p>
| <p>This is answered in the Perl FAQ, the answer which can be quickly found with <code>perldoc -q installed</code>. In short, it comes down to using <code>ExtUtils::Installed</code> or using <code>File::Find</code>, variants of both of which have been covered previously in this thread.</p>
<p>You can also find the FAQ entry <a href="http://perldoc.perl.org/perlfaq3.html#How-do-I-find-which-modules-are-installed-on-my-system%3f" rel="noreferrer">"How do I find which modules are installed on my system?"</a> in perlfaq3. You can see a list of all FAQ answers by looking in <a href="http://perldoc.perl.org/perlfaq.html" rel="noreferrer">perlfaq</a></p>
| <p>As you enter your Perl script you have all the installed modules as .pm files below the folders in @INC so a small bash script will do the job for you:</p>
<pre><code>#!/bin/bash
echo -e -n "Content-type: text/plain\n\n"
inc=`perl -e '$, = "\n"; print @INC;'`
for d in $inc
do
find $d -name '*.pm'
done
</code></pre>
| 14,071 |
<p>Has anyone managed to activate Gzip compression on a website in IIS6 ?
We're using Castle Monorail (it's very nice btw) and as a result have clean RESTful URLs with no extensions.....
..... and there's the rub -> as far as we can see we need extensions on our endpoints to allow gzip compression.</p>
<p>It seems the only way out is our own HTTPModule - does anyone else know of any other way ??</p>
<p>Cheers
ian</p>
| <p>Well I've found one way... it's a combination of the HTTPModule technique and Monorail filters.</p>
<p>So <a href="http://www.west-wind.com/WebLog/posts/102969.aspx" rel="nofollow noreferrer">the article above by Rick Strahl</a> is one of a number on the web that demonstrate using gzip / deflate compression. Lovely. Using these techniques with the <a href="http://www.castleproject.org/MonoRail/documentation/trunk/advanced/transformation.html" rel="nofollow noreferrer">a Monorail TransformFliter should work very nicely</a>.</p>
<p>Any other ways, or still got to craft code ?</p>
| <p>This is a great walk-through on enabling gzip compression in IIS6:
<a href="http://engineering.leads360.com/post/9301650692/http-compression-gzip-on-iis-6" rel="nofollow">http://engineering.leads360.com/post/9301650692/http-compression-gzip-on-iis-6</a></p>
| 48,608 |