instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>In XLST how would you find out the length of a node-set?</p>
|
<pre><code><xsl:variable name="length" select="count(nodeset)"/>
</code></pre>
|
<p>Generally in XSLT things aren't referred to as <code>Arrays</code>, since there is really no such thing in XSLT. The technical term is either <code>nodesets</code> (made up of zero or more nodes) or in XSLT 2.0 <code>sequences</code>.</p>
| 5,203
|
<p>I'm looking for something simple to use where the grammar is easy to define.</p>
|
<p>Although I've never used it before, <a href="http://www.antlr.org/" rel="nofollow noreferrer">ANTLR</a> has C# runtime.</p>
|
<p>System.Text.RegularExpressions?</p>
| 47,783
|
<p>I hear that tr1::result_of gets used frequently inside of Boost... I'm wondering if there are any good (simple) use cases for tr1::result_of I can use at home.</p>
|
<p>A description of result_of is given at <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1454.html" rel="nofollow noreferrer">open_std.org</a>. Microsoft has a quick example of a <a href="http://msdn.microsoft.com/en-us/library/bb982028.aspx" rel="nofollow noreferrer">unit test wrapper</a> that uses result_of.</p>
|
<p>It's useful when doing meta-programming. The only time I used it was in a wrapper function. If result_of<T>::type was void, the wrapper returned nothing. Otherwise it returns the whatever the wrapped function returns.</p>
| 23,542
|
<p>I am using xmlrpclib.ServerProxy to make RPC calls to a remote server. If there is not a network connection to the server it takes the default 10 seconds to return a socket.gaierror to my program. </p>
<p>This is annoying when doing development without a network connection, or if the remote server is down. Is there a way to update the timeout on my ServerProxy object?</p>
<p>I can't see a clear way to get access to the socket to update it.</p>
|
<p>An more straightforward solution is at:
<a href="http://www.devpicayune.com/entry/200609191448" rel="noreferrer">http://www.devpicayune.com/entry/200609191448</a></p>
<pre><code>import xmlrpclib
import socket
x = xmlrpclib.ServerProxy('http:1.2.3.4')
socket.setdefaulttimeout(10) #set the timeout to 10 seconds
x.func_name(args) #times out after 10 seconds
socket.setdefaulttimeout(None) #sets the default back
</code></pre>
|
<p>The following example works with Python 2.7.4.</p>
<pre><code>import xmlrpclib
from xmlrpclib import *
import httplib
def Server(url, *args, **kwargs):
t = TimeoutTransport(kwargs.get('timeout', 20))
if 'timeout' in kwargs:
del kwargs['timeout']
kwargs['transport'] = t
server = xmlrpclib.Server(url, *args, **kwargs)
return server
TimeoutServerProxy = Server
class TimeoutTransport(xmlrpclib.Transport):
def __init__(self, timeout, use_datetime=0):
self.timeout = timeout
return xmlrpclib.Transport.__init__(self, use_datetime)
def make_connection(self, host):
conn = xmlrpclib.Transport.make_connection(self, host)
conn.timeout = self.timeout
return connrpclib.Server(url, *args, **kwargs)
</code></pre>
| 48,678
|
<p>When trying to use GraphicsBuilder, I get a <code>java.lang.NoClassDefFoundError</code> for <code>groovy.swing.factory.BindProxyFactory</code>.</p>
<p>This is my environment:</p>
<pre><code>% java -version
java version "1.6.0_10"
Java(TM) SE Runtime Environment (build 1.6.0_10-b33)
Java HotSpot(TM) Server VM (build 11.0-b15, mixed mode)
% groovy --version
Groovy Version: 1.5.7 JVM: 1.6.0_10
% ls ~/.groovy/lib/graphicsbuilder*
graphicsbuilder-0.6.1.jar
...
</code></pre>
<p>And this is what I try to do:</p>
<pre><code> % groovysh
Groovy Shell (1.5.7, JVM: 1.6.0_10)
Type 'help' or '\h' for help.
-------------------------------------------------------------------------------
groovy:000> import groovy.swing.SwingBuilder
groovy:000> import groovy.swing.j2d.GraphicsBuilder
groovy:000> import groovy.swing.j2d.GraphicsPanel
groovy:000> def gb = new GraphicsBuilder()
ERROR java.lang.NoClassDefFoundError: groovy.swing.factory.BindProxyFactory
at groovysh_evaluate.run (groovysh_evaluate:5)
...
</code></pre>
<p>Where is BindProxyFactoryBean?</p>
|
<p>It's in the Groovy 1.6 builds, not the 1.5.7 builds. Apparently GfxBuilder 6.1 was built against the Groovy 1.6 codebase.</p>
|
<p>Yes, that is correct. Groovy 1.6.x is required for GfxBuilder 6.1 and onwards.</p>
| 37,689
|
<p>So, at my current job we're usually 1-3 developers, 1-2 art directors and 1 project manager on each project, with the smallest ones just being one of each and the larger ones being three developers and two art directors.</p>
<p>I'm looking for a software, combination of softwares or some type of service that will allow us to manage our projects individually, it's important that we're able to manage several projects at once within one system/piece of software (without going through a too complicated setup process for each project) since we usually have 2-3 ongoing projects in parallel. </p>
<p>We need to be able to integrate with SVN, Track bugs/features/request, Put up milestones and some type of agile management a´la SCRUM would be nice.</p>
<p>Preferably it should be able to run on Windows (without to much hassle, ever tried to put up Apache+Python+Svn+Trac on the same Windows 2003 server and get them all to run together? not fun.) since we mostly do .NET development and most of our servers run Windows 2003.</p>
|
<p>Since you seem to have a maximum of six people working in a single room - I'd give serious consideration to not using software at all. </p>
<p>A whiteboard & cork board for each project, plus a whole lot of index cards / stickies can go a long, long way towards meeting the project management needs of one or two small projects.</p>
<p>(Failing that - I've found basecamp a fairly lightweight tool for small projects - although it doesn't do any sort of source control integration. I've also heard good things about the latest FogBugz - but I've had such bad personal experiences of earlier versions I've not tried it yet myself)</p>
|
<p>I personally use <a href="http://www.basecamphq.com/?referrer=MITCHELSELLERS" rel="nofollow noreferrer">BaseCamp</a> for my company and have had great luck with it!</p>
<p><strong>Edit</strong> oops, I didn't notice the SVN requirement, BaseCamp can help with the other stuff.</p>
| 14,166
|
<p>I am using <code><input type="file" id="fileUpload" runat="server"></code> to upload a file in an ASP.NET application. I would like to limit the file type of the upload (example: limit to .xls or .xlsx file extensions). </p>
<p>Both JavaScript or server-side validation are OK (as long as the server side validation would take place before the files are being uploaded - there could be some very large files uploaded, so any validation needs to take place before the actual files are uploaded).</p>
|
<p>Seems like you are going to have limited options since you want the check to occur before the upload. I think the best you are going to get is to use javascript to validate the extension of the file. You could build a hash of valid extensions and then look to see if the extension of the file being uploaded existed in the hash.</p>
<p>HTML:</p>
<pre><code><input type="file" name="FILENAME" size="20" onchange="check_extension(this.value,"upload");"/>
<input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" />
</code></pre>
<p>Javascript:</p>
<pre><code>var hash = {
'xls' : 1,
'xlsx' : 1,
};
function check_extension(filename,submitId) {
var re = /\..+$/;
var ext = filename.match(re);
var submitEl = document.getElementById(submitId);
if (hash[ext]) {
submitEl.disabled = false;
return true;
} else {
alert("Invalid filename, please select another file");
submitEl.disabled = true;
return false;
}
}
</code></pre>
|
<p>Your only option seems to be client-side validation, because server side means the file was already uploaded. Also the MIME type is usually dictated by the file extension. </p>
<p>use a JavaScript Framework like jQuery to overload the onsubmit event of the form. Then check the extension. This will limit most attempts. However if a person changes an image to extension XLS then you will have a problem.</p>
<p>I don't know if this is an option for you, but you have more client side control when using something like Silverlight or Flash to upload. You may consider using one of these technologies for your upload process.</p>
| 9,749
|
<p>I'm trying to find the definition of a binary search tree and I keep finding different definitions everywhere. </p>
<p>Some say that for any given subtree the left child key is less than or equal to the root.</p>
<p>Some say that for any given subtree the right child key is greater than or equal to the root.</p>
<p>And my old college data structures book says "every element has a key and no two elements have the same key."</p>
<p>Is there a universal definition of a bst? Particularly in regards to what to do with trees with multiple instances of the same key.</p>
<p>EDIT: Maybe I was unclear, the definitions I'm seeing are</p>
<p>1) left <= root < right</p>
<p>2) left < root <= right</p>
<p>3) left < root < right, such that no duplicate keys exist.</p>
|
<p>Many algorithms will specify that duplicates are excluded. For example, the example algorithms in the MIT Algorithms book usually present examples without duplicates. It is fairly trivial to implement duplicates (either as a list at the node, or in one particular direction.)</p>
<p>Most (that I've seen) specify left children as <= and right children as >. Practically speaking, a BST which allows either of the right or left children to be equal to the root node, will require extra computational steps to finish a search where duplicate nodes are allowed.</p>
<p>It is best to utilize a list at the node to store duplicates, as inserting an '=' value to one side of a node requires rewriting the tree on that side to place the node as the child, or the node is placed as a grand-child, at some point below, which eliminates some of the search efficiency.</p>
<p>You have to remember, most of the classroom examples are simplified to portray and deliver the concept. They aren't worth squat in many real-world situations. But the statement, "every element has a key and no two elements have the same key", is not violated by the use of a list at the element node.</p>
<p>So go with what your data structures book said!</p>
<p>Edit:</p>
<p>Universal Definition of a Binary Search Tree involves storing and search for a key based on traversing a data structure in one of two directions. In the pragmatic sense, that means if the value is <>, you traverse the data structure in one of two 'directions'. So, in that sense, duplicate values don't make any sense at all.</p>
<p>This is different from BSP, or binary search partition, but not all that different. The algorithm to search has one of two directions for 'travel', or it is done (successfully or not.) So I apologize that my original answer didn't address the concept of a 'universal definition', as duplicates are really a distinct topic (something you deal with after a successful search, not as part of the binary search.)</p>
|
<p>The elements ordering relation <= is a <a href="http://en.wikipedia.org/wiki/Total_order" rel="nofollow">total order</a> so the relation must be reflexive but commonly a binary search tree (aka BST) is a tree without duplicates. </p>
<p>Otherwise if there are duplicates you need run twice or more the same function of deletion!</p>
| 38,588
|
<p>I'm not sure what the correct size should be.</p>
<p>Many sites seem to repeat that the apple-touch-icon should be 57x57 pixels but cite a broken link as their source.</p>
<p><a href="http://www.hanselman.com/blog/MakeYourWebsiteMobileAndIPhoneFriendlyAddHomeScreenIPhoneIconsAndAdjustTheViewPort.aspx" rel="noreferrer">Hanselman</a>'s and <a href="http://playgroundblues.com/posts/2008/jan/15/iphone-bookmark-iconage/" rel="noreferrer">playgroundblues</a>'s comments suggest different sizes including 163x163 and 60x60.</p>
<p>Apple's own <a href="http://www.apple.com/apple-touch-icon.png" rel="noreferrer">apple.com icon</a> is 129x129!</p>
<p>See my related question:
<a href="https://stackoverflow.com/questions/1505/how-do-i-give-my-web-sites-an-icon-for-iphone">How do I give my web sites an icon for iPhone?</a></p>
|
<p>It seems that Apple guidelines as of August 3, 2010 now include the "High resolution" images (for iPhone 4) in their "required" icon sizes.</p>
<p>Looks like we need to provide both a 57x57 and a 114x114 image now, as well as a 640x960 title image.</p>
<p>See <a href="http://developer.apple.com/iphone/library/documentation/userexperience/conceptual/mobilehig/IconsImages/IconsImages.html#//apple_ref/doc/uid/TP40006556-CH14-SW2" rel="nofollow noreferrer">Custom Icon and Image Creation Guidelines</a> (Javascript required) which is part of a whole document:</p>
<ul>
<li><a href="https://developer.apple.com/library/ios/documentation/userexperience/conceptual/mobilehig/MobileHIG.pdf" rel="nofollow noreferrer">iOS Human Interface Guidelines (2013; by Apple Inc; PDF; 26,3 MB)</a></li>
</ul>
|
<p>I don't think there is a "correct size". Since the iPhone really is running OSX, the icon rendering system is pretty robust. As long as you give it a high-quality image with the right aspect ratio and a resolution at least as high as the actual output will be, the OS will downscale very cleanly. My site uses a 158x158 and the icon looks pixel-perfect on the iPhone screen.</p>
| 2,391
|
<p>I don't need this, obviously; I'm just curious about what's going on here. Am I missing
something simple? Can I rely on this behaviour in all versions of Perl?)</p>
<p>Perl v5.8.8:</p>
<pre><code>%h = ( 0=>'zero', 1=>'one', 2=>'two' );
while ($k = each %h) {
$v = delete $h{$k};
print "deleted $v; remaining: @h{0..2}\n";
}
</code></pre>
<p>outputs</p>
<pre><code>deleted one; remaining: zero two
deleted zero; remaining: two
deleted two; remaining:
</code></pre>
<p><code>man perlfunc</code> (each) does not explain why the
while loop continues when <code>$k</code> is assigned 0.
The code behaves as if the condition on the <code>while</code> loop
were <code>($k = each %h, defined $k)</code>.</p>
<p>If the loop condition is actually changed to
<code>($k = each %h, $k)</code> then it does indeed
stop at <code>$k = 0</code> as expected.</p>
<p>It also stops at <code>$k = 0</code> for the following
reimplementation of <code>each</code>:</p>
<pre><code>%h = ( 0=>'zero', 1=>'one', 2=>'two' );
sub each2 {
return each %{$_[0]};
}
while ($k = each2 \%h) {
$v = delete $h{$k};
print "deleted $v; remaining: @h{0..2}\n";
}
</code></pre>
<p>outputs just:</p>
<pre><code>deleted one; remaining: zero two
</code></pre>
|
<p>You're calling <code>each</code> in scalar context, so it's not working because of a list return value.</p>
<p>Just like</p>
<pre><code>while ($line = <FILE>)
</code></pre>
<p>is special-cased to add an implicit <code>defined</code>, so is</p>
<pre><code>while ($key = each %hash)
</code></pre>
<p>In 5.8.8, that happens in op.c, lines 3760-3766:</p>
<pre><code>case OP_SASSIGN:
if (k1->op_type == OP_READDIR
|| k1->op_type == OP_GLOB
|| (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
|| k1->op_type == OP_EACH)
expr = newUNOP(OP_DEFINED, 0, expr);
break;
</code></pre>
<p>I'm not sure if this applies to all versions of Perl 5.</p>
<p>See also: <a href="http://www.perlmonks.org/?node_id=132451" rel="noreferrer">When does while() test for defined vs truth</a> on PerlMonks. I can't find where this is mentioned in the Perl docs (the <code><FILE></code> case is mentioned, but I don't see the <code>each</code> case).</p>
|
<p>Thanks, cjm.
It was clear some kind of implicit addition of a <code>defined</code>
was going on like that for glob but not where it was
documented. Now at least I know the limited cases in which
that special handling applies.</p>
<p>But the information should be in the perlfunc documentation,
not just the Perl source code!</p>
| 27,210
|
<p>I have two tables, <strong>Book</strong> and <strong>Tag</strong>, and books are tagged using the association table <strong>BookTag</strong>. I want to create a report that contains a list of books, and for each book a list of the book's tags. Tag IDs will suffice, tag names are not necessary.</p>
<p>Example:</p>
<pre><code>Book table:
Book ID | Book Name
28 | Dracula
BookTag table:
Book ID | Tag ID
28 | 101
28 | 102
</code></pre>
<p>In my report, I'd like to show that book #28 has the tags 101 and 102:</p>
<pre><code>Book ID | Book Name | Tags
28 | Dracula | 101, 102
</code></pre>
<p>Is there a way to do this in-line, without having to resort to functions or stored procedures? I am using SQL Server 2005.</p>
<p><em>Please note that the same question already has been asked in <a href="https://stackoverflow.com/questions/111341/combine-multiple-results-in-a-subquery-into-a-single-comma-separated-value">Combine multiple results in a subquery into a single comma-separated value</a>, but the solution involves creating a function. I am asking if there is a way to solve this without having to create a function or a stored procedure.</em></p>
|
<p>You can almost do it. The only problem I haven't resolved is the comma delimiter. Here is a query on a similar structure that separates the tags using a space.</p>
<pre><code>SELECT em.Code,
(SELECT et.Name + ' ' AS 'data()'
FROM tblEmployeeTag et
JOIN tblEmployeeTagAssignment eta ON et.Id = eta.EmployeeTag_Id AND eta.Employee_Id = em.id
FOR XML PATH('') ) AS Tags
FROM tblEmployee em
</code></pre>
<p>Edit:</p>
<p>Here is the complete version using your tables and using a comma delimiter:</p>
<pre><code>SELECT bk.Id AS BookId,
bk.Name AS BookName,
REPLACE((SELECT LTRIM(STR(bt.TagId)) + ', ' AS 'data()'
FROM BookTag bt
WHERE bt.BookId = bk.Id
FOR XML PATH('') ) + 'x', ', x','') AS Tags
FROM Book bk
</code></pre>
<p>I suppose for future reference I should explain a bit about what is going on. The 'data()' column name is a special value that is related to the FOR XML PATH statement. It causes the XML document to be rendered as if you did an .InnerText on the root node of the resulting XML.<br>
The REPLACE statement is a trick to remove the trailing comma. By appending a unique character (I randomly chose 'x') to the end of the tag list I can search for comma-space-character and replace it with an empty string. That allows me to chop off just the last comma. This assumes that you are never going to have that sequence of characters in your tags.</p>
|
<p>Unless you know what the tag ids/names are and can hard code them into your query, I'm afraid the answer is no.</p>
| 21,026
|
<h1>Premise</h1>
<p>I believe that there is a way to objectively define "Good" and "Bad" Object-Oriented design techniques and that, as a community we can determine what these are. This is an academic exercise. If done with seriousness and resolve, I believe it can be of great benefit to the community as a whole. The community will benefit by having a place we can all point to to say, "This technique is 'Good' or 'Bad' and we should or should not use it unless there are special circumstances."</p>
<h1>Plan</h1>
<p>For this effort, we should focus on Object-Oriented principles (as opposed to Functional, Set-based, or other type of languages).</p>
<p>I'm not planning on accepting one answer, instead I'd like the answers to contribute to the final collection or be a rational debate of the issues.</p>
<p>I realize that this may controversial, but I believe we can iron something out. There are exceptions to most every rule and I believe this is where the disagreement will fall. We should make declarations and then note relevant exceptions and objections from dissenters.</p>
<h1>Basis</h1>
<p>I'd like to take a stab at defining "Good" and "Bad":</p>
<ul>
<li><p>"Good" - This technique will work the first time and be a lasting solution. It will be easy to change later and will pay the time investment of its implementation quickly. It can be consistently applied and easily recognized by maintenance programmers in the future. Overall, it contributes to the good function and lowers cost of maintenance over the life of the product.</p>
</li>
<li><p>"Bad" - This technique may work in the short term, but soon becomes a liability. It is immediately difficult to change or becomes more difficult over time. The initial investment may be small or large, but it quickly becomes a growing cost, eventually becoming a sunk cost and must be removed or worked around constantly. It is subjectively applied and inconsistent and may be a surprise or not easily recognizable by maintenance programmers in the future. Overall, it contributes to the ultimate increasing cost of maintaining and/or operating the product and inhibits or prevents changes to the product. By inhibiting or preventing change, it becomes not just a direct cost, but an opportunity cost and a significant liability.</p>
</li>
</ul>
<h1>Starter</h1>
<p>As an example of what I think a good contribution would look like, I'd like to propose a "Good" principle:</p>
<h2>Separation of Concerns</h2>
<p>[Short description]</p>
<h3>Example</h3>
<p>[Code or some other type of example]</p>
<h3>Goals</h3>
<p>[Explanation of what problems this principle prevents]</p>
<h3>Applicability</h3>
<p>[Why, where, and when would I use this principle?]</p>
<h3>Exceptions</h3>
<p>[When wouldn't I use this principle, or where might it actually be harmful?]</p>
<h3>Objections</h3>
<p>[Note any dissenting opinions or objections from the community here]</p>
|
<p>Separation of Concerns</p>
<h2>Prefer Aggregation to Mixin-style Inheritance</h2>
<p>While functionality can be gained by inheriting from a utility class, in many cases it can all be gained using a member of said class.</p>
<h3>Example (Boost.Noncopyable):</h3>
<p>Boost.Noncopyable is a C++ class that lacks a copy constructor or assignment operator. It can be used as a base class to prevent the subclass from being copied or assigned (this is the common behavior). It can also be used as a direct member</p>
<p>Convert this:</p>
<pre><code>class Foo : private boost::noncopyable { ... };
</code></pre>
<p>To this:</p>
<pre><code>class Foo {
...
private:
boost::noncopyable noncopyable_;
};
</code></pre>
<h3>Example (Lockable object):</h3>
<p>Java introduced the <code>synchronized</code> keyword as an idiom to allow any object to be used in a threadsafe manner. This can be mirrored in other languages to provide mutexes to arbitrary objects. A common example is data structures:</p>
<pre><code>class ThreadsafeVector<T> : public Vector<T>, public Mutex { ... };
</code></pre>
<p>Instead, the two classes could be aggregated together.</p>
<pre><code>struct ThreadsafeVector<T> {
Vector<T> vector;
Mutex mutex;
}
</code></pre>
<h2>Goals</h2>
<p>Inheritance is frequently abused as a code-reuse mechanism. If inheritance is used for anything besides an Is-A relationship, overall code clarity is reduced.</p>
<p>With deeper chains, mixin base classes greatly increase the likelihood of a "Diamond of Death" scenario, wherein a subclass ends up inheriting multiple copies of a mixin class.</p>
<h2>Applicability</h2>
<p>Any language that supports multiple inheritance.</p>
<h2>Exceptions</h2>
<p>Any case where the mixin class provides or requires overloading members. In this case, inheritance usually implies an Is-Implemented-In-Terms-Of relationship, and an aggregate will not be sufficient.</p>
<h2>Objections</h2>
<p>The result of this transformation may lead to public members (e.g. <code>MyThreadSafeDataStructure</code> may have a publicly-accessible <code>Mutex</code> as a component).</p>
|
<p>I think the short answer is that "good" OO designs are robust under change, with the least code breakage for any requirements change. If you consider all the usual rules, they all tend to that same conclusion.</p>
<p>The difficulty is that you can't evaluate the "goodness" of the design without context; it is, I believe, a theorem that for any modularization, there exists a change in requirements that will maximize breakage, causing every class to be touched in each method. </p>
<p>If you want to be rigorous about it, you can develop a collection of "change cases" and order them in probability order, so that you minimize the breakage for the highest probability changes. </p>
<p>On most cases, though, some well-developed intuition helps a lot: device-specific or platform specific things tend to change, business rules and business process tend to change, while the implementations of, say, arithmetic, change very rarely. (Not, as you might imagine, never. Consider, for example, a business system that may or may not be able to make use of platform-supported BCD arithmetic.)</p>
| 47,864
|
<p>I am using RRDtool for storing data for displaying graphs. I update the RRD by RRDs::update and this fails when trying to rewrite the information, means update data for a time in the past (e.g. someone moved the system timer back). The error I get is: </p>
<pre><code>ERROR: Cannot update /opt/dashboard/rrd/Disk/192.168.120.168_disk_1.rrd with
'1228032301:24:24' illegal attempt to update using time 1228032301 when last
update time is 1228050001 (minimum one second step)
</code></pre>
<p>I want to always allow the rewrite, how can I do this?</p>
|
<p>rrdtool does not write your input into the rrd file. It rather samples what you enter and then stores the resulting datapoints. So providing 'old data' to rrdtool update will not work in the same way, as you can not easily skip back in a sound recording to 'fix' a few bad notes.</p>
<p>Obviously there are ways to alter old data, the way todo this in rrdtool, is to 'dump' the rrd file to xml, modify the content and 'restore' it. Not something one would like todo on a regular basis.</p>
|
<p>According to the RRD documentation, that timestamp number <strong>must</strong> increase with each update. Given your constraints, I'd modify your update routine so that if the update fails, you catch the exception and redo the update with the time field set to 'N'. That will make RRDtool use the current time as the update time.</p>
<p>Alternatively, if you don't want to deal with the catch-and-retry code, just modify your update code to always use 'N' as the time value -- then the update will always work.</p>
<p>It may be helpful to have a quick look at the documentation for the RRDtool <a href="http://oss.oetiker.ch/rrdtool/doc/rrdupdate.en.html" rel="nofollow noreferrer">update command</a>.</p>
| 42,584
|
<p>I have classX: </p>
<p>Sub New(ByVal item_line_no As String, ByVal item_text As String)</p>
<pre><code> ' check to ensure that the parameters do not exceed the file template limits
Select Case item_line_no.Length
Case Is > m_item_line_no_capacity
Throw New ArgumentOutOfRangeException(item_line_no, "Line No exceeds 4 characters")
Case Else
Me.m_item_line_no = item_line_no
End Select
Select Case item_text.Length
Case Is > m_item_free_text_capacity
Throw New ArgumentOutOfRangeException("Free Text Exceeds 130 characters")
Case Else
Me.m_item_free_text = item_text
End Select
End Sub
</code></pre>
<p>and the following unti to test one point of failure</p>
<pre><code><ExpectedException(GetType(ArgumentOutOfRangeException), "Line No exceeds 4 characters")> _
<Test()> _
Sub testLineNoExceedsMaxLength()
Dim it As New X("aaaaa", "Test")
End Sub
</code></pre>
<p>When I run the test I expect to get the message thrown in the exception "Line No exceeds 4 characters"</p>
<p>However the unit test fails with the following message</p>
<pre><code>RecordTests.testLineNoExceedsMaxLength : FailedExpected exception message: Line No exceeds 4 characters
got: Line No exceeds 4 characters
Parameter name: aaaaa
</code></pre>
<p>I think the something simple but it driving me insane. </p>
<p>NOTE: in the declaration of the ExpectedException I get an obsolete warning stating that instead of </p>
<pre><code><ExpectedException(GetType(ArgumentOutOfRangeException), "Line No exceeds 4 characters")>
</code></pre>
<p>it should be </p>
<pre><code><ExpectedException(GetType(ArgumentOutOfRangeException), ExpectedException="Line No exceeds 4 characters")>
</code></pre>
<p>However this throws a ExpectedException is not declared error! </p>
|
<p>Ok. Just run this.</p>
<p>The message for the exception is:</p>
<blockquote>
<p><strong>Line No exceeds 4 characters</strong></p>
<p><strong>Parameter name: aaaaa</strong></p>
</blockquote>
<p>(Including the line break)</p>
<p>You need to specify this all of this as the expected message:</p>
<pre><code><ExpectedException(GetType(ArgumentOutOfRangeException), ExpectedMessage="Line No exceeds 4 characters" & VbCrLf & "Parameter name: aaaaa")>
</code></pre>
|
<p><s>The <code>ExpectedExceptionAttribute</code> is deprecated - i.e. you shouldn't use it at all. The best reference I could quickly find about this was this post (the original article is here).</s></p>
<p>Your unit test would be a lot clearer if it was re-written:</p>
<pre><code><Test()> _
Sub testLineNoExceedsMaxLength()
Try
Dim it As New X("aaaaa", "Test")
Catch ex as ArgumentOutOfRangeExcpetion
Assert.That ( ex.Message, Is.Equal("Line No exceeds 4 characters") )
End Try
End Sub
</code></pre>
<p>See also these articles </p>
<ul>
<li><a href="http://steve.emxsoftware.com/TDD/NUnit+and+the+ExpectedExceptionAttribute" rel="nofollow noreferrer">This one</a>, and</li>
<li><a href="http://web.archive.org/web/20040228223704/http://cgi.skizz.plus.com/blog/dev/archives/000075.html" rel="nofollow noreferrer" title="Praise god for the Way Back Machine">This one</a>.</li>
</ul>
| 33,653
|
<h2>The problem:</h2>
<p>We use a program written by our biggest customer to receive orders, book tranports and do other order-related stuff. We have no other chance but to use the program and the customer is very unsupportive when it comes to problems with their program. We just have to live with the program.</p>
<p>Now this program is most of the time extremely slow when using it with two or more user so I tried to look behind the curtain and find the source of the problem.</p>
<h2>Some points about the program I found out so far:</h2>
<ul>
<li>It's written in VB 6.0</li>
<li>It uses a password-protected Access-DB (Access 2000 MDB) that is located a folder on one user's machine.</li>
<li>That folder is shared over the network and used by all other users.</li>
<li>It uses the msjet40.dll version 4.00.9704 to communicate with access. I guess it's ADO?</li>
</ul>
<p>I also used <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="noreferrer">Process Monitor</a> to monitor file access and found out why the program is so slow: it is doing thousands of read operations on the mdb-file, even when the program is idle. Over the network this is of course tremendously slow:</p>
<p><a href="http://img217.imageshack.us/img217/1456/screenshothw5.png" rel="noreferrer">Process Monitor Trace http://img217.imageshack.us/img217/1456/screenshothw5.png</a></p>
<h2>The real question:</h2>
<p>Is there any way to monitor the queries that are responsible for the read activity? Is there a trace flag I can set? Hooking the JET DLL's? I guess the program is doing some expensive queries that are causing JET to read lots of data in the process.</p>
<p>PS: I already tried to put the mdb on our company's file server with the success that accessing it was even slower than over the local share. I also tried changing the locking mechanisms (opportunistic locking) on the client with no success.</p>
<p>I want to know what's going on and need some hard facts and suggestions for our customer's developer to help him/her make the programm faster.</p>
|
<p>To get your grubby hands on exactly what Access is doing query-wise behind the scenes there's an undocumented feature called JETSHOWPLAN - when switched on in the registry it creates a <code>showplan.out</code> text file. The details are in
<a href="https://www.techrepublic.com/article/use-microsoft-jets-showplan-to-write-more-efficient-queries/" rel="nofollow noreferrer">this TechRepublic article</a> <a href="https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-22-5064388.html" rel="nofollow noreferrer">alternate</a>, summarized here:</p>
<blockquote>
<p>The ShowPlan option was added to Jet 3.0, and produces a text file
that contains the query's plan. (ShowPlan doesn't support subqueries.)
You must enable it by adding a Debug key to the registry like so:</p>
<pre><code>\\HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\JET\4.0\Engines\Debug
</code></pre>
<p>Under the new Debug key, add a string data type named <code>JETSHOWPLAN</code>
(you must use all uppercase letters). Then, add the key value <code>ON</code> to
enable the feature. If Access has been running in the background, you
must close it and relaunch it for the function to work.</p>
<p>When ShowPlan is enabled, Jet creates a text file named <code>SHOWPLAN.OUT</code>
(which might end up in your <code>My Documents</code> folder or the current
default folder, depending on the version of Jet you're using) every
time Jet compiles a query. You can then view this text file for clues
to how Jet is running your queries. </p>
<p>We recommend that you disable this feature by changing the key's value
to <code>OFF</code> unless you're specifically using it. Jet appends the plan to
an existing file and eventually, the process actually slows things
down. Turn on the feature only when you need to review a specific
query plan. Open the database, run the query, and then disable the
feature.</p>
</blockquote>
<p>For tracking down nightmare problems it's unbeatable - it's the sort of thing you get on your big expensive industrial databases - this feature is cool - it's lovely and fluffy - it's my friend… ;-)</p>
|
<p>It is not possible without the help of the developers. Sorry.</p>
| 18,468
|
<p>This may be a very stupid question so I apologize in advance. It seems that Instruments only works for me when using the iPhone Simulator. Is there something special to getting it working when tethering the application to the iPhone? Or is that even possible? I launch the application the normal way through the Run->Start with performace tool, etc., then see it's installing the app to my provisioned iPhone, then it launches Instruments but nothing. I thought since it's connected via USB it would be but can't get it to work.</p>
|
<p>My device worked with Instruments after following these steps:</p>
<ol>
<li>Unplug the iPhone.</li>
<li>In XCode, open the Organizer.</li>
<li>Delete the device.</li>
<li>Plug device in.</li>
<li>Answer yes when asked if you want to use device for development.</li>
</ol>
|
<p>It works with the device, in XCode, go to the top bar, and i think it's inside "build" (don't have a mac infront of me so sorry for the vague position) in there you select "run application with performance tool" (something like that) and that will start a new Instruments' session connected to the hardware. You can't (as far as I know) just connect directly from Instruments to the device, it needs to be through XCode.</p>
| 49,792
|
<p>I am getting the following error when trying to install Visual Studio 2005 on my 64bit, Vista computer:</p>
<blockquote>
<p>"1305.Error reading from file
C:\Program Files (x86)\Microsoft
Visual Studio 8\Microsoft Visual
Studio 2005 Standard Edition -
ENU\SITSetup.dll"</p>
</blockquote>
<p>I have successfully used the same DVD's to install Visual Studio on my old XP machine, and I can find the file (SITSetup.dll) on the DVD...and copy it off...so I don't think this is a case of having a bad DVD. At the time the error message pops up, I can see the file on my hard-drive, but it has a 0 size.</p>
<p>I've Googled this problem, and found some ideas, but nothing has worked thus far. Any suggestions would be appreciated.</p>
|
<p>I have to confess on this..especially since someone voted for the question. </p>
<p>Everything I said in my original posting about using the disks successfully in the past -was true. However, after innumerable shots at trying to get this install to work, I finally went back and looked at the DVD, and found that either myself, or one of my kids, left traces of food stuck to the underside of the DVD. After cleaning the DVD off, the install worked fine. This is embarrassing.</p>
<p>I assumed the DVD was fine because I had used it before, as well as being able to copy files off it. However, the last time I used it was years ago, and sometime in between then and now...something got on it. I guess the lesson here is never skip the basic checks!</p>
|
<p>I just installed it yesterday on my Vista box (32-bit, which may be the problem). It seemed to go through fine so I don't know what to tell you other than than when I first launched the app it notified me of "known compatibility issues" and recommended that I install both the SP1 and Vista SP! updates. No further issues past that.</p>
<p>As such, I would suspect either a problem with the 64 bit OS (though <a href="http://www.microsoft.com/windows/compatibility/Details.aspx?type=Software&p=Microsoft%20Visual%20Studio%202005%20Standard&v=Microsoft&uid=8&pf=0&pi=5&c=Development%20Tools&sc=all&os=64-bit" rel="nofollow noreferrer">Microsoft says it's fine...</a>) or other software on your machine. If you have a virus scanner running, for instance, disable it while installing.</p>
| 36,837
|
<p>I wondered whether anybody knows how to obtain membership of local groups on a remote server programmatically via C#. Would this require administrator permissions? And if so is there any way to confirm the currently logged in user's membership (or not) of these groups?</p>
|
<p><a href="http://www.codeproject.com/KB/system/everythingInAD.aspx" rel="nofollow noreferrer">Howto: (Almost) Everything In Active Directory via C#</a> is very helpfull and also includes instructions on how to iterate AD members in a group.</p>
<pre><code>public ArrayList Groups(string userDn, bool recursive)
{
ArrayList groupMemberships = new ArrayList();
return AttributeValuesMultiString("memberOf", userDn,
groupMemberships, recursive);
}
</code></pre>
<p>You will also need this function:</p>
<pre><code>public ArrayList AttributeValuesMultiString(string attributeName,
string objectDn, ArrayList valuesCollection, bool recursive)
{
DirectoryEntry ent = new DirectoryEntry(objectDn);
PropertyValueCollection ValueCollection = ent.Properties[attributeName];
IEnumerator en = ValueCollection.GetEnumerator();
while (en.MoveNext())
{
if (en.Current != null)
{
if (!valuesCollection.Contains(en.Current.ToString()))
{
valuesCollection.Add(en.Current.ToString());
if (recursive)
{
AttributeValuesMultiString(attributeName, "LDAP://" +
en.Current.ToString(), valuesCollection, true);
}
}
}
}
ent.Close();
ent.Dispose();
return valuesCollection;
}
</code></pre>
<p>If you do now want to use this AD-method, you could use the info in this article, but it uses unmanaged code:</p>
<p><a href="http://www.codeproject.com/KB/cs/groupandmembers.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/groupandmembers.aspx</a></p>
<p>The sample application that they made:</p>
<p><img src="https://i.stack.imgur.com/9Vt9Z.jpg" alt="alt text"></p>
|
<p>Perhaps this is something that can be done via WMI?</p>
| 6,732
|
<p>I am in the process of developing a web application that consists visually of a header above a body containing four columns of variable-height content. The design gods have decreed it to be fixed height, mainly because each of the columns can potentially get very long, and so (being designers) they are wanting iframes with independent scrollbars.</p>
<p>Four (potential) scrollbars are bad enough, but if the overall page height is fixed higher than the browser window then it'll end up with five! The 'normal' solution in a case like this of course is to fix the overall page height at something like 700 pixels to give it the 'best chance' of fitting vertically, but I don't want to do that for various reasons which I'd hope would be obvious.</p>
<p>So my question is: What would be the best way to have a body container that fills the available (vertical space) with each of the columns doing the same thing? Is it even practical/possible? Bonus question: Can I reliably use the CSS overflow property for the columns or do I need nasty iframes? I have lots of CSS experience, but next to none with using percentage dimensions (especially when combined with pixel dimensions as I'll need for the header). Also, this must be standards-compliant and backwards-compatible to IE6.</p>
<p>TIA.</p>
<p>EDIT: I'm not looking for a CSS layout solution per se, my problem is how to accommodate the need for each column to be the maximum height possible within the body container and scrollable, without fixing the height of the body in pixels - unless I absolutely need to.</p>
|
<p>I'm pretty sure this does exactly what you need: <a href="http://www.cssplay.co.uk/layouts/body5.html" rel="noreferrer">Liquid 4 column layout with fixed height banner and footer</a></p>
<p>No iframes, no java script, and each column automatically fills the available height.</p>
|
<p>Are you talking of something like this?</p>
<pre><code><div id="head"></div>
<div id="body">
<div id="col1"></div>
<div id="col2"></div>
<div id="col3"></div>
<div id="col4"></div>
</div>
</code></pre>
<p>The CSS</p>
<pre><code>#body { position: absolute; top: 60px /* height of the header */; bottom: 0px; width: 100%; }
#body div { position: absolute; top:0; bottom:0 ;width: 25% }
</code></pre>
<p>This may not work in IE6, for which you would have to use JavaScript:</p>
<pre><code>window.onResize = function () {
// Calculate the height of the body, substract the height of the head and apply to all columns
}
</code></pre>
| 23,825
|
<p>I have an interface called Dictionary which has a method <code>insert()</code>. This interface is implemented by class <code>BSTree</code>, but I also have a class <code>AVLTree</code> which is a child class of <code>BSTree</code>. <code>AVLTree</code> redefines the <code>insert()</code> so it suits it's needs. Now if I type the following code:</p>
<pre><code>Dictionary data=new AVLTree();
data.insert();
</code></pre>
<p>There is a problem, because the <code>insert()</code> method that is called is of <code>BSTree</code> instead of <code>AVLTree</code>. Why doesn't the polymorphism kick in here? What is the appropriate solution, one that retains the principle of polymorphism?</p>
|
<p>When you say AVLTree "redefines" the insert, what exactly do you mean? It has to override the method, which means having exactly the same signature (modulo variance).</p>
<p>Could you post the signatures of insert() in both BSTree and AVLTree?</p>
<p>If you apply the @Override annotation in AVLTree (assuming a suitably recent JDK) you should get a warning/error if you've not got the right signature.</p>
|
<p>In java, (I'm talking relatively to C++), polymorphism should "always" work. It's hard to see what's wrong without looking at the code.. maybe you could post interesting part? Such as the method's signature, class declaration, etc.. My guess is that you haven't used the same signature for both methods. </p>
| 43,730
|
<p>I would like to be able to build test applications (e.g. the nightly Minefield/Firefox) without Launch Services deciding that they're the best way to open their assigned file types.</p>
<p>Is there a way to hide my ~/src directory from Launch Services, so that Finder won't register applications in that folder?</p>
|
<p>There are a number of client side controls that one can use.</p>
<p>You can </p>
<ul>
<li>Build your own ActiveX control. Windows/IE only</li>
<li>Use Flash to queue up files and upload them one at a time to the server using the stanard file upload protocol. </li>
<li>Use a signed java applet to upload.</li>
<li>Write a browser plugin.</li>
</ul>
<p>Some random links from google:</p>
<p><a href="http://www.element-it.com/MultiPowUpload.aspx" rel="nofollow noreferrer">http://www.element-it.com/MultiPowUpload.aspx</a></p>
<p><a href="http://www.codeproject.com/KB/aspnet/FlashUpload.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/aspnet/FlashUpload.aspx</a></p>
<p><a href="http://www.dmxzone.com/forum/go/?36564" rel="nofollow noreferrer">http://www.dmxzone.com/forum/go/?36564</a></p>
|
<p>If you running a mod_perl2 apache there is the <a href="http://search.cpan.org/~ceeshek/Apache2-UploadProgress-0.2/lib/Apache2/UploadProgress.pm" rel="nofollow noreferrer">Apache2::UploadProgress</a> module. This adds an id to the http upload request, you then query the server for the progress of that upload. Has built in support for creating an AJAX progress bar in a popup window or within the page doing the upload. If you want to build your own progress display you can get the info back as XML or JSON data. </p>
| 47,166
|
<p>Hi I have a view with several User Controls and I pass ViewData to all of them, I would like to know how you would determine the element count by specifying the string key.
I understand that you cannot use comparison to an integer because ViewData is an object but I have it setup this way for explaining my question. I have also tried null but The ViewData object is never null, even for results where no data is populated in the ViewData. I.e</p>
<p>In my View</p>
<pre><code> <%if(ViewData["Test"].Values > 0)
{
%>
<%=Html.RenderPartial("~/Views/UC/Test.ascx", ViewData["Test"])%>
<%
}
%>
</code></pre>
|
<p>If I understood your question correctly, you want to get the count out of an element stored inside the ViewData.
The only way to achieve this is by casting it to IEnumerable or IList and then call the Count method.</p>
|
<p>To answer my own question this is the path I took about doing this. In my controller action method I determine the count based on number of records retrieved there and set my ViewData to null if it doesn't meet my requirements.</p>
<pre><code>public ActionResult Test(){
var test = //your query;
if(test.Count() > 0 )
{
ViewData["Test"] = test;
}
}
</code></pre>
<p>Now if nothing is retrieved it automatically sets the ViewData["Test"] to null and in your view Page you could do something like this.</p>
<pre><code><% if(ViewData["Test"] == null){
Html.RenderPartial("~/Views/UC/NoRecords.ascx");
}
else
{
Html.RenderPartial("~/Views/UC/Awesome.ascx");
}
%>
</code></pre>
<p>If you wanted to add multiple checks you must add them in your controller and compare using your view page. There are probably other ways of doing this but I found this works well. </p>
| 41,042
|
<p>Is there any good way to deal with the class renaming refactor from Resharper when the file is under source control and TortoiseSVN is the client. I have am trying VisualSVN right now but I haven't had the need to rename anything recently. I don't want to change our repository just to try this out.</p>
<p>Also not sure if this feature alone is worth the cost of VisualSVN.</p>
<p><strong>Update:</strong> I have uninstalled the trial of VisualSVN and tried AhknSVN. I seems to provided the same functionality so far. </p>
<p>I know this my sound trivial but the indicators seem to be lacking some functionality, it seems like they don't trickle up. (If a file in the project is different I would think the project indicator would indicate this as well.) I tend to keep my projects rolled as much as possible, so it is hard to tell what files have changed unless the project is expanded.</p>
|
<p>TortoiseSVN 1.5 has a neat hidden feature on the check in window:</p>
<p>Select a missing file and a new file and right-click. One of the options will be "fix move".</p>
<p>I tend to refactor away, and then use this to fix any files where the name has changed.</p>
|
<p>Time to branch your repository. That's the nice part about version control, you can create new branches without totaling the old ones.</p>
| 3,467
|
<p>Is it possible to create an integer (or DataTime, etc) column in ListView? It is quite important, because I would like to properly sort the list according to this column.</p>
<p>The only way to add subItems to a ListViewItem I found are:</p>
<pre><code>listviewitem.SubItems.Add("1");
</code></pre>
<p>I would like to avoid parsing these strings to get the int representation for every sort!</p>
|
<p>You could use the Tag property. These little helper functions take care of it:</p>
<pre><code>private void setListItem(int row, int column, int value) {
ListViewItem.ListViewSubItem item = listView1.Items[row].SubItems[column];
item.Tag = value;
item.Text = value.ToString();
}
private int getListItem(int row, int column) {
return (int)listView1.Items[row].SubItems[column].Tag;
}
</code></pre>
|
<p>I think we have a column of type integer like what we have the columns in datagrid, actually i do not have idea about listview control. Let me know if you find the answer.</p>
| 38,379
|
<p>I'm working on a command line application for Solaris, written in Java6. I'd like to be able to scroll through a history of previous commands using the up and down arrows like many Unix tools allow (shells, VIM command mode prompt, etc).</p>
<p>Is there any standard way of achieving this, or do I have to roll my own?</p>
|
<p>Yes, use the <a href="http://tiswww.case.edu/php/chet/readline/rltop.html" rel="nofollow noreferrer">GNU readline</a> library.</p>
|
<p>There is a SourceForge project, <a href="http://java-readline.sourceforge.net/" rel="nofollow noreferrer">http://java-readline.sourceforge.net/</a>, that provides JNI-based bindings to GNU readline. I've played around with it (not used in an actual project), and it certainly covers all of the functionality.</p>
| 7,148
|
<p>I have a page P1 loading from site S1 which contains an iframe. That iframe loads a page P2 from another site S2. At some point P2 would like to close the browser window, which contains P1 loaded from S1. Of course, since P2 is loaded from another site, it can't just do parent.close().</p>
<p>I have full control over P1 and P2, so I can add JavaScript code to both P1 and P2 as needed.
Suggestions on how to resolve this?</p>
|
<p>It's impossible, I am afraid. JavaScript from an iframe that is loaded to a different site then the one it is being rendered on is strictly prohibited due to security issues.</p>
<p>However, if the iframe is pointed to the same site you can get to it like:</p>
<pre><code><iframe name = "frame1" src = "http://yoursite">
</iframe>
<script type = "text/javascript">
alert(window.frames["frame1"].document);
</script>
</code></pre>
|
<p>If they originated from the same domain, you can modify the security-restrictions to allow modification between sub-domains.</p>
<p>set document.domain = "domain.com"; //on both pages and they are allowed to modify eachother.</p>
<p>It might work to just set them to a bogus-domain, haven't tried that, or just simply ".com" or something.</p>
| 36,398
|
<p>My automated deployment system updates a latest version of my site trough subversion. Instead of having my live site point to the trunk (which is always almost a work in progress version), I have my live site point to a tag.</p>
<p>E.g. I work on trunk and when my v1.0 is finished I create a tag called 1.0 and do a checkout of that tag which is then my live site. Now, I keep working on trunk and after a while there is a v2.0. I create a tag called 2.0 and I want my live site to resemble this 2.0 tag.</p>
<p>I could wipe the current live site and do a checkout of this 2.0 tag. Which sounds easy enough, however. My site is about 1GB is size because it has all kinds of PDF documents and video in it. I can safely say that most of the time I do updates it will be copy changes or bug fixes. This means that maybe only 1% of my site changes per update. And since my version control is only accessable to my webserver through on off site http connection it would mean that I need to download that whole site over and over again.</p>
<p>Is there an easy way to switch between tags and have subversion only update the differences between those tags?</p>
|
<p>There actually is a switch function that does just that. I use TortiseSVN which is a windows shell/gui for Subversion, so I'm not familiar with how to do it manually, but this looks like it should help:</p>
<p><a href="http://svnbook.red-bean.com/en/1.1/ch04s05.html" rel="noreferrer">http://svnbook.red-bean.com/en/1.1/ch04s05.html</a></p>
|
<p>I use a similar setup, except I use a live branch, rather than a tag. It's more work to commit, since I now have to merge changes from trunk into the live branch, but I can then just do an "svn up" in the webroot to update it. It also gives me slightly better control if I want to merge selected changes from different branches into live.</p>
<p>If I was doing it again, I'd use mercurial (or similar) since branches are much easier to maintain, but the above technique has worked for 3 live sites for about two years now.</p>
| 23,484
|
<p>I'm having a problem getting access to a database which lives on a remote server. </p>
<p>I have a ASP.NET 2.0 webpage that is trying to connect to a database.<br>
The database is accessed via a virtual folder (which I set up in IIS).<br>
The virtual folder points at a remote share which contains the database. </p>
<p>The virtual folder (in the web apps root directory) is pointing at a share on a remote server via a UNC path: </p>
<pre><code>\\databaseServerName\databaseFolder$\
</code></pre>
<p>The virtual folder has 'read' and 'browse' permissions set to 'true'. </p>
<p>I store the connection string in the 'appSettings' section of the web.config: </p>
<pre><code><add key="conStrVirtual" value="Provider=Microsoft.Jet.OleDb.4.0;Data Source=http://webAppServerName/virtualFolderName/databaseName.MDB;Jet OLEDB:Database Password=dumbPassword;"/>
</code></pre>
<p>The connection object is declard on my .aspx page: </p>
<pre><code>Dim objConnVirtual As New OleDbConnection(ConfigurationManager.AppSettings("conStrVirtual"))
</code></pre>
<p>Here is the code that tries to use the connection object: </p>
<pre><code>Public Sub Test()
If objConnVirtual.State <> ConnectionState.Open Then
objConnVirtual.Open()
End If
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM TableName", objConnVirtual)
objDR = cmd.ExecuteReader()
If objDR.Read() Then
response.write("Shazaam! Data shows up here")
End If
objDR.Close()
objConnVirtual.Close()
End Sub
</code></pre>
<p>When I run the above code I get the following error (on this line of the code 'objConnVirtual.Open()':<br>
<strong>Exception Details: System.Data.OleDb.OleDbException: Not a valid file name.</strong></p>
<p>I have checked the database name and it is correct (even copy/pasted it to make sure)</p>
<p>If I put the 'Data Source' section of the connection string into the address bar of my browser I can successfully see the contents of the share on the remote server.</p>
<p>Not sure if this is a problem with permissions or with the code.<br>
I have googled the crap out of this but have not been able to find a solution.</p>
<p>Any help is much appreciated.</p>
|
<p>When accessing a remote Access MDB database, you have to specify a UNC path like \\remoteMachine\Share\test.mdb.</p>
<p>Make sure your application pool identity has the right permissions to connect to the remote share. By default on IIS 6 you are working with the Network Service account, which is by default not allowed to access a remote share.</p>
<p>The best way is to let the AppPool run with a dedicated service user.</p>
|
<p>make sure the two servers have internal access to each other and also specify the ip & port of db server in your connection string .</p>
| 44,112
|
<p>Server virtualization is a big thing these days, so I'm tasked at work to install some of our software on a virtualized server and see what happens. Long story short: a <code>rsync</code> transfer promptly brings the virtualized server to its knees. The virtualization host is a beefy machine with no other load; I don't think this should be happening. <code>Top</code> shows high load averages, and cpu iowait near 100%. There's a huge bottleneck somewhere.</p>
<p>I'm more a programmer than a sysadmin, I lack the knowledge on how to go about fixing this outside of random Googling. I suspect I'm not alone in this. </p>
<p>What I'd like to see here is general advice on virtualization, and pointers to good articles and other resources, which I and others could use to educate ourselves. </p>
<ul>
<li>What tools (even standard unix tools) can be used to pinpoint bottlenecks?</li>
<li>What metrics should be followed to ensure things run smoothly?</li>
<li>What kind of things can be efficiently virtualized? </li>
<li>What kind of setups are doomed to fail?</li>
</ul>
<p>I apologize the broadness of the question. I just don't have the knowledge to ask useful specific questions about this.</p>
<p>Edit: More on my specific problem:</p>
<ul>
<li>XAN paravirtualization, 3 x guest CentOS</li>
<li>All guests on local SCSI disks, there is a fully hardware raid controller</li>
<li>rsyncd running on 1 guest os, transfer initiated from a remote non virtualized server through 100mbps LAN</li>
</ul>
<p>Like I said before, I really can't provide a ton of useful data. I'm not really expecting to get a direct solution to this problem, I'd be happy with pointers on where to start building the skillset required to better understand these kinds of problems.</p>
|
<p>I was going to put this in a comment, but I think it's more useful in the open:</p>
<p>Could you add more detail about your setup: </p>
<ul>
<li>Which VM server?<br>
(VMware Server, VMware ESX, MS VirtualServer, MS Hyper-V, something else?)</li>
<li>Which OS for the guest(s)?<br>
(Windows, Linux, 32-bit, 64-bit?)</li>
<li>Where are the guest(s) stored?<br>
(Local disk, or on a NAS or SAN?)</li>
<li>Were you rsyncing between guests on the same VM server, or between a guest and a physical server? </li>
<li>If across a network, how fast is the network?</li>
</ul>
<p>Performance tuning in any environment is 90% collecting data, and 10% analysis. Virtualized environments have more variables to consider than Physical environments, but more importantly, they have a different response curve than physical environments. Some applications can perform better in a virtualized environment than a physical environment; others will not. You have to understand the requirements of the application as well as constraints of the implementation.</p>
<p>I don't believe that there are any software-only applications that cannot be successfully deployed on virtual servers, if you pay attention to the details. (Applications that require custom hardware that can't be successfully virtualized is a different problem.)</p>
|
<p>Off hand I'd say this is I/O problem. In virtual environments on of the biggest factors that affects performance is the state of the disk of the host machine. The things that we do to optimize performance are:</p>
<ol>
<li>Fixed disk allocation. This way you get a contiguous block of drive space for the VM to live in. </li>
<li>Schedule a defrag of the VM Slice OS and the Host server drive. Fragmentation is your enemy.</li>
<li>Be sure that you are ending an server sessions gracefully. When bouncing the virtual OS, DO NOT just shutdown the VM slice, as this cause huge disk fragmentation. The virtual OS needs to perform the shut down / restart process.</li>
</ol>
| 14,802
|
<p>It' possible to use Junitperf with junit4?
I've a simplet Junit4 test class with several tests and I want to do a TimedTest on single test of that class. How can I do that?</p>
<p>To be more clear my Junit4 class is something like:</p>
<pre><code>public class TestCitta {
@Test
public void test1 {}
@Test
public void test2 {}
}
</code></pre>
<p>with junit3 i shold write something like:</p>
<pre><code>public class TestCittaPerformance {
public static final long toleranceInMillis = 100;
public static Test suite() {
long maxElapsedTimeInMillis = 1000 + toleranceInMillis;
Test testCase = new TestCitta("test2");
Test timedTest = new TimedTest(testCase, maxElapsedTimeInMillis);
return timedTest;
}
public static void main(String args[]) {
junit.textui.TestRunner.run(suite());
}
}
</code></pre>
<p>with Junit4?</p>
|
<p>I had the same problem but was not lucky trying to make it run in different build environments. So I used the @Rule feature available since JUnit 4 to inject performance test invocation and requirements checking using annotations. It turned out to become a small library which replaced JUnitPerf in this project and I published it under the name <a href="/questions/tagged/contiperf" class="post-tag" title="show questions tagged 'contiperf'" rel="tag">contiperf</a>. If you are interested in this approach, you can find it at <a href="https://github.com/lucaspouzac/contiperf" rel="nofollow noreferrer">https://github.com/lucaspouzac/contiperf</a>.</p>
|
<p>Or you can use the annotation: <code>@Test(timeout=1000)</code></p>
| 41,921
|
<p>Correct me if I'm wrong, but a "build" is a "compile", and not every language compiles. Continuous Integration involves building components to see if they continue to work beyond unit tests, which I might be oversimplifying. But if your project involves a language that does not compile, how do you perform nightly builds or use continuous integration techniques?</p>
|
<p>Hmm... I'd define "building" as something like "preparing, packaging and deploying all artifacts of a software system". The compilation to machine code is only one of many steps in the build. Others might be checking out the latest version of the code from scm-system, getting external dependencies, setting configuration values depending on the target the software gets deployed to and running some kind of test suite to ensure you've got a "working/running build" before you actually deploy.</p>
<p>"Building" software can/must be done for any software, independent of your programming langugage. Intepreted languages have the "disadvantage" that syntactic or structural (meaning e.g. calling a method with wrong parameters etc.) errors normally will only be detected at runtime (if you don't have a separate step in your build which checks for such errors e.g. with <a href="http://www.icosaedro.it/phplint/" rel="nofollow noreferrer">PHPLint</a>). </p>
<p>Thus (automated) Testcases (like Unit-Tests - see <a href="http://www.phpunit.de/" rel="nofollow noreferrer">PHPUnit</a> or <a href="http://simpletest.org/" rel="nofollow noreferrer">SimpleTest</a> - and Frontend-Tests - see <a href="http://selenium.openqa.org/" rel="nofollow noreferrer">Selenium</a>) are all the more important for big PHP projects to ensure the good health of the code.</p>
<p>There's a great Build-Tool (like Ant for Java or Rake for Ruby) for PHP too: <a href="http://phing.info/trac/" rel="nofollow noreferrer">Phing</a></p>
<p>CI-Systems like <a href="http://code.google.com/p/xinc/" rel="nofollow noreferrer">Xinc</a> or <a href="http://hudson-ci.org/" rel="nofollow noreferrer">Hudson</a> are simply used to automagically (like anytime a change is checked into scm) package your code, check it for obvious errors, run your tests (in short: run your build) and report the results back to your development team.</p>
|
<p>Create a daily tag of your current source control trunk?</p>
| 7,737
|
<p>When I pass an immutable type object(String, Integer,.. ) as final to a method I can achieve the characters of a C++ constant pointer. But how can I enforce such behavior in objects which are mutable?</p>
<pre><code>public void someMethod(someType someObject){
/*
* code that modifies the someObject's state
*
*/
}
</code></pre>
<p>All I want is to prevent someMethod from modifying the state of someObject without making any change in someType. Is this possible?</p>
|
<p>In the general case, no, it's not possible. In a very limited case, you can wrap someType in a class that provides the same interface (see Collections.unmodifiableList() for an example).</p>
<p>However, there's no equivalent to "pass a const pointer and the compiler will only allow you to call const functions on it".</p>
|
<p>No, it's not possible. You have to either pass in a copy of the object, or just rely on knowing what actions make state changes to the object and avoid calling them - the compiler won't help you.</p>
| 49,478
|
<p>I think I might be missing the point of having a logging framework for your application. In all the small apps I've always written a small "Logging" class and just pass log messages to a method in it which is written to a file. </p>
<p>What is the purpose of a 3rd party logging framework like log4net? Is it thread safety with logging write operations or am I missing something?</p>
|
<p>That's an excellent question.</p>
<p>The first reason is "why not?" If you are using a logging framework, then you'll reap the maintainability benefits of using something already packaged.</p>
<p>The second reason is that logging is subtle. Different threads, sessions, classes and object instances may all come into play in logging, and you don't want to have to figure this problem out on the fly. </p>
<p>The third reason is that you may find a performance bottleneck in your code. Figuring out that your code is slow because you're writing to a file without buffering or your hard drive has run out of disk space because the logger doesn't rollover and compress old files can be a pain in the neck.</p>
<p>The fourth reason is that you may want to append to syslog, or write to a database, or to a socket, or to different files. Frameworks have this functionality built in.</p>
<p>But really, the first answer is the best one; there's very little benefit to writing your own, and a whole bunch of drawbacks.</p>
|
<p>Just for an argument sake, why not a matured home grown? which doesn't come's with any extra baggage and you have complete control over it.</p>
<p>Most of the Logging frameworks has too many features which we really wont use most of them and having said that they comes with there own baggage(Its just not a class, its a framework). Why not implement a simple home grown logging where all your applications write there logs to a Queue and a simple offline service(may be a windows service) read the queue and writes it to your desired location(File, Database etc). by Using queue you can achieve async operation and no locking issues.</p>
| 17,446
|
<p>I know I must be missing something, but in a <code>while</code> statement how does the variable hold the data, when it finishes the first pass and goes into the second pass?</p>
<hr>
<p>{</p>
<pre><code>int num1 = 0 ;
int num2 = 0;
int num3 = 0;
while (num1 < 10)
{cout << "enter your first number: ";
cin >> num1;
cout << "Enter your second number: ";
cin >> num2;
num1 = num1 + num2 ;
cout << "Number 1 is now: " << num1 <<endl;
cout << "Enter Number 3: " ;
cin >> num3;
num1 = num1 + num3;
cout << "Number 1 is now: " << num1 << endl;
num1++;
};
</code></pre>
<p>In this code. The Variable doesn't hold the data. I'm not sure what I'm doing wrong!</p>
|
<p>Is num1 the variable you're having trouble with? This line:</p>
<pre><code>cin >> num1;
</code></pre>
<p>is setting num1 to the value input by the user. So the value calculated for it in the previous run through the loop is being overwritten each time by the new input.</p>
|
<p>I'm not sure I understand your question. In C any data that's not overwritten is carried over into the next iteration of the loop, and imagine that C++ works much the same way.</p>
| 5,679
|
<p>I've been digging through Stack Overflow as well as a number of Google searches, and I cannot find a satisfactory code formatter for JavaScript.</p>
<p>I have found several related tools, such as syntax highlighters and pretty-printers, but I am looking for a tool that I can ideally create a wrapper for in Eclipse and simply run from the menu bar. Hence, if any Java-based ones are available, that is a big plus. Free and/or open-source is preferred as well.</p>
<p>I am looking for something that my development group can use to maintain a consistent code style.</p>
<p><strong>Edit:</strong> Thanks to kRON for linking to the <a href="https://stackoverflow.com/questions/351298/best-source-code-formatter-for-javascript#351310">format customizations</a> page.</p>
<p><strong>Edit:</strong> <a href="https://stackoverflow.com/questions/18985/javascript-beautifier">Related question</a> on Stack Overflow.</p>
|
<p>In one breath: <a href="http://www.aptana.com/products/studio3.html" rel="nofollow noreferrer">Aptana Studio</a>! Yes, it's Java based and free (Eclipse, as standalone or plugin).</p>
<p>You can also <a href="http://www.aptana.com/docs/index.php/Customizing_your_formatting_preferences" rel="nofollow noreferrer">customize the formatting</a>.</p>
|
<p>If you are using notepad++, you can try jsminnpp plugin</p>
| 45,731
|
<p>I want to access a MySQL database directly from JavaScript code in an HTML page in Firefox.</p>
<p>Does such a library exist?</p>
<p>To be very clear, <strong>CGI+Ajax will not work</strong></p>
<p>Some background: I want to create something like a GUI front end for a MySQL database (that's not what it is, but it's close enough). I'm thinking about doing this as a local HTML page using JavaScript but for that to work I would need MySQL bindings for JavaScript under Firefox. I already have a working prototype in under 100 LOC, but it requires a web server, and for reasons that are beyond this question, that won't work.</p>
<p>NOTE: both the database and the JavaScript code will be running locally and are not intended as a public page. In fact the HTML file will loaded as a file://// file. The only reason I'm using JavaScript is that it's the only available system for doing GUI stuff where I need it.</p>
<p>I'm willing to install plugins, DLL's, Windows dependent stuff or what not to make this work.</p>
<hr>
<p>Edit: It looks like the answer is, "It can be done, but it's going to be painful". As one of my options is to just spew out all the data as files (ugly, and not too flexible, but it would work) I think I'm not going to pursue this.</p>
|
<p>JavaScript code lives inside the browser. It can make HTTP requests to the outside, but not really much more. So by design you won't be able to bind to a program running locally. If MySQL did expose an HTTP service, it might be possible, but that's not the case.</p>
<p>You might be able to find a plugin for Firefox that exposes a MySQL API to JavaScript, but I don't know any such plugin.</p>
<p>If you don't specifically need MySQL, but just a database accessible from JavaScript code, have a look at <a href="http://gears.google.com/" rel="nofollow noreferrer">Google Gears</a>. It is a Firefox / Internet Explorer plugin that exposes an <a href="http://www.sqlite.org/" rel="nofollow noreferrer">SQLite</a> database and a few other goodies.</p>
<p>If you give more information on what you are trying to build, we might be able to give you better advice...</p>
|
<p>I can't give you complete answer, but here are the general idea how you can do it with just MySQL + Internet Explorer + JavaScript (untested):</p>
<p>In JavaScript you can call a Windows application by using</p>
<pre><code>var myshell = new ActiveXObject( "WScript.shell" );
myshell.run( program names );
</code></pre>
<p>So the idea is to call <code>mysql.exe</code> with the SQL statements stored in an SQL file, then capture and parse the output:</p>
<pre><code>mysql.exe -h localhost -u root dbo < script.sql > output.txt
</code></pre>
<p>This idea doesn't come without challenges:</p>
<ul>
<li>you need to modify the SQL file before calling <code>mysql.exe</code></li>
<li>you need to open and parse the output file</li>
</ul>
<p>As I mentioned above I haven't tested anything, so this whole idea may not even work ...</p>
| 38,147
|
<p>If I have a URL (eg. <a href="http://www.foo.com/alink.pl?page=2" rel="noreferrer">http://www.foo.com/alink.pl?page=2</a>), I want to determine if I am being redirected to another link. I'd also like to know the final URL (eg. <a href="http://www.foo.com/other_link.pl" rel="noreferrer">http://www.foo.com/other_link.pl</a>). Finally, I want to be able to do this in Perl and Groovy.</p>
|
<p>In Perl:</p>
<pre><code>use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $request = HTTP::Request->new( GET => 'http://google.com/' );
my $response = $ua->request($request);
if ( $response->is_success and $response->previous ) {
print $request->url, ' redirected to ', $response->request->uri, "\n";
}
</code></pre>
|
<p>I think this will work for 301 redirects.</p>
<pre><code>use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $request = HTTP::Request->new( GET => 'http://google.com/' );
my $response = $ua->request($request);
if ( $response->is_redirect ) {
print $request->url . " redirected to location " . $response->header('Location') . "\n";
}
</code></pre>
| 31,330
|
<p>What WPF Calendar control would you recommend? I am looking for something that will let me display a variable amount of weeks potentially spanning multiple months.</p>
|
<p>Microsoft has now released a WPF calendar control.</p>
<pre><code><c:Calendar>
<c:DatePicker.BlackoutDates>
<c:CalendarDateRange Start="4/1/2008" End="4/6/2008"/>
<c:CalendarDateRange Start="4/14/2008" End="4/17/2008"/>
</c:DatePicker.BlackoutDates>
</c:Calendar>
<c:DatePicker>
<c:DatePicker.BlackoutDates>
<c:CalendarDateRange Start="4/1/2008" End="4/6/2008"/>
<c:CalendarDateRange Start="4/14/2008" End="4/17/2008"/>
</c:DatePicker.BlackoutDates>
</c:DatePicker>
</code></pre>
<p><a href="https://i.stack.imgur.com/7WmdW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7WmdW.png" alt="" /></a><br />
<sub>(source: <a href="http://windowsclient.net/SiteFiles/1000/wpfsp1/wpf-35sp1-toolkit/110-1.png" rel="nofollow noreferrer">windowsclient.net</a>)</sub></p>
<ul>
<li><a href="http://www.codeplex.com/wpf" rel="nofollow noreferrer">http://www.codeplex.com/wpf</a></li>
<li><a href="http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-calendar-datepicker-walkthrough.aspx" rel="nofollow noreferrer">http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-calendar-datepicker-walkthrough.aspx</a></li>
</ul>
<p>Charles Petzold wrote a <a href="http://msdn.microsoft.com/en-us/magazine/dd882520.aspx" rel="nofollow noreferrer">good article about customising the WPF calendar control</a> too.</p>
|
<p>I would take a look at <a href="http://j832.com/BagOTricks/" rel="nofollow noreferrer">Kevin's Bag-o-tricks</a></p>
| 13,821
|
<pre><code>div#thing {
position: absolute;
top: 0px;
z-index: 2;
margin: 0 auto;
}
<div id="thing">
<p>text text text with no fixed size, variable font</p>
</div>
</code></pre>
<p>The div is at the top, but I can't center it with <code><center></code> or <code>margin: 0 auto</code>;</p>
|
<p>Your problem may be solved if you give your <code>div</code> a fixed width, as follows:</p>
<pre><code>div#thing {
position: absolute;
top: 0px;
z-index: 2;
width:400px;
margin-left:-200px;
left:50%;
}
</code></pre>
|
<p>Yes:</p>
<pre><code>div#thing { text-align:center; }
</code></pre>
| 31,503
|
<p>I have an idea for a website which involves a canvas area which has no limit to its size. Basically you would be able to add items to the canvas (notes, photos whatever really). You would then be able to drag the canvas which would move those items along with the canvas until they disappear of screen. If you dragged the canvas back the other way they would appear again.</p>
<p>Question:
Which would be the best suited to this type of thing, Flash or Javacsript?</p>
<p>My main worries are the speed at which javascript/ flash could handle moving multiple items around on screen in the way discribed. Which language would handle better for a user on a slow machine.</p>
<p><strong>UPDATE:</strong></p>
<p>Thanks for your opnions guys, but to clarify what are the benefits of canvas over straight jQuery DOM manipulation? or visa versa. I've never used canvas before.</p>
|
<p>I don't think this is a question that will get you an objective answer - Flash developers will tell you Flash is better, web developers will say JavaScript. Trying to remain objective, I'd say that both technologies are suitable for what you describe, but have different advantages.</p>
<p>Flash will definitely render faster, even on slow machines, and is much richer graphically.</p>
<p>JavaScript is more accessible and works on a greater number of devices. Use a good JS framework though.</p>
|
<p>Do you need to use canvas, what you're describing could be done with just javascript and the DOM. It would perform perfectly well unless there are a huge number of elements and it would be cross-browser compatible. For canvas you would require <a href="http://excanvas.sourceforge.net/" rel="nofollow noreferrer">exCanvas</a> to support IE which can sometimes slow things down.</p>
| 22,002
|
<p>I'm trying filter the child collection of an aggregate root when loading it with Nhibernate. Load a Customer with all their Orders that have been shipped. Is this possible?</p>
|
<p>Well, you can expose properties that are filtered in the map, like so:</p>
<pre><code><bag name="shippedOrders" ... where="Status == 'Shipped'" >
<key column="CustomerId" />
<one-to-many class="Order" />
</bag>
</code></pre>
<p>The 'where' attribute is arbitrary SQL.</p>
<p>Theoretically you could have two properties of Customer, Orders and ShippedOrders. However, I should say that I have not done this, and I would want to test how NH handles cascading in this case. In any case, you will have to take care when new items are added/removed that they are added/removed correctly to both collections.</p>
<p>The fact that you want to do this makes we wonder if Order is an aggregate root. It might be less trouble in the long run doing it like this: </p>
<pre><code>orderRepository.GetOrders(int customerId, OrderStatus[] statuses)
</code></pre>
|
<p>You could look at it the other way - load all the shipped orders for a Customer. </p>
<pre><code>session.CreateCriteria( typeOf(Order) )
.Add( Restrictions.Eq("Shipped", shippedStatus ) )
.Add( Restrictions.Eq("Customer", requiredCustomer) )
.List<Order>();
</code></pre>
| 30,752
|
<p>I have a few 3D printers and now want to start building a custom 3D printer.
I want to build a 3D printer with multiple nozzles, and I want to make the hotend thin so the nozzles can be closer together.
What is the thinnest nozzle avalible to buy?
Are there any guides or details on how I could make a custom nozzle or modify a nozzle if I can't buy a thin nozzle?</p>
|
<p>The size of the nozzle usually isn't the main factor for how close you can put nozzles together. To keep the filament drive gear system from being the limiting factor, you would need Bowden extruders. "Then, the heat sinks and fans would be your limiting factor. Have you considered a single nozzle with three extruders? Otherwise, you need custom angled heat sinks similar to the three heat sinks on a single nozzle, and still a way to orient the nozzles at the same Z-height. That would be difficult if all the nozzles are on the same heater block. It still seems that nozzle size is the least of the issues of putting nozzles close together.</p>
<p>If you search for smaller nozzle sizes, you will get nozzles with smaller openings, not smaller overall size. The threads on the nozzles are a standard size. Thus, the smaller opening size can't be put closer together than the larger opening size. Otherwise, you have only small variations between different types of nozzles and need room to screw them in to the heater block if you put all of them into one block. You can get a nozzle using a 6 mm hex wrench that is smaller than one using a 7 mm hex (E3D).</p>
|
<p>One of the thinnest hotends I've seen are those from a Chinese factory Mellow Store, the heatsink is smaller than the top flange to mount the hotend. I don't know the quality of these hotends, the image below shows the basic layouts of available options:</p>
<p><a href="https://i.stack.imgur.com/MsvUL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MsvUL.jpg" alt="Mellow Store custom hotend" /></a></p>
<p>Ultimaker uses high quality hotends which are pretty small 2.85 mm hotends they call "cores", they house 2 next to each other and use a lifting mechanism:</p>
<p><a href="https://i.stack.imgur.com/pl0mt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pl0mt.png" alt="Ultimaker 0.8 mm core" /></a></p>
| 1,702
|
<p>I'd like to use the Object Test Bench in VS2008. The docs - and even the helpful text in the test bench window - say to right click on class in the Class View. Further reading indicates that this class must be in the startup project or referenced assembly. I've tried this on numerous classes - public, private, static, you name it - in several assemblies (either the startup project or a referenced project), and the context menu item "Create Instance" never appears.</p>
<p>Has anyone had any luck with this? Is this a bug, or am I doing something wrong?</p>
|
<p>Solved it!</p>
<p>I had multiple projects set to run on startup (I've gotten so used to working that way I didn't even realize there was a difference!).</p>
<p>Setting just one startup project fixed the problem.</p>
|
<p>I can only get it to work in the start up project if the project is a console or windows forms application. It doesn't seem to work with web sites.</p>
<p>BTW. I don't ever use it in practice. And after playing with awhile in the context of trying to figure out why it wasn't working for you, I now know why! Very difficult to do something that ought to be simple on a fully working project.</p>
| 25,299
|
<p>I'm creating a control and need to pass it the current logon user as a parameter (declaratively)</p>
<p>I tried this but didn't work (I got "<%= User.Identity.Name %>" as value):</p>
<pre><code><cc1:MyControl id="myid" runat="server" User="<%= User.Identity.Name %>" />
</code></pre>
<p>Is there a way to do it?</p>
|
<p>Why do you need to pass it at all?. The user control can access the User.Identity.Name property directly.</p>
|
<p>Try using:</p>
<pre><code>User="<%= User.Identity.Name %>"
</code></pre>
<p>%= is for output</p>
<p>%# is for databinding.</p>
| 36,130
|
<p>I have two versions of rails (2.1.0 and 2.2.2) installed in my computer.</p>
<p>When I create a new application, is it possible to specify that I want to use the older (2.1.0) version?</p>
|
<p>I found <a href="http://craiccomputing.blogspot.com/2008/06/using-older-versions-of-rails.html" rel="noreferrer">here</a> an undocumented option to create a new application using an older version of Rails.</p>
<pre><code>rails _2.1.0_ new myapp
</code></pre>
|
<p>Please watch out which version of ruby you are using with Rails.</p>
<p>The command for making a new project for a specific version of Rail may not work for you. I had some issues about it. And the problem was the ruby version I have default which is 3.0.0. This version did not work with Rails 5. Then I installed ruby 2.7.5 and switched to it as default. Only then I was able to make projects both for Rails 5 and 7.</p>
<p>If you want the same environment with ruby 2.7.5</p>
<pre><code>rvm install ruby-2.7.5
</code></pre>
<p>switch to this version as default</p>
<pre><code>rvm --default use 2.7.5
</code></pre>
<p>install bundler and webpacker</p>
<pre><code>gem install bundler
gem install webpacker
</code></pre>
<p>install lastest rails (which is 7)</p>
<pre><code>gem install rails
</code></pre>
<p>test it</p>
<pre><code>rails new test_app_6
cd test_app_6
rails s
</code></pre>
<p>check for localhost 3000</p>
<pre><code>http://localhost:3000
</code></pre>
<p>then stop the server (control + c) and install Rails 5</p>
<pre><code>gem install rails -v 5.2.6
</code></pre>
<p>test it</p>
<pre><code>rails _5.2.6_ new test_app_5
cd test_app_5
rails s
</code></pre>
<p>check for localhost 3000</p>
<pre><code>http://localhost:3000
</code></pre>
<p>You're set!</p>
| 49,668
|
<p>I don't have too much experience with C# so if someone could point me in the right direction I would greatly appreciate it. I have a foreach loop that references a variable of an object. I wish to make another foreach loop inside the main one that compares (or performs actions on) the current variable to the rest of the variables in the array of the object.
I have the following code:</p>
<pre><code>// Integrate forces for each body.
foreach (RigidBodyBase body in doc.Bodies)
{
// Don't move background-anchored bodies.
if (body.anchored) continue;
// This is where we will add Each Body's gravitational force
// to the total force exerted on the object.
// For each other body, get it's point and it's mass.
// Find the gravitational force exterted between target body and looped body.
// Find distance between bodies.
// vector addition
// Force = G*mass1*mass2/distance^2
// Find vector of that force.
// Add Force to TotalGravityForce
// loop until there are no more bodies.
// Add TotalGravityForce to body.totalForce
}
</code></pre>
|
<p>Each time you execute foreach, (even while nesting them) the internal Enumerator should "new" up a new iterator for you, there should not be any issue with that. The issues come about when you are adding, or removing items from the collection while you are still iterating...</p>
<p>Remember, in the inner foreach, to check to make sure you are not on the same item as the outer for each is on</p>
<pre><code> foreach( RigidBodyBase body in doc.Bodies)
foreach ( RigidBodyBase otherBody in doc.Bodies)
if (!otherBody.Anchored && otherBody != body) // or otherBody.Id != body.Id -- whatever is required...
// then do the work here
</code></pre>
<p>by the way, the best place to put this code would be in a GravityForce property of the RigidBodyBase class, Then you could just write:</p>
<pre><code> foreach (RigidBodyBase body in doc.Bodies)
body.TotalForce += body.GravityForce;
</code></pre>
<p>although depending on what you're doing here (moving all objects?) they're may be even more opportunity for refactoring... I'd also consider having a separate property for the "other" forces, and have TotalForce Property do the summing of the Gravity Force and the "other" Forces? </p>
|
<p>In this case, it's probably better to use a regular for loop with an index to what element you are on. Trying to iterate over the same collection withing it's own foreach loop will cause problems.</p>
| 42,966
|
<p>From what I know, the em keyword in CSS means the current size of a font.</p>
<p>So if you put 1.2 em, it means 120% of the font height.</p>
<p>It doesn't seem right though that em is used for setting the width of divs etc like YUI grids does:</p>
<pre><code>margin-right:24.0769em;*margin-right:23.62em;
</code></pre>
<p>Everytime I read about em, I forget what it really represents.</p>
<p>I'm hoping someone can explain it to me so it sticks in my head heeh.</p>
|
<p>Historically it is the width of an "M" in the font. Hence the name!
In CSS2.1 it is <a href="http://www.w3.org/TR/CSS21/syndata.html#em-width" rel="noreferrer">defined</a> to be the same as the font-size.</p>
<p>In many cases it seems more natural to use em rather than points or pixels, because it is relative to the font size. For example you might define a text-column to have a width of 40em. If you later decide to change the font-size, the column will still keep the same number of letters per line.</p>
|
<p>They are re-calculating exact pixel values to <code>em</code> to make them scalable.</p>
<p>See this <a href="http://riddle.pl/emcalc/" rel="nofollow noreferrer">on-line calculator</a> for example.</p>
| 17,395
|
<p>I'm pretty sure that I'm not understanding something about JPA (I'm using OpenJPA) and it's causing this problem. I want to make a copy of a Job entity.</p>
<pre><code>@Entity
@Table(name="Job")
public class Job implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@ManyToOne
private Job job;
@OneToMany(fetch = FetchType.EAGER)
private Set<Job> jobCollection;
...
public Job getJob() {
return this.job;
}
public void setJob(Job job) {
this.job = job;
}
public Set<Job> getCopies() {
return this.jobCollection;
}
public void setCopies(Set<Job> jobCollection) {
this.jobCollection = jobCollection;
}
}
</code></pre>
<p>Running the following code works as I would expect when creating the first copy.</p>
<pre><code>public void testCopyJob(){
Job job = jobManager.findJobById(100);
Job jobWithCopies = null;
try {
jobWithCopies = jobManager.copyJob(job, "test copy");
} catch (Exception e) {
fail(e.getMessage());
}
Set<Job> copies = jobWithCopies.getCopies();
assertEquals("num copies", 1, copies.size());
//make a second copy
Job jobWithCopies2 = null;
try {
jobWithCopies2 = jobManager.copyJob(jobWithCopies, "test copy");
assertEquals("multiple copies", 2, jobWithCopies2.getCopies().size());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
</code></pre>
<p>Attempting to create a second copy fails with...</p>
<pre><code>[11/25/08 8:46:56:546 EST] 00000018 SystemErr R <openjpa-1.2.1-SNAPSHOT-r422266:686069 fatal general error> org.apache.openjpa.persistence.PersistenceException: null
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:1688)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.kernel.StateManagerImpl.assignObjectId(StateManagerImpl.java:523)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.kernel.StateManagerImpl.assignField(StateManagerImpl.java:608)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.kernel.StateManagerImpl.beforeAccessField(StateManagerImpl.java:1494)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.kernel.StateManagerImpl.accessingField(StateManagerImpl.java:1477)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at entities.Job.pcGetid(Job.java)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at entities.Job.hashCode(Job.java:402)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at java.util.HashMap.putImpl(Unknown Source)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at java.util.HashMap.put(Unknown Source)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at java.util.HashSet.add(Unknown Source)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.util.java$util$HashSet$proxy.add(Unknown Source)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at entities.controller.JobManager.copyJob(JobManager.java:140)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at entities.controller.JobManagerTest.testCopyJob(JobManagerTest.java:55)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:45)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at java.lang.reflect.Method.invoke(Method.java:599)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at junit.framework.TestCase.runTest(TestCase.java:154)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at junit.framework.TestCase.runBare(TestCase.java:127)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at junit.framework.TestResult$1.protect(TestResult.java:106)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at junit.framework.TestResult.runProtected(TestResult.java:124)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at junit.framework.TestResult.run(TestResult.java:109)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at junit.framework.TestCase.run(TestCase.java:118)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at junit.framework.TestSuite.runTest(TestSuite.java:208)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at junit.framework.TestSuite.run(TestSuite.java:203)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.cactus.server.runner.ServletTestRunner.run(ServletTestRunner.java:309)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.cactus.server.runner.ServletTestRunner.doGet_aroundBody0(ServletTestRunner.java:187)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.cactus.server.runner.ServletTestRunner.doGet_aroundBody1$advice(ServletTestRunner.java:225)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.cactus.server.runner.ServletTestRunner.doGet(ServletTestRunner.java:1)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at javax.servlet.http.HttpServlet.service(HttpServlet.java:718)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1449)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:790)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:443)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:175)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3610)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:274)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:926)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1557)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:173)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:455)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:384)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:272)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:202)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:766)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:896)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1527)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R Caused by: java.lang.UnsupportedOperationException
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.kernel.DetachedStateManager.getMetaData(DetachedStateManager.java:696)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.jdbc.meta.strats.UntypedPCValueHandler.toRelationDataStoreValue(UntypedPCValueHandler.java:121)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.jdbc.sql.RowImpl.setRelationId(RowImpl.java:327)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.jdbc.sql.SecondaryRow.setRelationId(SecondaryRow.java:106)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.jdbc.meta.strats.HandlerStrategies.set(HandlerStrategies.java:150)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.jdbc.meta.strats.HandlerStrategies.set(HandlerStrategies.java:104)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.jdbc.meta.strats.HandlerCollectionTableFieldStrategy.insert(HandlerCollectionTableFieldStrategy.java:154)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.jdbc.meta.strats.HandlerCollectionTableFieldStrategy.insert(HandlerCollectionTableFieldStrategy.java:130)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.jdbc.meta.FieldMapping.insert(FieldMapping.java:579)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.insert(AbstractUpdateManager.java:197)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.populateRowManager(AbstractUpdateManager.java:139)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.persistence.jdbc.kernel.ConstraintUpdateManager.flush(ConstraintUpdateManager.java:73)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at com.ibm.ws.persistence.jdbc.kernel.ConstraintUpdateManager.flush(ConstraintUpdateManager.java:60)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.flush(JDBCStoreManager.java:655)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.kernel.DelegatingStoreManager.flush(DelegatingStoreManager.java:130)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2010)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:1908)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:1679)
[11/25/08 8:46:56:546 EST] 00000018 SystemErr R ... 52 more
</code></pre>
<p>This exception is thrown in the JobManager.copyJob() method (at line: attachedJob.getCopies().add(newJob);)...</p>
<pre><code>@JPAManager(targetEntity=entities.Job.class)
public class JobManager {
private EntityManager getEntityManager() {
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("import");
return emf.createEntityManager();
}
@Action(Action.ACTION_TYPE.FIND)
public Job findJobById(int id) {
EntityManager em = getEntityManager();
Job job = null;
try {
job = (Job) em.find(Job.class, id);
} finally {
em.close();
}
return job;
}
public Job copyJob(Job job, String newJobName) throws Exception {
EntityManager em = getEntityManager();
Job attachedJob = null;
try {
em.getTransaction().begin();
//merge any changes made to job
attachedJob = em.merge(job);
//copy the job and establish bi-directional relationship
Job newJob = new Job(job);
newJob.setName(newJobName);
newJob.setJob(attachedJob);
em.persist(newJob);
attachedJob.getCopies().add(newJob);
em.getTransaction().commit(); //commit changes to original job
} catch (Exception ex) {
try {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
} catch (Exception e) {
ex.printStackTrace();
throw e;
}
throw ex;
} finally {
em.close();
}
return attachedJob;
}
}
</code></pre>
<p>This is the generated DB schema I'm using...</p>
<pre><code>CREATE TABLE Job (id INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY, JOB_ID INTEGER, PRIMARY KEY (id));
CREATE TABLE Job_jobCollection (JOB_ID INTEGER, element VARCHAR(254));
ALTER TABLE Job ADD FOREIGN KEY (JOB_ID) REFERENCES Job (id);
ALTER TABLE Job_jobCollection ADD FOREIGN KEY (JOB_ID) REFERENCES Job (id);
</code></pre>
<p>Looking at the OpenJPA 1.2 source code shows that the DetachedStateManager.getMetaData() method is not implemented so I'm wondering why it's being called. Any tips??</p>
|
<p>You don't show what your implementation of the copy constructor for Job is, but if you are copying the id from one Job as the id of the copy of that Job, then attempting to save the copy job will fail because JPA will know that the instance of Job with that Id lives in another object, and it is that original object that should be persisted.</p>
<p>It looks like your problem is actually in hashCode, though, and your sample shows that you don't have a hashCode implementation. It looks like openjpa instrumented you a hashCode implementation based on the value of Id. When you add something to a Set, the Set will call hashCode() on your object as part of the process of determining if the object is already in the Set.</p>
<p>I would try changing id from an int to an Integer (openjpa appears to be trying to assign from an object which might just be the boxed Integer). Or implement your own hashCode that just returns the value of Id.</p>
|
<p>I'm not familiar with JPA and therefore I don't know if your JobManager is doing the wrong thing. </p>
<p>What will be really helpful is if you could provide a longer stacktrace so we can tell what led you to <code>DetachedStateManager.getMetaData()</code> and start from somewhere there.</p>
<p>yc</p>
| 40,675
|
<p>I'm using C#, .NET 3.5. I understand how to utilize events, how to declare them in my class, how to hook them from somewhere else, etc. A contrived example:</p>
<pre><code>public class MyList
{
private List<string> m_Strings = new List<string>();
public EventHandler<EventArgs> ElementAddedEvent;
public void Add(string value)
{
m_Strings.Add(value);
if (ElementAddedEvent != null)
ElementAddedEvent(value, EventArgs.Empty);
}
}
[TestClass]
public class TestMyList
{
private bool m_Fired = false;
[TestMethod]
public void TestEvents()
{
MyList tmp = new MyList();
tmp.ElementAddedEvent += new EventHandler<EventArgs>(Fired);
tmp.Add("test");
Assert.IsTrue(m_Fired);
}
private void Fired(object sender, EventArgs args)
{
m_Fired = true;
}
}
</code></pre>
<p>However, what I do <em>not</em> understand, is when one declares an event handler</p>
<pre><code>public EventHandler<EventArgs> ElementAddedEvent;
</code></pre>
<p>It's never initialized - so what, exactly, is ElementAddedEvent? What does it point to? The following won't work, because the EventHandler is never initialized:</p>
<pre><code>[TestClass]
public class TestMyList
{
private bool m_Fired = false;
[TestMethod]
public void TestEvents()
{
EventHandler<EventArgs> somethingHappend;
somethingHappend += new EventHandler<EventArgs>(Fired);
somethingHappend(this, EventArgs.Empty);
Assert.IsTrue(m_Fired);
}
private void Fired(object sender, EventArgs args)
{
m_Fired = true;
}
}
</code></pre>
<p>I notice that there is an EventHandler.CreateDelegate(...), but all the method signatures suggest this is only used for attaching Delegates to an already existing EventHandler through the typical ElementAddedEvent += new EventHandler(MyMethod).</p>
<p>I'm not sure if <em>what</em> I am trying to do will help... but ultimately I'd like to come up with an abstract parent DataContext in LINQ whose children can register which table Types they want "observed" so I can have events such as BeforeUpdate and AfterUpdate, but specific to types. Something like this:</p>
<pre><code>public class BaseDataContext : DataContext
{
private static Dictionary<Type, Dictionary<ChangeAction, EventHandler>> m_ObservedTypes = new Dictionary<Type, Dictionary<ChangeAction, EventHandler>>();
public static void Observe(Type type)
{
if (m_ObservedTypes.ContainsKey(type) == false)
{
m_ObservedTypes.Add(type, new Dictionary<ChangeAction, EventHandler>());
EventHandler eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler;
m_ObservedTypes[type].Add(ChangeAction.Insert, eventHandler);
eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler;
m_ObservedTypes[type].Add(ChangeAction.Update, eventHandler);
eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler;
m_ObservedTypes[type].Add(ChangeAction.Delete, eventHandler);
}
}
public static Dictionary<Type, Dictionary<ChangeAction, EventHandler>> Events
{
get { return m_ObservedTypes; }
}
}
public class MyClass
{
public MyClass()
{
BaseDataContext.Events[typeof(User)][ChangeAction.Update] += new EventHandler(OnUserUpdate);
}
public void OnUserUpdated(object sender, EventArgs args)
{
// do something
}
}
</code></pre>
<p>Thinking about this made me realize I don't really understand what's happening under the hod with events - and I would like to understand :)</p>
|
<p>I've written this up in a fair amount of detail in <a href="http://pobox.com/~skeet/csharp/events.html" rel="noreferrer">an article</a>, but here's the summary, assuming you're reasonably happy with <a href="http://msdn.microsoft.com/en-us/library/ms173171.aspx" rel="noreferrer">delegates</a> themselves:</p>
<ul>
<li>An event is just an "add" method and a "remove" method, in the same way that a property is really just a "get" method and a "set" method. (In fact, the CLI allows a "raise/fire" method as well, but C# never generates this.) Metadata describes the event with references to the methods.</li>
<li>When you declare a <em><a href="http://msdn.microsoft.com/en-us/library/aa664455.aspx" rel="noreferrer">field-like event</a></em> (like your ElementAddedEvent) the compiler generates the methods <em>and a private field</em> (of the same type as the delegate). Within the class, when you refer to ElementAddedEvent you're referring to the field. Outside the class, you're referring to the field.</li>
<li>When anyone subscribes to an event (with the += operator) that calls the add method. When they unsubscribe (with the -= operator) that calls the remove.</li>
<li><p>For field-like events, there's some synchronization but otherwise the add/remove just call Delegate.<a href="http://msdn.microsoft.com/en-us/library/system.delegate.combine.aspx" rel="noreferrer">Combine</a>/<a href="http://msdn.microsoft.com/en-us/library/system.delegate.remove.aspx" rel="noreferrer">Remove</a> to change the value of the auto-generated field. Both of these operations assign to the backing field - remember that delegates are immutable. In other words, the autogenerated code is very much like this:</p>
<pre><code>// Backing field
// The underscores just make it simpler to see what's going on here.
// In the rest of your source code for this class, if you refer to
// ElementAddedEvent, you're really referring to this field.
private EventHandler<EventArgs> __ElementAddedEvent;
// Actual event
public EventHandler<EventArgs> ElementAddedEvent
{
add
{
lock(this)
{
// Equivalent to __ElementAddedEvent += value;
__ElementAddedEvent = Delegate.Combine(__ElementAddedEvent, value);
}
}
remove
{
lock(this)
{
// Equivalent to __ElementAddedEvent -= value;
__ElementAddedEvent = Delegate.Remove(__ElementAddedEvent, value);
}
}
}
</code></pre></li>
<li><p>The initial value of the generated field in your case is <code>null</code> - and it will always become <code>null</code> again if all subscribers are removed, as that is the behaviour of Delegate.Remove.</p></li>
<li><p>If you want a "no-op" handler to subscribe to your event, so as to avoid the nullity check, you can do:</p>
<pre><code>public EventHandler<EventArgs> ElementAddedEvent = delegate {};
</code></pre>
<p>The <code>delegate {}</code> is just an anonymous method which doesn't care about its parameters and does nothing.</p></li>
</ul>
<p>If there's anything that's still unclear, please ask and I'll try to help!</p>
|
<p>Under the hood, events are just delegates with special calling conventions. (For example, you don't have to check for nullity before raising an event.)</p>
<p>In pseudocode, Event.Invoke() breaks down like this:</p>
<p>If Event Has Listeners
Call each listener synchronously on this thread in arbitrary order.</p>
<p>Since events are multicast, they will have zero or more listeners, held in a collection. The CLR will loop through them, calling each in an arbitrary order.</p>
<p>One big caveat to remember is that event handlers execute in the same thread as the event is raised in. It's a common mental error to think of them as spawning a new thread. They do not.</p>
| 26,262
|
<p>How can I delete the session information from my browser by using javascript? Is it possible to do?</p>
|
<p>Session information is usually stored on the server. An HTTP request to a page that destroys the session would normally do the trick (using AJAX if you wish).</p>
<p>For cookies you can set the cookie expiry date to the current date, this will expire the cookie and remove it.</p>
<pre><code>var d = new Date();
document.cookie = "cookiename=1;expires=" + d.toGMTString() + ";" + ";";
</code></pre>
|
<p>If you don't set an expiry date to a cookie, by definition it is only session lived. Ie. it will be deleted when the user will close his browser. Thus, no need for clean up.</p>
| 31,478
|
<p>I am forking a number of processes and I want to measure how long it takes to complete the whole task, that is when all processes forked are completed. Please advise how to make the parent process wait until all child processes are terminated? I want to make sure that I stop the timer at the right moment.</p>
<p>Here is as a code I use:</p>
<pre><code>#include <iostream>
#include <string>
#include <fstream>
#include <sys/time.h>
#include <sys/wait.h>
using namespace std;
struct timeval first, second, lapsed;
struct timezone tzp;
int main(int argc, char* argv[])// query, file, num. of processes.
{
int pCount = 5; // process count
gettimeofday (&first, &tzp); //start time
pid_t* pID = new pid_t[pCount];
for(int indexOfProcess=0; indexOfProcess<pCount; indexOfProcess++)
{
pID[indexOfProcess]= fork();
if (pID[indexOfProcess] == 0) // child
{
// code only executed by child process
// magic here
// The End
exit(0);
}
else if (pID[indexOfProcess] < 0) // failed to fork
{
cerr << "Failed to fork" << endl;
exit(1);
}
else // parent
{
// if(indexOfProcess==pCount-1) and a loop with waitpid??
gettimeofday (&second, &tzp); //stop time
if (first.tv_usec > second.tv_usec)
{
second.tv_usec += 1000000;
second.tv_sec--;
}
lapsed.tv_usec = second.tv_usec - first.tv_usec;
lapsed.tv_sec = second.tv_sec - first.tv_sec;
cout << "Job performed in " <<lapsed.tv_sec << " sec and " << lapsed.tv_usec << " usec"<< endl << endl;
}
}//for
}//main
</code></pre>
|
<p>I'd move everything after the line "else //parent" down, outside the for loop. After the loop of forks, do another for loop with waitpid, then stop the clock and do the rest:</p>
<pre><code>for (int i = 0; i < pidCount; ++i) {
int status;
while (-1 == waitpid(pids[i], &status, 0));
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
cerr << "Process " << i << " (pid " << pids[i] << ") failed" << endl;
exit(1);
}
}
gettimeofday (&second, &tzp); //stop time
</code></pre>
<p>I've assumed that if the child process fails to exit normally with a status of 0, then it didn't complete its work, and therefore the test has failed to produce valid timing data. Obviously if the child processes are <em>supposed</em> to be killed by signals, or exit non-0 return statuses, then you'll have to change the error check accordingly.</p>
<p>An alternative using wait:</p>
<pre><code>while (true) {
int status;
pid_t done = wait(&status);
if (done == -1) {
if (errno == ECHILD) break; // no more child processes
} else {
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
cerr << "pid " << done << " failed" << endl;
exit(1);
}
}
}
</code></pre>
<p>This one doesn't tell you which process in sequence failed, but if you care then you can add code to look it up in the pids array and get back the index.</p>
|
<pre><code>for (int i = 0; i < pidCount; i++) {
while (waitpid(pids[i], NULL, 0) > 0);
}
</code></pre>
<p>It won't wait in the right order, but it will stop shortly after the last child dies.</p>
| 35,359
|
<p>For my C# RichTextBox, I want to programmatically do the same thing as clicking the up arrow at the top of a vertical scroll bar, which moves the RichTextBox display up by one line. What is the code for this? Thanks!</p>
|
<p>Here's what I do:</p>
<pre><code>using System.Runtime.InteropServices;
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint wMsg,
UIntPtr wParam, IntPtr lParam);
</code></pre>
<p>then call:</p>
<pre><code>SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1));
</code></pre>
<p>Seems to work OK - you might need to tweak things a bit, though.</p>
<p>Hope that helps.</p>
|
<p>window.scrollBy(0,20); </p>
<p>This will scroll the window. 20 is an approximate value I have used in the past that typically equals one line... but of course font size may impact how far one line really is.</p>
| 25,215
|
<p>Is that possible? I mean, can both ends of the many to many relationship point to the same table?</p>
|
<p>I'm not sure how you'd do it without enormous, horrible redundancy. The standard way to handle a many-to-many relationship between two tables is via a third table that contains two primary key values, one for the first table, one for the second table, with a unique constraint (read 'index') on the combination of all those columns, and possibly with one or two duplicate (non-unique) indexes on the separate primary keys. In outline:</p>
<pre><code>CREATE TABLE Table1 (pkcol1 ... PRIMARY KEY, ...);
CREATE TABLE Table2 (pkcol2 ... PRIMARY KEY, ...);
CREATE TABLE MtoM_Table1_Table2
(
pkcol1 ... REFERENCES Table1,
pkcol2 ... REFERENCES Table2,
PRIMARY KEY (pkcol1, pkcol2)
);
-- CREATE INDEX fk1_mtom_table1_table2 ON MtoM_Table1_Table2(pkcol1);
-- CREATE INDEX fk2_mtom_table1_table2 ON MtoM_Table1_Table2(pkcol2);
</code></pre>
<p>If your DBMS is intelligent, you can skip the separate index on the leading column of the primary key since the index on the primary key can also be used when searching for the just the leading value.</p>
<p>Suppose Table1 and Table2 are the same table (so, in fact, we have just Table1), as in the question; this would normally still require the MtoM_Table1_Table1 mapping table - a separate table from the main table. The mapping table must have separate names for the PK (primary key) column, but both columns (or sets of columns) in the mapping table will refer to the PK column(s) in Table1.</p>
<pre><code>CREATE TABLE Table1 (pkcol1 ... PRIMARY KEY, ...);
CREATE TABLE MtoM_Table1_Table1
(
pkcol1 ... REFERENCES Table1(pkcol1),
akcol1 ... REFERENCES Table1(pkcol1),
PRIMARY KEY (pkcol1, akcol1)
);
-- CREATE INDEX fk1_mtom_table1_table1 ON MtoM_Table1_Table1(pkcol1);
-- CREATE INDEX fk2_mtom_table1_table1 ON MtoM_Table1_Table1(akcol1);
</code></pre>
<p>If you wanted to eliminate the mapping table too, then you would have to have a second column in Table1 to hold the other PK value - call it FKcol1 (for foreign key column). This then leaves you with a quandary: what is the primary key? It has to be the combination of PKCol1 and FKCol1. But FKCol1 is supposed to reference the primary key of another row -- so you have a contradiction. Even supposing you managed to avoid that as a problem (how, exactly?), to have 'many rows' in the referencing side of the many-to-many relationship, you must have multiple rows in the master table with the same data in all columns except FKcol, but these will reference a number (more than one, in general) other rows in the table. This is a contradiction plus a nightmare of redundancy, plus you've lost your simple primary key, plus it would be horrible to work out what the heck is going on.</p>
<pre><code>CREATE TABLE Table1
(
pkcol1 ... /* PRIMARY KEY */,
fkcol1 ... /* FOREIGN KEY REFERENCES Table1(pkcol1) */,
...
);
-- CREATE INDEX fk1_table1 ON Table1(pkcol1);
-- CREATE INDEX fk2_table1 ON Table1(fkcol1);
</code></pre>
<p>So, I'm convinced that the only sane answer is "No - you cannot represent both ends of a many-to-many relationship in the same table; you must use a mapping table to retain much chance of anything working 'as usual' in the system".</p>
|
<p>If you are using hibernate-annotations, there is a @ManyToMany, not sure about the XML equivalent. It should appear in the API documentation of your distribution</p>
| 46,267
|
<p>i am trying to produce clouds effect in my flash animation using as3</p>
<p>i am able to generate clouds through action script but the real problem is how to make them be generated at one end of the screen and travel diagonally to the other end... </p>
<p>any thoughts?</p>
|
<p>This is the barebones version of what you want to do, the handleEnterFrame function will run once each frame (and for each cloud, but I'm guessing you'll prefer the simpler solution)</p>
<pre><code>package {
import flash.display.Sprite;
import flash.events.Event;
public class Cloud extends Sprite{
public var xSpeed:Number = 1;
public var ySpeed:Number = 1;
public function Cloud() {
addEventListener(Event.ENTER_FRAME, handleEnterFrame);
}
public function handleEnterFrame(e:Event):void {
x += xSpeed;
y += ySpeed;
}
}
}
</code></pre>
<p>Set "Export for actionscript" in the Linkage menu of your cloud symbol, and set the class name to "Cloud".<br>
This code should be placed in an external file called "Cloud.as", in the same directory as your flash file.<br>
(thanks to <a href="https://stackoverflow.com/users/26331/aaaidan">aaaidan</a> for pointing this out)</p>
|
<p>Check out a package called Tweener: <a href="http://code.google.com/p/tweener/" rel="nofollow noreferrer">http://code.google.com/p/tweener/</a></p>
<p>I use Tweener for all my animation needs. You simply write a line of code like so:</p>
<p>Tweener.addTween(cloudObject, {x: targetX, time: 3.0});</p>
| 47,725
|
<p>I'm looking for something like the <code>tempfile</code> module in Python: A (preferably) secure way to open a file for writing to. This should be easy to delete when I'm done too...</p>
<p>It seems, .NET does not have the "batteries included" features of the <code>tempfile</code> module, which not only creates the file, but returns the file descriptor (old school, I know...) to it along with the path. At the same time, it makes sure only the creating user can access the file and whatnot (<code>mkstemp()</code> I think): <a href="https://docs.python.org/library/tempfile.html" rel="nofollow noreferrer">https://docs.python.org/library/tempfile.html</a></p>
<hr />
<p>Ah, yes, I can see that. But GetTempFileName does have a drawback: There is a race condition between when the file was created (upon call to GetTempFileName a 0-Byte file gets created) and when I get to open it (after return of GetTempFileName). This might be a security issue, although not for my current application...</p>
|
<p>I've also had the same requirement before, and I've created a small class to solve it:</p>
<pre><code>public sealed class TemporaryFile : IDisposable {
public TemporaryFile() :
this(Path.GetTempPath()) { }
public TemporaryFile(string directory) {
Create(Path.Combine(directory, Path.GetRandomFileName()));
}
~TemporaryFile() {
Delete();
}
public void Dispose() {
Delete();
GC.SuppressFinalize(this);
}
public string FilePath { get; private set; }
private void Create(string path) {
FilePath = path;
using (File.Create(FilePath)) { };
}
private void Delete() {
if (FilePath == null) return;
File.Delete(FilePath);
FilePath = null;
}
}
</code></pre>
<p>It creates a temporary file in a folder you specify or in the system temporary folder. It's a disposable class, so at the end of its life (either <code>Dispose</code> or the destructor), it deletes the file. You get the name of the file created (and path) through the <code>FilePath</code> property. You can certainly extend it to also open the file for writing and return its associated <code>FileStream</code>.</p>
<p>An example usage:</p>
<pre><code>using (var tempFile = new TemporaryFile()) {
// use the file through tempFile.FilePath...
}
</code></pre>
|
<p>I don't know of any built in (within the framework) classes to do this, but I imagine it wouldn't be too much of an issue to roll your own..</p>
<p>Obviously it depends on the type of data you want to write to it, and the "security" required..</p>
<p><a href="http://www.developerfusion.co.uk/show/3913/" rel="nofollow noreferrer">This article</a> on DevFusion may be a good place to start?</p>
| 4,048
|
<p>I've been interested in doing some work on a desktop application for while now and my most proficient language is Java. Due to wanting to be able to compile down to a native executable, does anyone have any experience they would like to share about using gcj to compile, and CNI for libraries? I was hoping to use of of the native toolkits, not just Swing/SWT.</p>
|
<p>As Eclipse has been sucessfully compiled natively (see <a href="http://www.linuxjournal.com/article/7413" rel="nofollow noreferrer">http://www.linuxjournal.com/article/7413</a>) I would say it's possible.</p>
<p>I used GCJ to embed Java code into an C++ application, but I would not use it for a UI application. I would go pure Java there (probably Eclipse RCP based) as that is where I have experience.</p>
<p>Have fun experimenting!</p>
|
<p>I haven't used gcj for compiling to a native executable but for interfacing to native libraries I've found <a href="https://github.com/twall/jna/" rel="nofollow noreferrer">JNA</a> to be a very nice way to do it as you don't have to write any native code at all to make native calls. Note that doing it this way does result in a performance penalty so it probably wouldn't be an option if you're calling into native code in a tight loop where performance is likely to be an issue.</p>
| 46,238
|
<p>I need to create a 2D int array of size 800x800. But doing so creates a stack overflow (ha ha).</p>
<p>I'm new to C++, so should I do something like a vector of vectors? And just encapsulate the 2d array into a class?</p>
<p>Specifically, this array is my zbuffer in a graphics program. I need to store a z value for every pixel on the screen (hence the large size of 800x800).</p>
<p>Thanks!</p>
|
<p>You need about 2.5 megs, so just using the heap should be fine. You don't need a vector unless you need to resize it. See <a href="https://isocpp.org/wiki/faq/freestore-mgmt#multidim-arrays" rel="nofollow noreferrer">C++ FAQ Lite</a> for an example of using a "2D" heap array.</p>
<pre><code>int *array = new int[800*800];
</code></pre>
<p>(Don't forget to <code>delete[]</code> it when you're done.)</p>
|
<p>Well, building on what Niall Ryan started, if performance is an issue, you can take this one step further by optimizing the math and encapsulating this into a class.</p>
<p>So we'll start with a bit of math. Recall that 800 can be written in powers of 2 as:</p>
<pre><code>800 = 512 + 256 + 32 = 2^5 + 2^8 + 2^9
</code></pre>
<p>So we can write our addressing function as:</p>
<pre><code>int index = y << 9 + y << 8 + y << 5 + x;
</code></pre>
<p>So if we encapsulate everything into a nice class we get:</p>
<pre><code>class ZBuffer
{
public:
const int width = 800;
const int height = 800;
ZBuffer()
{
for(unsigned int i = 0, *pBuff = zbuff; i < width * height; i++, pBuff++)
*pBuff = 0;
}
inline unsigned int getZAt(unsigned int x, unsigned int y)
{
return *(zbuff + y << 9 + y << 8 + y << 5 + x);
}
inline unsigned int setZAt(unsigned int x, unsigned int y, unsigned int z)
{
*(zbuff + y << 9 + y << 8 + y << 5 + x) = z;
}
private:
unsigned int zbuff[width * height];
};
</code></pre>
| 8,692
|
<p>I have an img tag in my webapp that uses the onload handler to resize the image:</p>
<pre><code><img onLoad="SizeImage(this);" src="foo" >
</code></pre>
<p>This works fine in Firefox 3, but fails in IE7 because the image object being passed to the <code>SizeImage()</code> function has a width and height of 0 for some reason -- maybe IE calls the function before it finishes loading?. In researching this, I have discovered that other people have had this same problem with IE. I have also discovered that this isn't valid HTML 4. This is our doctype, so I don't know if it's valid or not:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code></pre>
<p>Is there a reasonable solution for resizing an image as it is loaded, preferably one that is standards-compliant? The image is being used for the user to upload a photo of themselves, which can be nearly any size, and we want to display it at a maximum of 150x150. If your solution is to resize the image server-side on upload, I know that is the correct solution, but I am forbidden from implementing it :( It must be done client side, and it must be done on display.</p>
<p>Thanks.</p>
<p><strong>Edit</strong>: Due to the structure of our app, it is impractical (bordering on impossible) to run this script in the document's onload. I can only reasonably edit the image tag and the code near it (for instance I could add a <code><script></code> right below it). Also, we already have Prototype and EXT JS libraries... management would prefer to not have to add another (some answers have suggested jQuery). If this can be solved using those frameworks, that would be great.</p>
<p><strong>Edit 2</strong>: Unfortunately, we must support Firefox 3, IE 6 and IE 7. It is desirable to support all Webkit-based browsers as well, but as our site doesn't currently support them, we can tolerate solutions that only work in the Big 3.</p>
|
<p>IE7 is trying to resize the image before the DOM tree is fully rendered. You need to run it on document.onload... you'll just need to make sure your function can handle being passed a reference to the element that isn't "this."</p>
<p>Alternatively... and I hope this isn't a flameable offense... jQuery makes stuff like this really, really easy.</p>
<p>EDIT in response to EDIT 1:</p>
<p>You can put <code>document.onload(runFunction);</code> in any script tag, anywhere in the body. it will still wait until the document is loaded to run the function.</p>
|
<p>You can do something like : </p>
<pre><code>var img = new Image();
img.src = '/output/preview_image.jpg' + '?' + Math.random();
img.onload = function() {
alert('pass')
}
</code></pre>
| 24,239
|
<p>I'm trying to call into a C++ library from Perl on an AIX 5.1 machine. I've created a very simple test project to try to exercise this.</p>
<p>My C++ shared library (<code>test.cpp</code>):</p>
<pre><code>#include <stdio.h>
#include <iostream>
void myfunc()
{
printf("in myfunc()\n");
std::cout << "in myfunc() also" << std::endl;
}
</code></pre>
<p>My SWIG interface file (<code>test.i</code>):</p>
<pre><code>%module test
%{
void myfunc();
%}
void myfunc();
</code></pre>
<p>I then build the shared object like so:</p>
<pre><code>swig -c++ -perl test.i
g++ -c test_wrap.cxx -I/usr/opt/perl5/lib/5.6.0/aix/CORE -o test_wrap.o
g++ -c test.cpp -o test.o
ld -G -bI:/usr/opt/perl5/lib/5.6.0/aix/CORE/perl.exp -bnoentry -bexpall -lc_r test.o test_wrap.o -o test.so
</code></pre>
<p>At this point, I have a <code>test.so</code> shared object that should be loadable in perl (via the SWIG generated <code>test.pm</code>). I have a very simple perl script to try to load the shared object and call the one function that I am exporting (<code>test.pl</code>):</p>
<pre><code>#!/usr/bin/perl
use test;
test::myfunc();
</code></pre>
<p>When I run <code>test.pl</code>, I get the following output:</p>
<blockquote>
<p>in myfunc()<br>
Illegal instruction (core dumped)</p>
</blockquote>
<p>If I comment-out the <code>std::cout</code> usage in <code>myfunc</code>, it works without problem. It appears as though using anything in the C++ STL causes a core dump (I tried just declaring a <code>std::vector</code> and <code>std::stringstream</code>, both result in the core dump). I can create a standalone C++ executable that uses the STL without any issues, it's only when called in my shared object when loaded from perl that I get into trouble.</p>
<p>I've also tried using xlc rather than gcc, but I get the same result. I'm thinking there is some funky linker flag that I need to pass in to ensure that all of the linkage occurs correctly? Any ideas are welcome...</p>
<p>Edit: If I link using <code>gcc</code>/<code>xlc</code> instead of invoking the linker directly (<code>ld</code>), I immediately get a segmentation fault. It looks like it crashes when perl is trying to simply load the shared library. Calling <code>ld</code> as I have above is the closest that I've got it to working, but I think I may be missing some libraries or special AIX linker flags for the C++ libraries.</p>
<p>Edit2: Ok, I've got it working. AIX is very fragile when it comes to linking. I ultimately came up with the following link command that seems to be working correctly:</p>
<pre><code>ld -G -bI:/usr/opt/perl5/lib/5.6.0/aix/CORE/perl.exp -bnoentry -bexpall -lC -lc -ldl test.o test_wrap.o -o test.so
</code></pre>
<p>The libraries that I linked against are the most relevant. It turns out that the order in which the libraries are mentioned is very important also (ugh). Also note that this is being built against Perl 5.6.0 that ships with AIX 5.1. I've tried building this same simple application against Perl 5.8.8 and it doesn't work. However, I'm pretty sure the much more sane method of linking (using straight <code>gcc</code>/<code>xlc</code> instead of having to call <code>ld</code> directly) seems to work better. So this issue appears to be a bug in the Perl distribution or the linker or something.</p>
<p>Hopefully this will help some poor soul cursed with having to work with AIX...</p>
|
<p>Wouldn't you just add your libstdc++ to your ld command? e.g., <code>-lstdc++</code>?</p>
<p>What I did on Linux, after replicating your problem was:</p>
<pre><code>gcc -g -lstdc++ -shared test*.o -o test.so
</code></pre>
<p>Then the problem went away.</p>
<p>(Trying to get the exact right list of libraries for ld was too much work, so I just told gcc to do it for me.)</p>
|
<p>I know nothing about SWIG, but you might also want to check that it's expecting a function using cdecl (rather than pascal, fastcall, or some other calling convention). Using the wrong one between tools can lead to "bad things happening" (usually stack corruption, as far as I can tell).</p>
| 22,379
|
<p>I want to "remove" a UIView from a superview and add it again at the end... but at the "bottom" of the rest of the UIviews that belong to the superview. </p>
<p>Is this possible?</p>
<p>Any help is very appreciated!</p>
|
<p>Hmmm...</p>
<pre><code>- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;
</code></pre>
<p>Might be what you're after? Alternatively -</p>
<pre><code>- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;
</code></pre>
<p>Though you could avoid removing the view all together (if you don't need to for any other reason) by calling sendSubviewToBack: -</p>
<pre><code>- (void)sendSubviewToBack:(UIView *)view;
</code></pre>
|
<p>I don't really understand what you mean by bottom.
You can use: <code>[view removeFromSuperview];</code> to remove it ( make sure you <code>retain</code> it ( <code>[view retain];</code> ) before you do that and <code>release</code> <code>[view release];</code> when it's no longer needed.</p>
<p>Another thing you can do if you want one view to be behind another view is to set its "<code>zPosition</code>" ( <code>view.layer.zPosition = X;</code> )</p>
<p>if a View has a <code>zPosition</code> that is bigger than another views <code>zPosition</code> it will appear on top of the other view.</p>
| 29,531
|
<p>I'm trying to understand the concepts behind DDD, but I find it hard to understand just by reading books as they tend to discuss the topic in a rather abstract way. I would like to see some good implementations of DDD in code, preferably in C#.</p>
<p>Are there any good examples of projects practicing DDD in the open source world?</p>
|
<p>Eric Evans and a Swedish consulting company have released a sample application based on the shipping example that Eric uses throughout the book. It's in Java, but the concepts are well documented on the project page.</p>
<p><a href="http://dddsample.sourceforge.net/" rel="nofollow noreferrer">http://dddsample.sourceforge.net/</a></p>
<p>However, be warned that DDD is more about the journey than the destination. Understand that the sample code you are looking took many forms before it became what you see now. You did not see the awkward models that were used initially and you're missing the steps taken to refactor the model based on insight gained along the way. While the building blocks are important in DDD, Eric belives they are over-emphasized, so take all samples with a grain of salt.</p>
|
<p>I haven't used any myself, but there are some tools mentioned on the DDD Wikipedia page. Most of them seem to be implemented in Java though.</p>
<p><a href="http://en.wikipedia.org/wiki/Domain-driven_design#Software_tools_to_support_domain-driven_design" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Domain-driven_design#Software_tools_to_support_domain-driven_design</a></p>
| 18,347
|
<p>How to list physical disks in Windows?
In order to obtain a list of <code>"\\\\.\PhysicalDrive0"</code> available.</p>
|
<p>#WMIC
<a href="http://www.ss64.com/nt/wmic.html" rel="nofollow noreferrer">wmic</a> is a very complete tool</p>
<pre class="lang-none prettyprint-override"><code>wmic diskdrive list
</code></pre>
<p>provide a (too much) detailed list, for instance</p>
<p>for less info</p>
<pre class="lang-none prettyprint-override"><code>wmic diskdrive list brief
</code></pre>
<p>#C
<a href="https://stackoverflow.com/users/281306/sebastian-godelet">Sebastian Godelet</a> mentions <a href="https://stackoverflow.com/questions/327718/how-to-list-physical-disks/327724#comment18466111_327724">in the comments</a>:</p>
<blockquote>
<p>In C:</p>
</blockquote>
<pre class="lang-c prettyprint-override"><code>system("wmic diskdrive list");
</code></pre>
<p>As commented, you can also call the WinAPI, but... as shown in "<a href="https://stackoverflow.com/a/1431517/6309">How to obtain data from WMI using a C Application?</a>", this is quite complex (and generally done with C++, not C).</p>
<hr />
<p>#PowerShell
Or with PowerShell:</p>
<pre><code>Get-WmiObject Win32_DiskDrive
</code></pre>
<hr />
<p>Update Feb. 2022, Microsoft announces in "<a href="https://learn.microsoft.com/en-us/windows/deployment/planning/windows-10-deprecated-features" rel="nofollow noreferrer">Windows 10 features we're no longer developing</a>"</p>
<blockquote>
<p>The WMIC tool is deprecated in Windows 10, version 21H1 and the 21H1 General Availability Channel release of Windows Server.</p>
<p>This tool is superseded by <strong><a href="https://learn.microsoft.com/en-us/powershell/scripting/learn/ps101/07-working-with-wmi" rel="nofollow noreferrer">Windows PowerShell for WMI</a></strong>.</p>
<p>Note: This deprecation only applies to the <a href="https://learn.microsoft.com/en-us/windows/win32/wmisdk/wmic" rel="nofollow noreferrer">command-line management tool</a>. WMI itself is not affected.</p>
</blockquote>
|
<p>Make a list of all letters in the US English Alphabet, skipping a & b. "CDEFGHIJKLMNOPQRSTUVWXYZ". Open each of those drives with <code>CreateFile</code> e.g. <code>CreateFile("\\.\C:")</code>. If it does not return <code>INVALID_HANDLE_VALUE</code> then you got a 'good' drive. Next take that handle and run it through <code>DeviceIoControl</code> to get the Disk #. <strong><a href="https://stackoverflow.com/a/9312075/504239">See my related answer for more details</a></strong>.</p>
| 42,479
|
<p>When would a database design be described as overnormalized? Is this characterization an absolute one? Or is it dependent on the way it is used in the application? Thanks.</p>
|
<p>In the general sense, I think that overnormalized is when you are doing so many JOINs to retrieve data that it is causing notable performance penalties and deadlocks on your database, even after you've tuned the heck out of your indexes. Obviously, for huge applications and sites like MySpace or eBay, de-normalization is a scaling requirement.</p>
<p>As a developer for several small businesses, I tell you that in my experience it's always been easier to go from normalized -> denormalized than the other way around, and in fact going the other way around (to avoid duplication of data now that the business requirements have changed a year or so later) is much more difficult.</p>
<p>When I read general statements such as "you should put the address in your customers table instead of a separate address table so you can avoid the join", I shudder, because you just know that a year from now somebody's going to ask you to do something with addresses that you totally didn't foresee, like maintaining an audit trail, or storing multiple per customer. If your database allows you to create an indexed view, you can sidestep that issue until you get to the point where your dataset is so large that it can't possibly exist or be served by a single server or set of servers in a 1-write, many-read environment. For most of us, I don't think that scenario happens very often.</p>
<p>When in doubt, I aim for third normal form with some exceptions (for example, having a field contain a CSV-list of separated strings because I know I'll never ever look at the data from the other angle). When I need to consolidate, I'll look at my views or indexes first. Hope this helps.</p>
|
<p>In my experience, I've never seen a normalized database that contains postal addresses, as it's usually acceptable to store the address as a string. Ideally, there would be tables for countries, counties / states, cities, districts and streets. I've not come across anyone who needs to report on street level, so it hasn't been necessary. The addresses have only be used for postal contact, so are treated as a single entity.</p>
| 37,359
|
<p>How would retrieve all customer's birthdays for a given month in SQL? What about MySQL?
I was thinking of using the following with SQL server.</p>
<pre><code>select c.name
from cust c
where datename(m,c.birthdate) = datename(m,@suppliedDate)
order by c.name
</code></pre>
|
<p>don't forget the 29th February...</p>
<pre><code>SELECT c.name
FROM cust c
WHERE (
MONTH(c.birthdate) = MONTH(@suppliedDate)
AND DAY(c.birthdate) = DAY(@suppliedDate)
) OR (
MONTH(c.birthdate) = 2 AND DAY(c.birthdate) = 29
AND MONTH(@suppliedDate) = 3 AND DAY(@suppliedDate) = 1
AND (YEAR(@suppliedDate) % 4 = 0) AND ((YEAR(@suppliedDate) % 100 != 0) OR (YEAR(@suppliedDate) % 400 = 0))
)
</code></pre>
|
<pre><code> SELECT * FROM tbl_Employee WHERE DATEADD( Year, DATEPART( Year, GETDATE()) - DATEPART( Year, DOB), DOB) BETWEEN CONVERT( DATE, GETDATE()) AND CONVERT( DATE, GETDATE() + 30)
</code></pre>
<p>This can be use to get the upcoming Birthday by days</p>
| 13,798
|
<p>Given an Oracle table created using the following:</p>
<pre><code>CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE);
</code></pre>
<p>Using the Python ODBC module from its <a href="http://www.python.org/download/windows/" rel="nofollow noreferrer">Win32 extensions</a> (from the win32all package), I tried the following:</p>
<pre><code>import dbi, odbc
connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD")
cursor = connection.cursor()
cursor.execute("SELECT WhenAdded FROM Log")
results = cursor.fetchall()
</code></pre>
<p>When I run this, I get the following:</p>
<pre><code>Traceback (most recent call last):
...
results = cursor.fetchall()
dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s
in FETCH
</code></pre>
<p>The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps?</p>
|
<p>I believe this is a bug in the Oracle ODBC driver. Basically, the Oracle ODBC driver does not support the <code>TIMESTAMP WITH (LOCAL) TIME ZONE</code> data types, only the <code>TIMESTAMP</code> data type. As you have discovered, one workaround is in fact to use the <code>TO_CHAR</code> method.</p>
<p>In your example you are not actually reading the time zone information. If you have control of the table you could convert it to a straight <code>TIMESTAMP</code> column. If you don't have control over the table, another solution may be to create a view that converts from <code>TIMESTAMP WITH TIME ZONE</code> to <code>TIMESTAMP</code> via a string - sorry, I don't know if there is a way to convert directly from <code>TIMESTAMP WITH TIME ZONE</code> to <code>TIMESTAMP</code>.</p>
|
<p>My solution to this, that I hope can be bettered, is to use Oracle to explicitly convert the TIMESTAMP into a string:</p>
<pre><code>cursor.execute("SELECT TO_CHAR(WhenAdded, 'YYYY-MM-DD HH:MI:SSAM') FROM Log")
</code></pre>
<p>This works, but isn't portable. I'd like to use the same Python script against a SQL Server database, so an Oracle-specific solution (such as TO_CHAR) won't work.</p>
| 5,935
|
<p>I am trying to call a webservice using ssl.
How do i get the relevant server cert so that i can import it into my truststore?
I know about the use of property com.ibm.ssl.enableSignerExchangePrompt from a main method but i would add the server cert to my truststore manually.</p>
<p>I dont want this property set in any of my servlets</p>
<p>Any help is greatly appreciated
Thanks
Damien</p>
|
<p>you can programmatically do this with Java by implementing your own X509TrustManager. </p>
<pre><code>
public class dummyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//do nothing
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// do nothing
}
public X509Certificate[] getAcceptedIssuers() {
//just return an empty issuer
return new X509Certificate[0];
}
}
</code></pre>
<p>Then you can use this trust manager to create a SSL sockect </p>
<pre><code>
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, new TrustManager[] { new dummyTrustManager() },
new java.security.SecureRandom());
SSLSocketFactory factory = context.getSocketFactory();
InetAddress addr = InetAddress.getByName(host_);
SSLSocket sock = (SSLSocket)factory.createSocket(addr, port_);
</code></pre>
<p>Then with that socket you can just extract the server certificate (an put import it
in the trusted keystore)</p>
<pre><code>
SSLSession session = sock.getSession();
Certificate[] certchain = session.getPeerCertificates();
</code></pre>
|
<p>If you browse to the site in your web browser you can look at the security info by hitting the little padlock icon and in the dialog that pops up you can save the certificate. </p>
<p><strong>Steps for Chrome</strong></p>
<ol>
<li>Click the padlock(in the address bar)</li>
<li>Click 'Certificate Information'</li>
<li>Under the 'Details' tab you can select 'Copy to file...'.</li>
</ol>
| 17,630
|
<p>When a Java VM crashes with an EXCEPTION_ACCESS_VIOLATION and produces an hs_err_pidXXX.log file, what does that indicate? The error itself is basically a null pointer exception. Is it always caused by a bug in the JVM, or are there other causes like malfunctioning hardware or software conflicts?</p>
<p>Edit: there is a native component, this is an SWT application on win32.</p>
|
<p>Most of the times this is a bug in the VM.
But it can be caused by any native code (e.g. JNI calls).</p>
<p>The hs_err_pidXXX.log file should contain some information about where the problem happened.</p>
<p>You can also check the "Heap" section inside the file. Many of the VM bugs are caused by the garbage collection (expecially in older VMs). This section should show you if the garbage was running at the time of the crash. Also this section shows, if some sections of the heap are filled (the percentage numbers). </p>
<p>The VM is also much more likely to crash in a low memory situation than otherwise.</p>
|
<p>Are you using a Browser widget and executing javascript in the Browser widget? If so, then there are bugs in some versions of SWT that causes the JVM to crash in native code, in various Windows libraries.</p>
<p>Two examples (that I opened) are <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=217306" rel="nofollow noreferrer">bug 217306</a> and <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=127960" rel="nofollow noreferrer">bug 127960</a>. These two bug reports are not the only bug reports of the JVM crashing in SWT, however.</p>
<p>If you aren't using the Browser widget then these suggestions won't help you. In that case, you can search for a list of <a href="https://bugs.eclipse.org/bugs/buglist.cgi?quicksearch=swt+jvm+crash" rel="nofollow noreferrer">SWT bugs causing a JVM crash</a>. If none of those are your issue, then I highly recommend that you open a bug report with SWT.</p>
| 16,942
|
<p>I am getting the following error:</p>
<blockquote>
<p>Access denied for user 'apache'@'localhost' (using password: NO)</p>
</blockquote>
<p>When using the following code:</p>
<pre><code><?php
include("../includes/connect.php");
$query = "SELECT * from story";
$result = mysql_query($query) or die(mysql_error());
echo "<h1>Delete Story</h1>";
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)){
echo '<b>'.$row[1].'</b><span align="right"><a href="../process/delete_story.php?id='.$row[0].'">Delete</a></span>';
echo '<br /><i>'.$row[2].'</i>';
}
}
else {
echo "No stories available.";
}
?>
</code></pre>
<p>The <code>connect.php</code> file contains my MySQL connect calls that are working fine with my <code>INSERT</code> queries in another portion of the software. If I comment out the <code>$result = mysql_query</code> line, then it goes through to the else statement. So, it is that line or the content in the if.</p>
<p>I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions.</p>
|
<blockquote>
<p>And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter.</p>
</blockquote>
<p>If it is saying 'apache@localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection.</p>
<p>If you do the connection right in your script, not in a called file, do you get the same error?</p>
|
<p>Just to check, if you use <strong>just</strong> this part you get an error?</p>
<pre><code><?php
include("../includes/connect.php");
$query = "SELECT * from story";
$result = mysql_query($query) or die(mysql_error());
</code></pre>
<p>If so, do you still get an error if you copy and paste one of those Inserts into this page, I am trying to see if it's local to the page or that actual line.</p>
<p>Also, can you post a copy of the connection calls (minus passwords), unless the inserts use exactly the same syntax as this example.</p>
| 2,505
|
<p>The idea is to move all of the right elements into the left and the left into the right with an empty space in the middle. The elements can either jump over one or two pieces into an empty space. </p>
<pre><code>LLL[ ]RRR
</code></pre>
<p>I'm trying to think of a heuristic for this task. Is the heuristic meant to aid in finding a possible solution, or actually return a number of moves as the solution? How would I express such a heuristic?</p>
|
<p>Sounds like you are a bit confused about what a heuristic is.</p>
<p>A rough definition is "a simplifying assumption" or "a decent guess"</p>
<p>For example, let's say you have to put together a basketball team, and you have fact sheets on people who want to play that list their contact info, birth date, and height. You could hold tryouts where you test each candidate's specific skills; that would require bringing in all the candidates, though, and that could take a long time. You use a heuristic to narrow the search -- only call people who are at least 6'2" tall. This might ignore some great basketball players, but it's a pretty decent guess.</p>
<p>Another example of a heuristic: you are trying to use the smallest number of coins to pay a bill. The heuristic (a simplifying approach) is to pick the coin with the biggest value (which is less than the remaining bill) first, subtract the value from the bill, and repeat. This is not guaranteed to work every time, but it'll get you to the right neighborhood most of the time.</p>
<p>A heuristic for your problem might be "never move Ls to the right, and never move Rs to the left" -- it narrows the "search space" of all possible moves by eliminating some of the possibilities from the outset.</p>
|
<p>A heuristic is generally a "hint" which usually (but not always) will guide your procedure to the correct direction. Using heuristics speeds up your procedures (your algorithms), again, <strong>usually</strong>, but not always. It's like an "advice" to the algorithm which is correct more often than not.</p>
<p>I'm not sure what you are looking for, as the description is a little vague. If you want the algorithm, you will need to study what effect a particular move will have to the current situation and a way to step forward for all possible moves each time, in effect traversing a tree of states (ie. states that will evolve if you make a particular sequence of moves).</p>
<p>You can also see that it possibly matters <strong>how close</strong> the current position is to what you want to achieve (your desired final position).So instead of calculating all the possible paths from your initial state until you find the final state, you can guide your algorithm based on the heuristic "how close is the current state to the desired one" and only traverse a part of the tree.</p>
| 36,727
|
<p>From the <em>Immediate Window</em> in Visual Studio: </p>
<pre><code>> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"
</code></pre>
<p>It seems that they should both be the same. </p>
<p>The old FileSystemObject.BuildPath() didn't work this way...</p>
|
<p>This is kind of a philosophical question (which perhaps only Microsoft can truly answer), since it's doing exactly what the documentation says.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx" rel="noreferrer">System.IO.Path.Combine</a></p>
<p>"If path2 contains an absolute path, this method returns path2."</p>
<p><a href="http://referencesource.microsoft.com/#mscorlib/system/io/path.cs,2d7263f86a526264" rel="noreferrer">Here's the actual Combine method</a> from the .NET source. You can see that it calls <a href="http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#16ed6da326ce4745" rel="noreferrer">CombineNoChecks</a>, which then calls <a href="http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#807960f08fca497d" rel="noreferrer">IsPathRooted</a> on path2 and returns that path if so:</p>
<pre><code>public static String Combine(String path1, String path2) {
if (path1==null || path2==null)
throw new ArgumentNullException((path1==null) ? "path1" : "path2");
Contract.EndContractBlock();
CheckInvalidPathChars(path1);
CheckInvalidPathChars(path2);
return CombineNoChecks(path1, path2);
}
internal static string CombineNoChecks(string path1, string path2)
{
if (path2.Length == 0)
return path1;
if (path1.Length == 0)
return path2;
if (IsPathRooted(path2))
return path2;
char ch = path1[path1.Length - 1];
if (ch != DirectorySeparatorChar && ch != AltDirectorySeparatorChar &&
ch != VolumeSeparatorChar)
return path1 + DirectorySeparatorCharAsString + path2;
return path1 + path2;
}
</code></pre>
<p>I don't know what the rationale is. I guess the solution is to strip off (or Trim) DirectorySeparatorChar from the beginning of the second path; maybe write your own Combine method that does that and then calls Path.Combine().</p>
|
<p>This \ means "the root directory of the current drive". In your example it means the "test" folder in the current drive's root directory. So, this can be equal to "c:\test".</p>
| 7,652
|
<p>As everyone knows, the <a href="http://en.wikipedia.org/wiki/Visual_C%2B%2B" rel="nofollow noreferrer">Visual C++</a> runtime marks uninitialized or just freed memory blocks with special non-zero markers. Is there any way to disable this behavior entirely without manually setting all uninitialized memory to zeros? It's causing havoc with my valid not null checks, since <code>0xFEEEFEEE != 0</code>.</p>
<p>Hrm, perhaps I should explain a bit better. I create and initialize a variable (via new), and that all goes just fine. When I free it (via delete), it sets the pointer to <code>0xFEEEFEEE</code> instead of <code>NULL</code>. When I insert a proper check for <code>NULL</code>, as all good programs that manage their own memory should, I come up with problems as <code>0xFEEEFEEE</code> passes a <code>NULL</code> check without problems. Is there any good way, other than manually setting all pointers to <code>NULL</code> when deleting them, to detect when memory has already been freed? I would prefer to not use <a href="http://en.wikipedia.org/wiki/Boost_C%2B%2B_Libraries" rel="nofollow noreferrer">Boost</a> simply because I don't want the overhead, small though it may be, since that's the only thing I'd be using Boost for.</p>
|
<p>When you create a pointer, explicity initialize it to <code>NULL</code>. Likewise after a <code>delete</code>. Depending on the value of uninitialized data (except in a few specific cases) is asking for trouble.</p>
<p>You can save yourself a lot of headaches by using a smart pointer class (such as <a href="http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/shared_ptr.htm" rel="nofollow noreferrer"><code>boost::shared_ptr</code></a>) which will automatically deal with whether a pointer is initialized or not.</p>
|
<p>I'm pretty sure you can't disable the visual studio default here, and even if you did, the value would then be just whatever was in memory before the memory was allocated.</p>
<p>Your best off just getting in the habit of setting them to 0 in the first place, it's only 2 extra charecters.</p>
<pre><code>int *ptr=0;
</code></pre>
<p>You can also use the NULL macro, which is defined as 0 (but not be default, so be carful with multiple definitions when includeing stuff like windows.h and defining it yourself!</p>
| 9,143
|
<p>Example C API signature:</p>
<p><code>void Func(unsigned char* bytes);</code></p>
<p>In C, when I want to pass a pointer to an array, I can do:</p>
<pre><code>unsigned char* bytes = new unsigned char[1000];
Func(bytes); // call
</code></pre>
<p>How do I translate the above API to P/Invoke such that I can pass a pointer to C# byte array?</p>
|
<p>The easiest way to pass an array of bytes is to declare the parameter in your import statement as a byte array. </p>
<pre><code>[DllImport EntryPoint="func" CharSet=CharSet.Auto, SetLastError=true]
public extern static void Func(byte[]);
byte[] ar = new byte[1000];
Func(ar);
</code></pre>
<p>You should also be able to declare the parameter as an IntPtr and Marshal the data manually.</p>
<pre><code>[DllImport EntryPoint="func" CharSet=CharSet.Auto, SetLastError=true]
public extern static void Func(IntPtr p);
byte[] ar = new byte[1000];
IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * ar.Length);
Marshal.Copy(ar, 0, p, ar.Length);
Func(p);
Marshal.FreeHGlobal(p);
</code></pre>
|
<p>Here is the appropriate signature for the native function.</p>
<pre><code>[System.Runtime.InteropServices.DllImportAttribute("<Unknown>", EntryPoint="Func")]
public static extern void Func(System.IntPtr bytes) ;
</code></pre>
| 36,800
|
<p>I understand that some countries have laws regarding website accessibility. In general, what are the minimum requirements that a website must meet to be accessible, regardless of country? Or, in lieu of minimum requirements, what are some specific things that websites should have to make the accessible?</p>
|
<p>W3C publishes Web Content Accessibility Guidelines:</p>
<p><a href="http://www.w3.org/TR/WAI-WEBCONTENT/" rel="nofollow noreferrer">http://www.w3.org/TR/WAI-WEBCONTENT/</a></p>
<p>If you want a quick summary list, look for the yellow-highlighted lines in that document. Each guideline is also broken down into specific requirements ("checkpoints") in one of three priorities - to claim any kind of accessibility under this scheme you must satisfy all priority 1 checkpoints, but they're "necessary" rather than "sufficient" conditions.</p>
<p>Looking at your pages in lynx is also a good measure - if it won't render in text, chances are good that a screen reader will have a difficult time of it too.</p>
|
<p>It's not a binary question, and there's no silver bullet. Making sure you follow at least the basics of WCAG and testing in a couple of screen readers and without the mouse will probably be the most effective use of your time. If at all possible, test with real people with real disabilities, they have a perspective that is hard for fully-abled people to attain.</p>
| 10,116
|
<p>Some WPF controls (like the <code>Button</code>) seem to happily consume all the available space in its' container if you don't specify the height it is to have.</p>
<p>And some, like the ones I need to use right now, the (multiline) <code>TextBox</code> and the <code>ListBox</code> seem more worried about just taking the space necessary to fit their contents, and no more. </p>
<p>If you put these guys in a cell in a <code>UniformGrid</code>, they will expand to fit the available space. However, <code>UniformGrid</code> instances are not right for all situations. What if you have a grid with some rows set to a * height to divide the height between itself and other * rows? What if you have a <code>StackPanel</code> and you have a <code>Label</code>, a <code>List</code> and a <code>Button</code>, how can you get the list to take up all the space not eaten by the label and the button?</p>
<p>I would think this would really be a basic layout requirement, but I can't figure out how to get them to fill the space that they could (putting them in a <code>DockPanel</code> and setting it to fill also doesn't work, it seems, since the <code>DockPanel</code> only takes up the space needed by its' subcontrols).</p>
<p>A resizable GUI would be quite horrible if you had to play with <code>Height</code>, <code>Width</code>, <code>MinHeight</code>, <code>MinWidth</code> etc. </p>
<p>Can you bind your <code>Height</code> and <code>Width</code> properties to the grid cell you occupy? Or is there another way to do this?</p>
|
<p>There are also some properties you can set to force a control to fill its available space when it would otherwise not do so. For example, you can say:</p>
<pre><code>HorizontalContentAlignment="Stretch"
</code></pre>
<p>... to force the contents of a control to stretch horizontally. Or you can say:</p>
<pre><code>HorizontalAlignment="Stretch"
</code></pre>
<p>... to force the control itself to stretch horizontally to fill its parent.</p>
|
<p>Use the <strong>HorizontalAlignment</strong> and <strong>VerticalAlignment</strong> layout properties. They control how an element uses the space it has inside its parent when more room is available than it required by the element.</p>
<p>The width of a StackPanel, for example, will be as wide as the widest element it contains. So, all narrower elements have a bit of excess space. The alignment properties control what the child element does with the extra space.</p>
<p>The default value for both properties is Stretch, so the child element is stretched to fill all available space. Additional options include Left, Center and Right for <strong>HorizontalAlignment</strong> and Top, Center and Bottom for <strong>VerticalAlignment</strong>.</p>
| 5,677
|
<p>I have a site that I've developed that makes decent use of Javascript, and minimal use of AJAX for a few things. The site worked fine on the iPhone until I added the <a href="http://www.w3schools.com/Ajax/ajax_server.asp" rel="nofollow noreferrer">function to create an HttpRequest handle</a> at which point all Javascript on the iPhone now silently fails. So, I have a few questions.</p>
<p>(1) It seems that AJAX does not work at all on the iPhone. IS this true? If not, how can I modify the HttpRequest create function to accomodate the iPhone?</p>
<p>(2) If AJAX is indeed impossible on the iPhone, is there a way I can modify the function given so that it will fail gracefully on the iPhone, and other scripts on the page will still function?</p>
<p>(3) If this is not true, what do I need to do server side (and is this even possible?) do detect the iPhone, so that I can remove the AJAX code entirely when an iPhone requests the page?</p>
<p>What would <em>also</em> work quite nicely is the ability to use CSS to detect the iPhone as a display device, and act accordingly, similar to what you use with Opera Show. Of course, this wouldn't fix the AJAX issue, but it would be neat. ^_^</p>
<p>Thanks for answers. Several of my customers access the site regularly from the iPhone, and I want my pages to work as much as they possibly can, so I'm willing to modify my code for it, even though I don't have one to test on.</p>
|
<p>Of course the iPhone supports ajax, check out <a href="http://developer.apple.com/webapps/" rel="noreferrer">http://developer.apple.com/webapps/</a> for a BUNCH of resources for developing iPhone webapps. I would recommend using a framework (such as <a href="http://www.jquery.com/" rel="noreferrer">jQuery</a>, or <a href="http://code.google.com/p/iui/" rel="noreferrer">iUI</a> (for ui)) rather than rolling your own ajax functionality, it will already address a lot of the browser quirks and be optimised. </p>
|
<p>Aax works perfectly on the iPhone, even our most advanced stuff like the <a href="http://ra-ajax.org/samples/Viewport-Calendar-Starter-Kit.aspx" rel="nofollow noreferrer">Ajax Calendar Starter-Kit</a> works flawlessly on at least my iPhone (3G)</p>
| 32,534
|
<p>In Google groups and some other web sites, there is a 5-star rating component which is pretty neat, such as in this url:
<a href="http://groups.google.com/group/Google-Picasa-Data-API/browse_thread/thread/b5a346e6429a70a7?hl=en" rel="noreferrer">http://groups.google.com/group/Google-Picasa-Data-API/browse_thread/thread/b5a346e6429a70a7?hl=en</a></p>
<p>I am wondering whether there is an existing 5-star rating component in the iPhone environment. Or if there is not, if anyone has clue where to start?</p>
<p>Thanks</p>
|
<p>UIView that allows you to build Rating components to provide the same kind of experience AppStore or Youtube applications on iPhone do.</p>
<p><a href="http://code.google.com/p/s7ratingview/" rel="nofollow noreferrer">http://code.google.com/p/s7ratingview/</a></p>
|
<p>You can give <a href="https://github.com/dyang/DYRateView" rel="nofollow noreferrer">DYRateView</a> a try.</p>
<p>There is a tutorial on my blog on how to use DYRateView in your project: <a href="http://iappexperience.com/post/23227218867/dyrateview-a-simple-yet-powerful-rating-control-for" rel="nofollow noreferrer">http://iappexperience.com/post/23227218867/dyrateview-a-simple-yet-powerful-rating-control-for</a>.</p>
<p><a href="https://i.stack.imgur.com/yB6xd.png" rel="nofollow noreferrer" title="Read only view"><img src="https://i.stack.imgur.com/yB6xd.png" alt="picture" title="Read only view" /></a></p>
<p><a href="https://i.stack.imgur.com/EmOAr.png" rel="nofollow noreferrer" title="Edit view"><img src="https://i.stack.imgur.com/EmOAr.png" alt="picture" title="Edit view" /></a></p>
| 37,276
|
<p>In my web application I have a file which hold the current revision number via $Rev$. This work fine except, if I don't make any changes to that file, it doesn't get committed.</p>
<p><strong>Is there anyway I can force a single file to always get committed to the SVN server?</strong></p>
<p><em>I'm using TortoiseSVN for Windows so any code or step-by-step instructions would be helpful.</em></p>
|
<p>Basically, you want the output of the <code>svnversion</code> command in a file.</p>
<p>Such files are usually kept out of the repository, and automatically created by a build script. I suggest you do the same. If you don't build, but just to a <code>svn up</code> on the server side, just call <code>svnversion</code> after <code>svn up</code> or create a shell script to do both actions.</p>
<p>If you <strong>have</strong> to keep it in the repository on the other hand, calling <code>svnversion</code> in a pre-commit hook would be your best bet.</p>
|
<p>Depending on your client, some of them offer a pre-commit hook that you can implement something that simply "touches" the file and flags it as changed. If your using something like Visual Studio you could create a post build task that would "touch" the file but you would have to make sure that you do a build before committing changes.</p>
| 2,781
|
<p>In SQL server 2005 this query</p>
<pre><code>select len(cast('the quick brown fox jumped over the lazy dog' as varchar))
</code></pre>
<p>returns 30 as length while the supplied string has more characters. This seems to be the default. Why 30, and not 32 or any other power of 2?</p>
<p><strong>[EDIT]</strong> I am aware that I should always specifiy the length when casting to varchar but this was a quick let's-check-something query. Questions remains, why 30?</p>
|
<p>Why don't you specify the varchar length? ie:</p>
<pre><code>SELECT CAST('the quick brown fox jumped over the lazy dog' AS VARCHAR(45))
</code></pre>
<p>As far as why 30, that's the default length in SQL Server for that type.</p>
<p>From <a href="http://msdn.microsoft.com/en-us/library/ms176089.aspx" rel="noreferrer">char and varchar (Transact-SQL)</a>:</p>
<blockquote>
<p>When n is not specified in a data definition or variable declaration statement, the default length is 1. <em>When n is not specified when using the CAST and CONVERT functions, the default length is 30.</em></p>
</blockquote>
|
<p>Default size with convert/cast has nothing to do with the memory allocation and hence the default value (ie 30) is not related to any power of 2.</p>
<p>regarding why 30, this is microsoft's guideline which gives this default value so as to cover the basic data in first 30 characters.
<a href="http://msdn.microsoft.com/en-us/library/ms176089.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms176089.aspx</a></p>
<p>Although one can always alter the length during conversion/cast process </p>
<pre><code>select len(cast('the quick brown fox jumped over the lazy dog' as varchar(max)))
</code></pre>
| 46,853
|
<p>Because of the more tedious way of adding hosts to be monitored in Nagios (it requires defining a host object, as opposed to the previous program which only required the IP and hostname), I figured it'd be best to automate this, and it'd be a great time to learn Perl, because all I know at the moment is C/C++ and Java. </p>
<p>The file I read from looks like this:</p>
<pre><code>xxx.xxx.xxx.xxx hostname #comments. i.dont. care. about
</code></pre>
<p>All I want are the first 2 bunches of characters. These are obviously space delimited, but for the sake of generality, it might as well be anything. To make it more general, why not the first and third, or fourth and tenth? Surely there must be some regex action involved, but I'll leave that tag off for the moment, just in case.</p>
|
<p>The one-liner is great, if you're not writing more Perl to handle the result.</p>
<p>More generally though, in the context of a larger Perl program, you would either write a custom regular expression, for example:</p>
<pre><code>if($line =~ m/(\S+)\s+(\S+)/) {
$ip = $1;
$hostname = $2;
}
</code></pre>
<p>... or you would use the <em>split</em> operator.</p>
<pre><code>my @arr = split(/ /, $line);
$ip = $arr[0];
$hostname = $arr[1];
</code></pre>
<p>Either way, add logic to check for invalid input.</p>
|
<p>Since ray asked, I thought I'd rewrite my whole program without using Perl's implicitness (except the use of <code><ARGV></code>; that's hard to write out by hand). This will probably make Python people happier (braces notwithstanding :-P):</p>
<pre><code>while (my $line = <ARGV>) {
chop $line;
$line =~ s/#.*//;
next unless $line =~ /\S/;
@fields = (split ' ', $line)[0,1];
print join(' ', @fields), "\n";
}
</code></pre>
<p>Is there anything I missed? Hopefully not. The <code>ARGV</code> filehandle is special. It causes each named file on the command line to be read, unless none are specified, in which case it reads standard input.</p>
<p>Edit: Oh, I forgot. <code>split ' '</code> is magical too, unlike <code>split / /</code>. The latter just matches a space. The former matches any amount of any whitespace. This magical behaviour is used by default if no pattern is specified for <code>split</code>. (Some would say, <em>but what about <code>/\s+/</code></em>? <code>' '</code> and <code>/\s+/</code> are similar, except for how whitespace at the beginning of a line is treated. So <code>' '</code> really is magical.)</p>
<p>The moral of the story is, Perl is great if you like lots of magical behaviour. If you don't have a bar of it, use Python. :-P</p>
| 18,876
|
<p>Here's the problem:</p>
<pre><code>split=re.compile('\\W*')
</code></pre>
<p>This regular expression works fine when dealing with regular words, but there are occasions where I need the expression to include words like <code>k&amp;auml;ytt&amp;auml;j&aml;auml;</code>.</p>
<p>What should I add to the regex to include the <code>&</code> and <code>;</code> characters?</p>
|
<p>You probably want to take the problem reverse, i.e. finding all the character without the spaces:</p>
<pre><code>[^ \t\n]*
</code></pre>
<p>Or you want to add the extra characters:</p>
<pre><code>[a-zA-Z0-9&;]*
</code></pre>
<p>In case you want to match HTML entities, you should try something like:</p>
<pre><code>(\w+|&\w+;)*
</code></pre>
|
<p>Looks like this RegEx did the trick:</p>
<pre><code>split=re.compile('(\\\W+&\\\W+;)*')
</code></pre>
<p>Thanks for the suggestions. Most of them worked fine on Reggy, but I don't quite understand why they failed with <code>re.compile</code>.</p>
| 18,360
|
<p>In certain cases, I can't seem to get components to receive events.</p>
<p>[edit] </p>
<p>To clarify, the example code is just for demonstration sake, what I was really asking was if there was a central location that a listener could be added, to which one can reliably dispatch events to and from arbitrary objects.</p>
<p>I ended up using parentApplication to dispatch and receive the event I needed to handle.</p>
<p>[/edit]</p>
<p>If two components have differing parents, or as in the example below, one is a popup, it would seem the event never reaches the listener (See the method "popUp" for the dispatch that doesn't work):</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
initialize="init()">
<mx:Script>
<![CDATA[
import mx.controls.Menu;
import mx.managers.PopUpManager;
// Add listeners
public function init():void
{
this.addEventListener("child", handleChild);
this.addEventListener("stepchild", handleStepchild);
}
// Handle the no pop button event
public function noPop(event:Event):void
{
dispatchEvent(new Event("child"));
}
// Handle the pop up
public function popUp(event:Event):void
{
var menu:Menu = new Menu();
var btnMenu:Button = new Button();
btnMenu.label = "stepchild";
menu.addChild(btnMenu);
PopUpManager.addPopUp(menu, this);
// neither of these work...
this.callLater(btnMenu.dispatchEvent, [new Event("stepchild", true)]);
btnMenu.dispatchEvent(new Event("stepchild", true));
}
// Event handlers
public function handleChild(event:Event):void
{
trace("I handled child");
}
public function handleStepchild(event:Event):void {
trace("I handled stepchild");
}
]]>
</mx:Script>
<mx:VBox>
<mx:Button label="NoPop" id="btnNoPop" click="noPop(event)"/>
<mx:Button label="PopUp" id="btnPop" click="popUp(event)"/>
</mx:VBox>
</mx:Application>
</code></pre>
<p><strong>I can think of work-arounds, but it seems like there ought to be some central event bus...</strong> </p>
<p>Am I missing something?</p>
|
<p>Above is correct.
You are dispatching the event from btnMenu, but you are not listening for events on btnMenu - you are listening for events on the Application.</p>
<p>Either dispatch from Application:</p>
<pre><code>dispatchEvent(new Event("stepchild", true));
</code></pre>
<p>or listen on the btnMenu</p>
<pre><code>btnMenu.addEventListener("stepchild",handleStepChild);
btnMenu.dispatchEvent(new Event("stepchild",true));
</code></pre>
|
<p>You are attaching the listener to <code>this</code> when the event is getting dispatched from <code>btnMenu</code>.</p>
<p>This should work:</p>
<pre>
dispatchEvent(new Event("stepchild", true));
</pre>
<p>ps. There is really no reason to put an unnecessary '<code>this</code>' everywhere, unless it's explicitly required to overcome scope issues. In this case you can just leave every <code>this</code> out.</p>
| 15,875
|
<p>On my journey into the depths of custom ASP.NET control development I am obviously getting my head around the ASP.NET PostBack model and how it affects control development.</p>
<p>I understand that controls have no "lifetime" in ASP.NET, and therefore must be re-initialized on each and every page load. We overcome this by persisting the objects values/parameters to the ViewState.</p>
<p>Many articles I read therefore suggest not using PostBack since this can add considerable overhead to the Page. <strong>I am not looking for how to disable it, I know that.</strong> </p>
<p>What I am looking for is:</p>
<p><strong>What alternatives to we have to using the PostBack model to initialize controls?</strong></p>
<p>I know we <em>could</em> use the QueryString, but that seems awfully messy, and obviously unreliable.</p>
<p><strong>Ideally you could give me an overview of the architecture/design of a different approach and the pro's/con's of it..</strong></p>
<p>Many thanks ^_^</p>
|
<p>Well, Session State is a server-side solution, with its own pile of cruft to deal with if you want to avoid ViewState altogether. Really though, using ViewState in a custom control is all fine and good - just be picky about what you store - only store deltas from the declared control state, don't store anything you're going to get on postback anyway (e.g. from a DB call), etc.</p>
|
<p>I think you still mis-understand controls somewhat. Controls only have the problem you describe when you add them to the page dynamically. If you declare your controls upfront in the aspx code then they build along with the page.</p>
| 10,147
|
<p>I would like to parse a document using SAX, and create a subdocument from some of the elements, while processing others purely with SAX. So, given this document:</p>
<pre><code> <DOC>
<small>
<element />
</small>
<entries>
<!-- thousands here -->
</entries>
</DOC>
</code></pre>
<p>I would like to parse the DOC and DOC/entries elements using the SAX ContentHandler, but when I hit <code><small></code> I want to create a new document containing just the <code><small></code> and its children.</p>
<p>Is there an easy way to do this, or do I have to build the DOM myself, by hand?</p>
|
<p>One approach is to create a <code>ContentHandler</code> that watches for events that signal the entry or exit from a <code><small></code> element. This handler acts as a proxy, and in "normal" mode passes the SAX events straight through to the "real" <code>ContentHandler</code>. </p>
<p>However, when entry into a <code><small></code> element is detected, the proxy is responsible for the creation of a <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/transform/sax/SAXTransformerFactory.html#newTransformerHandler()" rel="nofollow noreferrer"><code>TransformerHandler</code></a> (with a no-op, "null" transform), <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/transform/sax/TransformerHandler.html#setResult(javax.xml.transform.Result)" rel="nofollow noreferrer">plumbed</a> up to a <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/transform/dom/DOMResult.html" rel="nofollow noreferrer"><code>DOMResult</code></a>. The <code>TransformerHandler</code> expects all the events that a complete, well-formed document would produce; you cannot immediately send it a <code>startElement</code> event. Instead, simulate the beginning of a new document by invoking <code>setDocumentLocator</code>, <code>startDocument</code>, and other necessary events on the <code>TransformerHandler</code> instance first. </p>
<p>Then, until the end of the <code><small></code> element element is detected by the proxy, all events are forwarded to this <code>TransformerHandler</code> instead of the "real" <code>ContentHandler</code>. When the closing <code></small></code> tag is encountered, the proxy simulates the end of a document by invoking <code>endDocument</code> on the <code>TransformerHandler</code>. A DOM is now available as the result of the <code>TransformerHandler</code>, which contains only the <code><small /></code> fragment.</p>
|
<p>I've had no problem building multiple simultaneous documents out of one SAX stream. It's pretty much SOP for any business-document-oriented stream. What difficulty are you having with doing that? The hierarchy of your classes needn't match the hierarchy of the SAX stream.</p>
| 47,441
|
<p>I am having a postgres production database in production (which contains a lot of Data). now I need to modify the model of the tg-app to add couple of new tables to the database. </p>
<p>How do i do this? I am using sqlAlchemy.</p>
|
<p>This always works and requires little thinking -- only patience.</p>
<ol>
<li><p>Make a backup.</p></li>
<li><p>Actually make a backup. Everyone skips step 1 thinking that they have a backup, but they can never find it or work with it. Don't trust any backup that you can't recover from.</p></li>
<li><p>Create a new database schema.</p></li>
<li><p>Define your new structure from the ground up in the new schema. Ideally, you'll run a DDL script that builds the new schema. Don't have a script to build the schema? Create one and put it under version control.</p>
<p>With SA, you can define your tables and it can build your schema for you. This is ideal, since you have your schema under version control in Python.</p></li>
<li><p>Move data.</p>
<p>a. For tables which did not change structure, move data from old schema to new schema using simple INSERT/SELECT statements.</p>
<p>b. For tables which did change structure, develop INSERT/SELECT scripts to move the data from old to new. Often, this can be a single SQL statement per new table. In some cases, it has to be a Python loop with two open connections.</p>
<p>c. For new tables, load the data.</p></li>
<li><p>Stop using the old schema. Start using the new schema. Find every program that used the old schema and fix the configuration. </p>
<p>Don't have a list of applications? Make one. Seriously -- it's important. </p>
<p>Applications have hard-coded DB configurations? Fix that, too, while you're at it. Either create a common config file, or use some common environment variable or something to (a) assure consistency and (b) centralize the notion of "production".</p></li>
</ol>
<p>You can do this kind of procedure any time you do major surgery. It never touches the old database except to extract the data.</p>
|
<p>If you are just adding tables, and not modifying any of the tables which have the existing data in it, you can simply add the new sqlAlchemy table definitions to model.py, and run:</p>
<pre><code>tg-admin sql create
</code></pre>
<p>This will not overwrite any of your existing tables.</p>
<p>For schema migration, you might take a look at <a href="http://code.google.com/p/sqlalchemy-migrate/" rel="nofollow noreferrer">http://code.google.com/p/sqlalchemy-migrate/</a> although I haven't used it yet myself.</p>
<p>Always take a backup of the production database before migration activity.</p>
| 38,701
|
<p>I have a string which contain tags in the form <code>< tag ></code>. Is there an easy way for me to programmatically replace instances of these tags with special ascii characters? e.g. replace a tag like <code>"< tab >"</code> with the ascii equivelent of <code>'/t'</code>?</p>
|
<pre><code>string s = "...<tab>...";
s = s.Replace("<tab>", "\t");
</code></pre>
|
<p>Regex patterns should do the trick.</p>
| 11,998
|
<p>I'd like to be able to open a TDataSet asynchronously in its own thread so that the main VCL thread can continue until that's done, and then have the main VCL thread read from that TDataSet afterwards. I've done some experimenting and have gotten into some very weird situations, so I'm wondering if anyone has done this before.</p>
<p>I've seen some sample apps where a TDataSet is created in a separate thread, it's opened and then data is read from it, but that's all done in the separate thread. I'm wondering if it's safe to read from the TDataSet from the main VCL thread after the other thread opens the data source.</p>
<p>I'm doing Win32 programming in Delphi 7, using TmySQLQuery from <a href="http://www.microolap.com/products/connectivity/mysqldac/" rel="noreferrer">DAC for MySQL</a> as my TDataSet descendant.</p>
|
<p>Provided you only want to use the dataset in its own thread, you can just use synchronize to communicate with the main thread for any VCL/UI update, like with any other component.<br>
Or, better, you can implement communication between the mainthread and worker threads with your own messaging system. </p>
<p>check Hallvard's solution for threading here:<br>
<a href="http://hallvards.blogspot.com/2008/03/tdm6-knitting-your-own-threads.html" rel="noreferrer">http://hallvards.blogspot.com/2008/03/tdm6-knitting-your-own-threads.html</a> </p>
<p>or this other one:<br>
<a href="http://dn.codegear.com/article/22411" rel="noreferrer">http://dn.codegear.com/article/22411</a> </p>
<p>for some explanation on synchronize and its inefficiencies:<br>
<a href="http://www.eonclash.com/Tutorials/Multithreading/MartinHarvey1.1/Ch3.html" rel="noreferrer">http://www.eonclash.com/Tutorials/Multithreading/MartinHarvey1.1/Ch3.html</a></p>
|
<p>Most TDatasets are not thread safe. One that I know is thread safe is <a href="http://www.components4programmers.com/products/kbmmemtable/index.htm" rel="nofollow noreferrer" title="kbmMemtable">kbmMemtable</a>. It also has the ability to clone a dataset so that the problem of moving the record pointer (as explained by Jim McKeeth) does occur. They're one of the best datasets you can get (bought or free).</p>
| 10,393
|
<p>I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.</p>
<p>Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?</p>
<p>system info:</p>
<ul>
<li>MySQL 5.0.19 </li>
<li>Client 5.1.11 </li>
<li>Windows XP</li>
<li>Python 2.4 / MySQLdb 1.2.1 p2</li>
</ul>
|
<p>Here's some pseudocode for how i do it in PHP:</p>
<p>Script 1:</p>
<pre><code>START TRANSACTION;
INSERT INTO table <anything you want>;
SLEEP(5);
UPDATE table SET field = 'foo';
COMMIT;
</code></pre>
<p>Script 2:</p>
<pre><code>START TRANSACTION;
UPDATE table SET field = 'foo';
SLEEP(5);
INSERT INTO table <anything you want>;
COMMIT;
</code></pre>
<p>Execute script 1 and then immediately execute script 2 in another terminal. You'll get a deadlock if the database table already has some data in it (In other words, it starts deadlocking after the second time you try this).</p>
<p>Note that if mysql won't honor the SLEEP() command, use Python's equivalent in the application itself.</p>
|
<p>you can always run LOCK TABLE tablename from another session (mysql CLI for instance). That might do the trick.</p>
<p>It will remain locked until you release it or disconnect the session.</p>
| 33,882
|
<ol>
<li>Is there a way to do this with SQL Server tools?</li>
<li>If not, is there a 3rd party tool that does this?</li>
</ol>
<p>There doesn't seem to be a good way to edit longer text columns in the SQL Server Managers for SQL Server 2000 or 2005. While SQL Server Manager is really not for editing data in your db, what other tool does Microsoft provide that would normally allow you to do this? Every other field is pretty easy to edit, except long text fields. In Access, you could hit shift-f2 and it would pop up a nice dialog to edit your text in.</p>
<p><a href="http://techinterview.org/edit.png" rel="nofollow noreferrer">alt text http://techinterview.org/edit.png</a></p>
|
<p>Generally, SQL Management Studio is an administrative tool for your database and not meant for data entry other than a quick edit here or there. Generally you would script the data or it would be entered by an application that uses the database for persistence.</p>
<p>(Although I have pointed Access to my SQL Server DB for a better quick and dirty UI.)</p>
|
<p>In the Management Console, isn't it possible to do an "Open Table" context-menu action and then edit the data from there?</p>
| 33,015
|
<p>We have a C++ library that we provide to several different clients. Recently we made the switch from using raw pointers in the public interface to using boost::sharedptr instead. This has provided an enormous benefit, as you might guess, in that now the clients no longer have to worry about who needs to delete what and when. When we made the switch I believed it was the right thing to do, but it bothered me that we had to include something from a third-party library in our public interface - generally you avoid that kind of thing if you can. I rationalized it that boost was practically part of the C++ language now, and our use case requires that both the client code and the library hold pointers to the objects. However recently one of our clients has asked us if we could switch to using a neutral smart pointer class in the interface, because our library is essentially forcing them to a particular version of boost- a point which I certainly understand and appreciate. So now I am wondering what the best course of action might be. I have thought about it a little bit, and wondered about creating a simple smart pointer class that simply held a real boost smart pointer. But then the clients would probably immediately stuff one of those into their flavor of boost::sharedptr, and then we'd be three shared pointers deep - which might be a problem, or it might not. Anyway, I'd love to hear some opinions from the community about the best way to solve this problem.</p>
<p>Edit: I originally said transfer of ownership, but I should have specified that code on both sides of the API boundary need to hold a pointer to the object.</p>
|
<p>shared_ptr<> <em>is</em> part of the language, as of the release of TR1.
See: <a href="http://msdn.microsoft.com/en-us/library/bb982729.aspx" rel="nofollow noreferrer">(TR1)</a></p>
|
<p>introducing boost::shared_ptr forces your client to use boost. to some people, this is a minor issue.</p>
<p>it also forces your clients to use the same compiler as used by your lib, if your lib is distributed as compiled binary. or, if your library is distributed in source code, the clients have to stick to their own choice of compiler used to compile your lib. this isn't a minor issue to any project of considerable size.</p>
| 43,489
|
<p>Here on Stack Overflow, you're a "user." On <a href="http://43things.com/" rel="nofollow noreferrer">43things.com</a> you're a "person." On other sites, you're an "account." And then some web apps skip the usage of this kind of signifier, and it's just <a href="http://webapp.com/yourusername" rel="nofollow noreferrer">http://webapp.com/yourusername</a></p>
<p>Do you think that these signifiers imply anything at all? Do you prefer one over the other? </p>
<p>In building an application, I often come to this step in the process and stumble on whether to call users of the application a "user" or a "person" or an "account." I'm sure there are other examples, but these are the ones I come across most often. I'm curious what others think when coming to building the user management functions of their applications. I think most default to using "user," but do you put any thought into why?</p>
|
<p><strong>Person</strong> implies that there is a 1:1 correspondence with a real human being. <strong>Account</strong> doesn't necessarily imply this (e.g. service accounts), and neither does <strong>User</strong>, strictly speaking. For example, here on SO there is a "Community" user who is obviously not a real person. It wouldn't make sense to call this the "Community person".</p>
|
<p>"Account" implies there could be several users for it. Using just / is appropriate if the user is the central part of your application, i. e. a social network like facebook. I'd use "user" for real users, people that can actually login etc. and "person" if you're just managing people, like a search engine for people.</p>
<p><strong>Edit:</strong> In the grand scale of the universe, it really doesn't matter.</p>
| 16,876
|
<ul>
<li>I make a user control and then want to include it on a page</li>
<li><p>I have to always manually type the @Register line at the top of my .aspx file, e.g.</p>
<p><%@ Register TagPrefix="edward" TagName="GetQuote" src="~/Controls/GetQuote.ascx" %>
<br/></p></li>
<li>Is there any way to automatically create these @Register lines? </li>
</ul>
<p>(I tried dragging in the .ascx file from the Solution Explorer, doesn't work.)</p>
<p><b>Problem solved</b>: I was dragging into my source view instead of design view. Thanks DilbertDave.</p>
|
<p>I don't get this issue - are you dragging to the aspx in source or design mode?</p>
<p>Dragging in Design mode creates the Register line for me.</p>
|
<p>try adding your control to the toolbox (via Tools > Choose Toolbox Items) and then dragging it onto your page from the toolbox? (your controls would need to be in a separate dll)</p>
| 41,434
|
<p>I am familiar with C++ RTTI, and find the concept interesting.</p>
<p>Still there exist a lot of more ways to abuse it than to use it correctly (the RTTI-switch dread comes to mind). As a developer, I found (and used) only two viable uses for it (more exactly, one and a half).</p>
<p><strong>Could you share some of the ways RTTI is a viable solution to a problem, with example code/pseudo-code included?</strong></p>
<p>Note: The aim is to have a repository of viable examples a junior developer can consult, criticize and learn from.</p>
<p><strong>Edit:</strong> You'll find below code using C++ RTTI</p>
<pre><code>// A has a virtual destructor (i.e. is polymorphic)
// B has a virtual destructor (i.e. is polymorphic)
// B does (or does not ... pick your poison) inherits from A
void doSomething(A * a)
{
// typeid()::name() returns the "name" of the object (not portable)
std::cout << "a is [" << typeid(*a).name() << "]"<< std::endl ;
// the dynamic_cast of a pointer to another will return NULL is
// the conversion is not possible
if(B * b = dynamic_cast<B *>(a))
{
std::cout << "a is b" << std::endl ;
}
else
{
std::cout << "a is NOT b" << std::endl ;
}
}
</code></pre>
|
<p><a href="http://www.objectmentor.com/resources/articles/acv.pdf" rel="nofollow noreferrer">Acyclic Visitor</a> (pdf) is a great use of it.</p>
|
<p>I used RTTI when doing some canvas-based work with Qt several years ago. It was darn convenient when doing hit-tests on objects to employ RTTI to determine what I was going to do with the shape I'd 'hit'. But I haven't used it otherwise in production code.</p>
| 29,490
|
<p>I have a Visual Studio (2008) solution consisting of several projects, not all in the same namespace. When I build the solution, all the DLL files used by the top level project, <strong>TopProject</strong>, are copied into the <em>TopProject\bin\debug</em> folder. However, the corresponding .pdb files are only copied for some of the other projects. This is a pain, for example when using <a href="http://www.ndepend.com/" rel="nofollow noreferrer">NDepend</a>.</p>
<p>How does Visual Studio decide which .pdb files to copy into higher level bin\debug folders? How can I get Visual Studio to copy the others too?</p>
<hr>
<p>References are as follows: all the DLL files are copied to a central location, without their PDB files. <strong>TopProject</strong> <em>only</em> has references to these copied DLL files; the DLL files themselves, however, evidently know where their PDB files are, and (most of them) get copied to the <code>debug</code> folder correctly.</p>
|
<p>From <a href="http://msdn.microsoft.com/en-us/library/yd4f8bd1(VS.71).aspx" rel="nofollow noreferrer">MSDN</a>:</p>
<blockquote>
<p>A program database (PDB) file holds
debugging and project state
information that allows incremental
linking of a Debug configuration of
your program. A PDB file is created
when you compile a C/C++ program with
/ZI or /Zi or a Visual
Basic/C#/JScript .NET program with
/debug.</p>
</blockquote>
<p>So it looks like the "issue" here (for lack of a better word) is that some of your DLLs are being built in debug mode (and hence emitting PDB files), and some are being built in release mode (hence not emitting PDB files). If that's the case, it should be easy to fix -- go into each project and update its build settings. This would be the default scenario, if you haven't done any tweaking of command line options.</p>
<p>However, it will get trickier if that isn't the case. Maybe you're all in release or debug mode. Now you need to look at the command line compile options (specified in the project properties) for each project. Update them to /debug accordingly if you want the debugger, or remove it if you don't.</p>
<p><strong>Edit in Response to Edit</strong></p>
<p>Yes, the DLL files "know" that they have PDB files, and have paths to them, but that doesn't mean too much. Copying just DLL files to a given directory, as others have mentioned, won't clear this issue up. You need the PDB files as well.</p>
<p>Copying individual files in Windows, with the exception of certain "bundle"-type files (I don't know Microsoft's term for this, but "complete HTML packages" are the concept) doesn't copy associated files. DLL files aren't assembled in the "bundle" way, so copying them leaves their PDB file behind.</p>
<p>I'd say the only answer you're going to have is to update your process for getting the DLL files to those central locations, and include the PDB files ... I'd love to be proven wrong on that, though!</p>
|
<p>First off, never assume anything. Clean the solution, rebuild it in debug mode, and check to see if all PDB files are created. If not, that's your problem.</p>
<p>If they are created, and they're not all getting copied, you can get around this by creating a post build event that manually copies the PDB files to the desired locations. This is just a workaround, of course.</p>
<p>The only other thing I can think of is that your solution file has become corrupt. You can open your .sln as an XML file and examine the contents. Check the configuration for the projects that are acting as expected and compare them to those that aren't. If you don't see anything, you have to repeat this at the project level. Compare working .csproj (or whatever) project files and the non-working ones.</p>
<hr>
<p><strong>Edit in response to edit</strong>:</p>
<p>If you're just manually copying stuff around, then manually copy the PDF files as well. DLL files shouldn't "know" anything about PDB files, I believe. Just stick them in the destination directory and go have a cup of coffee. Relax.</p>
| 16,087
|
<p>Is there a <a href="http://en.wikipedia.org/wiki/REPL" rel="noreferrer">REPL</a> (Read-Eval-Print Loop) available anywhere for Actionscript 3? I could not find anything on google, but it would really come in handy.</p>
|
<p><a href="http://eval.hurlant.com/demo/" rel="noreferrer">Google harder</a>. ;)</p>
|
<p>actionscript3 is a compiled language so is this even possible?</p>
| 41,180
|
<p>Acetone can be used to smooth ABS prints. What safety precautions should be taken during its use?</p>
|
<p>There are a few main safety precautions you should consider.</p>
<ul>
<li><strong><a href="http://sinkhacks.com/building-acetone-vapor-bath-smoothing-3d-printed-parts/" rel="nofollow">Make sure the area is well-ventilated.</a></strong> Acetone is flammable. A buildup of acetone gas could quickly get concentrated, meaning that a single spark could lead to disaster. Using a fan is good; angle it towards an open window. This is also to prevent exposure to acetone because of its toxicity.</li>
<li><strong><a href="http://www.sciencelab.com/msds.php?msdsId=9927062" rel="nofollow">Be prepared to fight a fire.</a></strong> Should vapor ignite, you may need to fight the fire. If it is large enough, then you should clearly evacuate the area. If it appears to be small, use dry chemical powder to snuff out the fire. Alcohol foam, water spray, and/or fog may be used on slightly larger fires. Acetone is not likely to cause a large inferno to rip through the building. But there's always the chance of a small fire. Be careful.</li>
<li><strong><a href="https://rivercitylabs.org/acetone-smoothing-chamber-3d-printing/" rel="nofollow">Create a vapor chamber.</a></strong> This is another way to stop a potential fire from spreading. It can also reduce contamination.</li>
<li><strong>Wear gloves.</strong> This can minimize any potential transfer toxic effects. However, skin exposure is unlikely to cause major issues.</li>
</ul>
<p>Acetone is toxic, as I mentioned before, but it is not highly toxic. Exposure via <a href="http://ccohs.ca/oshanswers/chemicals/chem_profiles/acetone.html" rel="nofollow">the eyes and nose/mouth</a> is the main risk. Skin effects may occur (e.g. mild irritation), but they are minor and generally arise only after long-term exposure (hence the recommendation of gloves in some cases).</p>
<p>Acetone exposure is only a serious problem when a person is repeatedly exposed to levels <a href="http://www.cdc.gov/niosh/idlh/67641.html" rel="nofollow">greater than 1,000 ppm</a> (severe effects only arise at much higher levels). It seems unlikely, given a proper ventilation system, that this will be an issue</p>
<p>In addition to all this, basic safety precautions such as wearing a ventilator mask and goggles should definitely be taken. When working with any such chemicals with the potential for bodily harm, these should absolutely be used.</p>
|
<p>You can smooth a print with acetone using different approaches which require different precautions. In general, you should have ventilated area and use gloves (or wash your hands after the procedure). </p>
<h2>Applying Acetone Directly</h2>
<p>Using the print in acetone for several seconds or you can apply acetone with a brush. There is a low possibility of fire. See this video, <a href="https://www.youtube.com/watch?v=r3nJbU9OInk" rel="nofollow noreferrer">(4) MakerBot Replicator - Model Finishing Tricks - Acetone Wash</a>. </p>
<h2>Cold Acetone Vapor</h2>
<p>This process takes several hours and gives you best control of the process. Because no external heat is used there is low chance of fire. See this video, <a href="https://www.youtube.com/watch?v=h2lm6FuaAWI" rel="nofollow noreferrer">Cold Acetone Vapor Finishing for 3D Printing</a>.</p>
<h2>Hot Acetone Vapor</h2>
<p>This approach takes minutes to smooth the print and there is high chance of ignition. I would never use it inside a building. See this video, <a href="https://www.youtube.com/watch?v=5sblh0bBHoQ" rel="nofollow noreferrer">Make your 3D Printed parts look professional with Acetone and a Rice cooker! - 2014</a>.</p>
| 105
|
<p>Might it make <strong><em>more</em></strong> sense to put 64-bit applications into "Program Files (x64)" and leave 32-bit applications to run in "Program Files"?</p>
<p>I have a batch file that need to run a <a href="http://en.wikipedia.org/wiki/Adobe_Flex" rel="nofollow noreferrer">Flex</a> compiler. In x64, that program is in "Program Files (x86)". On Windows Vista 32-bit, it's in "Program Files" - environment variables? Check it: </p>
<pre><code>ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
</code></pre>
<p>What do I do?</p>
<hr>
<pre><code>set mxmlc="%ProgramFiles(x86)%\Adobe\Flex Builder 3\sdks\3.1.0\bin\mxmlc.exe"
if NOT EXIST %mxmlc% set mxmlc="%ProgramFiles%\Adobe\Flex Builder 3\sdks\3.1.0\bin\mxmlc.exe"
</code></pre>
<p>tnx</p>
|
<p>That's nothing. Guess what <em>\Windows\System32</em> contains? That's right, 64-bit DLL files. So where did they decide to put 32-bit legacy DLL files? <em>\Windows\SysWOW64</em> of course.</p>
<p>The problem is, while there are built-in facilities for Windows applications to discover the location of system directories, many applications don't use them. And since Microsoft, above all else, is a slave to backwards compatibility we get stupid stuff like this.</p>
|
<p>Because Microsoft loves making things more complex for people. Rather than simplifying the transition to 64-bit, they made it divided and difficult.</p>
| 37,442
|
<p>I am looking to start writing apps for my Windows Mobile 6.1 professional device (Sprint Mogul/HTC Titan).</p>
<p>I use the copy of Visual Studio 2003 that I bought in college for all of my current contracting work, (all of my day job work is done on a company laptop). From what I can tell from MSDN in order to develop using windows Mobile 5 or 6 SDK I need to have at least Visual Studio 2005 Standard and I really don't feel like shelling out that much cash just to be able to develop for my phone.</p>
<p>Are there any free tools available to develop for Windows mobile? Or is there an affordable way to get VS that I am overlooking?</p>
|
<p>Even if you had Visual Studio 2005 you would be limited to the 2.0 Framework. You will need to use Visual Studio 2008 Professional or better to use the 3.5 Framework. But you also have an alternative. </p>
<p>I wrote an article on Windows Mobile Development without Visual Studio. The minimum you need is the .Net Compact Framework SDK. It comes with a command line compiler that can generate .Net assemblies that will run on a Windows Mobile phone. Naturally you will not want to use the command line for your compiling. So the instructions I wrote are centered around the (free) ShartpDevelop.Net editor. You can find the instructions on CodeProject.com. Here is the URL. </p>
<p><a href="http://www.codeproject.com/KB/mobile/WiMoSansVS.aspx" rel="noreferrer">http://www.codeproject.com/KB/mobile/WiMoSansVS.aspx</a></p>
|
<p>Can't you use Visual Studio Express Editions for Mobile Development</p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=94DE806B-E1A1-4282-ABC5-1F7347782553&displaylang=en" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?FamilyID=94DE806B-E1A1-4282-ABC5-1F7347782553&displaylang=en</a></p>
| 5,314
|
<p>I have a simple html page with a div. I am using jQuery to load the contents of an aspx app into the "content" div. Code looks like this:</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
</script>
<script type="text/javascript">
jQuery.noConflict();
</script>
</head>
<body>
<div id="content">
<div id="loading">
<div class="loading-indicator">Loading...</div>
</div>
</div>
</body>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#content").load("default.aspx");
});
</script>
</html>
</code></pre>
<p>The problem is default.aspx uses shadowbox and other javascript libraries. When that code tries to execute on default.aspx it acts like the js source files were not loaded. I check in firebug and the js files are there (no 404 or anything). Anyone know what I'm missing? As you can see I used the jQuery noConflict function because I thought the use of $ might be conflicting with the other libraries but no help there...</p>
|
<p>I have code doing this, it might be more verbose than is needed, but nested js files shouldn't be a problem.</p>
<pre><code>jQuery.get('default.aspx', null, function(data) {
$('#default').append(data);
}, 'html');
</code></pre>
|
<p>Seems like a common problem: <a href="http://andreineculau.wordpress.com/2006/09/29/ajax-ondemand-javascript-or-dynamic-script-tags/" rel="nofollow noreferrer">http://andreineculau.wordpress.com/2006/09/29/ajax-ondemand-javascript-or-dynamic-script-tags/</a></p>
<p>I'm guessing it's security built into browsers to prevent an ajax response from running arbitrary script.</p>
| 38,926
|
<p>What would be the most effective way to grab the schema + table name in this scenario:</p>
<p>SELECT [t0].[Id], [t0].[CODE] AS [arg0], [t0].[DESC] AS [arg1]
FROM [SchemaName].[TableName] AS [t0]
WHERE ([t0].[Id] <> @p0)</p>
<p>The outcome needs to be: "SchemaName.TableName" ....</p>
<p>I'm using C#.</p>
<p>Thanks!</p>
|
<p>I believe you should be able to do this (make sure to declare the local namespace):</p>
<pre><code><Window.Resources>
<local:MyDataStructure x:Key="mds1" />
</Window.Resources>
<ListBox ItemsSource="{Binding Data}" SelectedValue="{Binding Source={StaticResource mds1} Path=ChosenItem}"/>
</code></pre>
|
<p>Make this two properties inside a single class(Just to simplify the solution) and make the code ready for property changed events</p>
<pre><code> public class MyDataList : INotifyPropertyChanged
{
private Guid _choosen;
public ObservableCollection<Guid> Data { get; set; }
public Guid ChosenItem {
get
{
return _choosen;
}
set
{
_choosen = value;
PropertyChanged(this, new PropertyChangedEventArgs("ChosenItem"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
</code></pre>
<p>create an instance of this class and Bind to the DataContext of the ListBox
Now write the ListBox XAML code as bellow. SelectedValue binding is doing the trick here.</p>
<pre><code><ListBox ItemsSource="{Binding Data}" SelectedValue="{Binding Path=ChosenItem}" x:Name="listBox"/>
</code></pre>
| 46,254
|
<p>I have a pretty complicated Linq query that I can't seem to get into a LinqDataSsource for use in a GridView:</p>
<pre><code>IEnumerable<ticket> tikPart = (
from p in db.comments where
p.submitter == me.id &&
p.ticket.closed == DateTime.Parse("1/1/2001") &&
p.ticket.originating_group != me.sub_unit
select p.ticket
).Distinct();
</code></pre>
<p>How can I get this into a GridView? Thank you!</p>
|
<pre><code>gridview.DataSource = tikPart.ToList();
gridview.DataBind();
</code></pre>
|
<p>You can bind IQueryable<> type to GridView using LinqDataSource control. <a href="http://johnsobrepena.blogspot.com/2010/01/data-bind-coolgridview-to-iqueryable.html" rel="nofollow noreferrer">http://johnsobrepena.blogspot.com/2010/01/data-bind-coolgridview-to-iqueryable.html</a></p>
| 17,297
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.