instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I have mounted two radial fan on my printer as a part cooling solution.</p>
<p><a href="https://i.stack.imgur.com/MTeZ5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MTeZ5.png" alt="radial blower fan"></a></p>
<p>As you can see, the fan has input on the left side and blows air down. Does a mirror construction exists? With outlet on the right.</p>
<p>I can even print my own casing, but I'm not sure if the fan will work, if I change the rotation direction.</p>
<p>I'm using this print cooling fan duct: <a href="https://www.thingiverse.com/thing:1850163" rel="nofollow noreferrer">https://www.thingiverse.com/thing:1850163</a></p>
<p>The fan on the right side has the opening facing the hotend, and there is not much space, so the impeller can catch on wiring etc. If the right fan had opening to the right, there would be no such problem.</p>
|
<p>Yes these do exist, but I've never seen them in the size you are interested in, see e.g. these projector fans:</p>
<p><a href="https://i.stack.imgur.com/Jw36Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jw36Y.png" alt="enter image description here"></a></p>
<p>An alternative are fans that attract flow from both sides, like:</p>
<p><a href="https://i.stack.imgur.com/hryYg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hryYg.jpg" alt="enter image description here"></a></p>
<p>but I've not seen them in the small size you are interested in.</p>
<p>Considering the placement of the fans in the printed cooling duct you posted, I see no problem in using 2 similar fans. There is enough free space to suck in air and if you are afraid that the wires are caught by the impeller, you need to properly fasten the wires, ty wraps work wonderfully in securing cables. If I'm not mistaken, you could even use the holes in the fans to secure the cables or otherwise design and print a small bracket for attaching the ty wraps.</p>
|
<p>I did also some research on this and decided to go with this solution. This fan only measures 50x50x10mm and is easy flippable: <a href="https://de.aliexpress.com/item/1005001894771961.html" rel="nofollow noreferrer">https://de.aliexpress.com/item/1005001894771961.html</a></p>
<p><a href="https://i.stack.imgur.com/WYQaY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WYQaY.png" alt="enter image description here" /></a></p>
<p>Another option was this: <a href="https://de.aliexpress.com/item/4001185014078.html" rel="nofollow noreferrer">https://de.aliexpress.com/item/4001185014078.html</a></p>
<p><a href="https://i.stack.imgur.com/wHwkP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wHwkP.png" alt="enter image description here" /></a></p>
<p>Also found a Thingi, where people tried to flip the existing 5015 blower fans. It seems very difficult, since you have to print the fins in flipped direction and they tend to break.. <a href="https://www.thingiverse.com/thing:3716277" rel="nofollow noreferrer">https://www.thingiverse.com/thing:3716277</a></p>
<p><a href="https://i.stack.imgur.com/doFXv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/doFXv.jpg" alt="enter image description here" /></a></p>
| 1,478
|
<p>In looking at the use of C# in a ISV setting, I'm wondering what prominent C# based desktop apps are out there? I can think of only Paint .NET. </p>
<p>Is C# a good idea for an ISV, or should one stick to more native environments like Delphi or even QT?</p>
<p>Of course any experienced based advise or feedback would be appreciated.</p>
|
<p>Yes, C# can be used quite effectivly to build applications. In regards what applciations are out there, what are you looking for? Big apps, little apps?</p>
<p>I know of a big app that is built on the .NET framework (unsure if C# or VB) and that is Quickbooks.</p>
|
<p>I believe that MS use C# to build many of their apps both Windows and Web. At this time, C# is a great language to go with because of the flexibility of the language/framework.</p>
| 25,650
|
<p>How can I check in C# if button.Click event has any handlers associated?
If (button.Click != null) throws compile error.</p>
|
<p>You can't. Events just expose "add a handler" and "remove a handler" - that's all. (In fact in the CLR you can also have metadata to associate a method with "fire the event" but the C# compiler never generates that.) Some event publishers may offer additional means to check whether or not there are any subscribers (or indeed let you see those subscribers) but it's not part of the event pattern itself.</p>
<p>See <a href="http://pobox.com/~skeet/csharp/events.html" rel="nofollow noreferrer">my article about events</a> for more information, or look at the <a href="https://stackoverflow.com/questions/tagged/events">events</a> tag (which I'm about to add to this question).</p>
|
<p>I think you can if you are in the class that raises the event.</p>
<p>You can define the handler and enumerate each.</p>
<p>e.g. If your event is defined as </p>
<pre><code>event System.EventHandler NewEvent;
</code></pre>
<p>Then on the raise event method you might create you can do...</p>
<pre><code> EventHandler handler = NewEvent;
if(handler != null)
{
handler(this, e);
}
</code></pre>
<p>That will give you the handler and from that you can get the Invocation List.</p>
| 28,817
|
<p>How can I visually customize autocomplete fields in Wicket (change colors, fonts, etc.)?</p>
|
<p>You can use CSS to modify the look of this component. For the Ajax auto-complete component in 1.3 the element you want to override is div.wicket-aa, so for example you might do:</p>
<pre><code>div.wicket-aa {
background-color:white;
border:1px solid #CCCCCC;
color:black;
}
div.wicket-aa ul {
list-style-image:none;
list-style-position:outside;
list-style-type:none;
margin:0pt;
padding:5px;
}
div.wicket-aa ul li.selected {
background-color:#CCCCCC;
}
</code></pre>
|
<p>Perilandmishap has probably the most usefull answer for your needs. Personally, I always found the default Ajax auto complete control in Wicket to be woefully insufficient for my needs. If you really want a professional "feel" to your auto complete, roll your an using Wicket's Ajax libraries.</p>
| 9,548
|
<p>I've got a question concerning fields in databases which are measures that might be displayed in different units but are stored only in one, such as "height", for example.</p>
<p>Where should the "pattern unit" be stated?. Of course, in the documentation, etc... But we all know nobody reads the documentation and that self-documented things are preferable.</p>
<p>From a practical point of view, what do you think of coding it in the database field (such as height_cm for example)?.</p>
<p>I find this weird at a first look, but I find it practical to avoid any mistakes when different people deal with the database directly and the "pattern unit" will never change.</p>
<p>What do you think?</p>
|
<p>What's weird about height_cm? Looks good to me. </p>
<p>Sometimes you see measures and units in two separate fields, which is much more painful.</p>
<p>As long as you know the units aren't going to change, I think height_cm is a good way to deal with it.</p>
|
<p>I agree, nothing wrong with adding the unit to the field name.</p>
<p>The only thing I'd say is to make the naming convention consistent across your database - i.e. avoid situations where you have both <code>height_cm</code> and <code>mm_width</code> present in the same database!</p>
| 21,019
|
<p>I'm looking for a way of getting a <strong>concurrent collection</strong> in <strong>C#</strong> or at least a collection which supports a <strong>concurrent enumerator</strong>. Right now I'm getting an <code>InvalidOperationException</code> when the collection over which I'm iterating changes. </p>
<p>I could just deep copy the collection and work with a private copy but I'm wondering if there is perhaps a better way</p>
<p>Code snippet:</p>
<pre class="lang-cs prettyprint-override"><code>foreach (String s in (List<String>) callingForm.Invoke(callingForm.delegateGetKillStrings))
{
//do some jazz
}
</code></pre>
<p>--edit--</p>
<p>I took the answer but also found that I needed to ensure that the code which was writing to the collection needed to attempt to get a lock as well.</p>
<pre class="lang-cs prettyprint-override"><code>private void addKillString(String s)
{
lock (killStrings)
{
killStrings.Add(s);
}
}
</code></pre>
|
<p>Other than doing a deep-copy your best bet might be to lock the collection:</p>
<pre><code> List<string> theList = (List<String> )callingForm.Invoke(callingForm.delegateGetKillStrings);
lock(theList.SyncRoot) {
foreach(string s in theList) {
// Do some Jazz
}
}
</code></pre>
|
<p>If you want to use the FCL collections, then locking is the only way to support iteration / modification from multiple threads that may overlap.</p>
<p>Be careful what you use as your lock object, though. Using SyncRoot is only a good idea if the collection itself is a private member of the class that uses it. If the collection is protected or public, then a client of your class can take its own lock on your SyncRoot, potentially deadlocking with code in your class. </p>
<p>If you are interested in taking a look at a 3rd-party collection library, I recommend the excellent <a href="http://www.itu.dk/research/c5/" rel="nofollow noreferrer">C5 Generic Collection Library</a>. They have a family of tree-based collections that can easily and safely be modified and iterated at the same time without locking - see sections 8.10 and 9.11 of their (excellent) documentation for details.</p>
| 5,970
|
<p>(See related question: <a href="https://stackoverflow.com/questions/162917/how-do-i-report-an-error-midway-through-a-chunked-http-repsonse-without-closing">How do I report an error midway through a chunked http repsonse without closing the connection?</a>)</p>
<p>In my case, the #1 desire is for the browser to display an error message. No matter how uninformative.</p>
<p>Closing the ServletResponse outputStream obviously doesn't work. Neither does throwing an exception, even if I don't close first (tested on Tomcat 6.0.16). I think that what I want is either a RST packet, FIN in the middle of a chunk, or badly formed chunk headers.</p>
<p>After that I can worry about how various browsers respond.</p>
<p>Edited for clarification: This is for a file download, perhaps several gigabytes of binary data. I can't make certain that all of the data can be successfully read or decrypted before I have to start sending some of it.</p>
|
<p>My own answer, after research.</p>
<p>Part one: There seems to be no way to convince the application servers that I tested to put an error onto the wire past the "committed" phase. The following Servlet code results in legal HTTP Chunked Transfer headers on the socket. Interestingly, in the case of WebSphere an error message is appended to the end of the stream before the end mark.</p>
<pre><code>public class Servlet extends HttpServlet {
public static final int ARRAY_SIZE = 65536;
private static final int SEND_COUNT = 100000;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
String testData = "This is a fairly long piece of test text, running on and on and on, over and over.";
final ServletOutputStream outputStream = response.getOutputStream();
for (int i = 0; i < SEND_COUNT; ++i) {
outputStream.println(testData);
}
throw new ServletException("Break it now");
}
}
</code></pre>
<p>Part two: Even if the application server was willing to either write bogus data to the wire or close the socket without a closing zero length chunk, common clients do not report an error. IE7, FF3 and cURL do not report errors in chunk encoding. This makes HTTP downloads inherently unreliable, and is contrary to the spirit if not the letter of the HTTP 1.1 RFC.</p>
|
<p>I think you're going about it the wrong way. It seems like it would be simpler to not actually start sending the data until you're sure if will be a success or a failure. That way you can send an error message at the start if needed, instead of sending partial data that's not valid.</p>
<p>If you really must, you might be able to wrangle something up with JavaScript. When you get to the error, output something like this before closing the connection:</p>
<pre><code><script type="text/javascript"> alert("Processing failed!"); </script>
</code></pre>
<p>You might want to expand on the script, but you get the general idea. This is assuming that what's being sent back to the browser is a HTML page, you didn't specify that in the question.</p>
| 22,937
|
<p>What query can return the names of all the stored procedures in a SQL Server database</p>
<p>If the query could exclude system stored procedures, that would be even more helpful.</p>
|
<p>As Mike stated, the best way is to use <code>information_schema</code>. As long as you're not in the master database, system stored procedures won't be returned.</p>
<pre><code>SELECT *
FROM DatabaseName.INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'
</code></pre>
<p>If for some reason you had non-system stored procedures in the master database, you could use the query (this will filter out MOST system stored procedures):</p>
<pre><code>SELECT *
FROM [master].INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'
AND LEFT(ROUTINE_NAME, 3) NOT IN ('sp_', 'xp_', 'ms_')
</code></pre>
|
<p>This, list all things that you want</p>
<p>In Sql Server 2005, 2008, 2012 :</p>
<pre><code>Use [YourDataBase]
EXEC sp_tables @table_type = "'PROCEDURE'"
EXEC sp_tables @table_type = "'TABLE'"
EXEC sp_tables @table_type = "'VIEW'"
</code></pre>
<p>OR</p>
<pre><code>SELECT * FROM information_schema.tables
SELECT * FROM information_schema.VIEWS
</code></pre>
| 27,012
|
<p>I am tired of doing typical CRUD programming type applications. I would like to work on some interesting (not too hard) programming problems. Are there any sites out there to help me exercise my brain?</p>
|
<p>Project Euler: <a href="http://projecteuler.net/" rel="noreferrer">http://projecteuler.net/</a> is a nice collection of randomly interesting problems.</p>
<p>Somewhat related (not always programming, but generally interesting to programmers) is the IBM ponder this site: <a href="http://domino.research.ibm.com/Comm/wwwr_ponder.nsf/pages/index.html" rel="noreferrer">http://domino.research.ibm.com/Comm/wwwr_ponder.nsf/pages/index.html</a></p>
|
<p>Checkout for <a href="http://www.codechef.com/" rel="nofollow">CodeChef</a>
Interesting problems here any language vl do</p>
| 34,963
|
<p>I want to find a sql command or something that can do this where I have a table named tblFoo and I want to name it tblFooBar. However, I want the primary key to also be change, for example, currently it is:</p>
<pre><code>CONSTRAINT [PK_tblFoo] PRIMARY KEY CLUSTERED
</code></pre>
<p>And I want a name change to change it to:</p>
<pre><code>CONSTRAINT [PK_tblFooBar] PRIMARY KEY CLUSTERED
</code></pre>
<p>Then, recursively go through and cascade this change on all tables that have a foreigh key relationship, eg. from this:</p>
<pre><code>CHECK ADD CONSTRAINT [FK_tblContent_tblFoo] FOREIGN KEY([fooID])
</code></pre>
<p>To this:</p>
<pre><code> CHECK ADD CONSTRAINT [FK_tblContent_tblFooBar] FOREIGN KEY([fooID])
</code></pre>
<p>Naturally, I am trying not to go through and do this all manually because a) it is an error prone process, and b)it doesn't scale.</p>
|
<p>This is just off the top of my head and isn't complete (you'd need to add similar code for indexes). Also, you would need to either add code to avoid renaming objects from a table with the same base name, but additional characters - for example, this code would also list tblFoo2 and all of its associated objects. Hopefully it's a start for you though.</p>
<pre><code>DECLARE
@old_name VARCHAR(100),
@new_name VARCHAR(100)
SET @old_name = 'tblFoo'
SET @new_name = 'tblFooBar'
SELECT
'EXEC sp_rename ''' + name + ''', ''' + REPLACE(name, @old_name, @new_name) + ''''
FROM dbo.sysobjects
WHERE name LIKE '%' + @old_name + '%'
</code></pre>
|
<p>SQL Server won't do this directly as far as I am aware. You would have to manually build the script to do the change. This can be achieved by generating the SQL for the table definition (SSMS will do this) and doing a search and replace on the names.</p>
| 23,290
|
<p>Say for example I have the following string:</p>
<p>var testString = "Hello, world";</p>
<p>And I want to call the following methods:</p>
<p>var newString = testString.Replace("Hello", "").Replace("world", "");</p>
<p>Is there some code construct that simplifies this, so that I only have to specify the Replace method once, and can specify a bunch of parameters to pass to it in one go?</p>
|
<p>Create a function to which you pass the <code>String</code> and a <code>Dictionary(String, String)</code>. Iterate over each item in the Dictionary and <code>InputString.Replace(DictionaryEntry.Key, DictionaryEntry.Value)</code>. Return the string with the replaced values.</p>
<p>But I'd just do <code>.Replace.Replace</code> if it's only 2 times...</p>
|
<p>I don't know if this is any sweeter, but you can do:</p>
<pre><code>string inputString = "Hello, world";
string newString = new[] { "Hello", "world" }.Aggregate(inputString, (result, replace) => result.Replace(replace, ""));
</code></pre>
<p>This will start with the input string as the seed, and run thefunction with each of the replace strings.</p>
<p>A better example to understand the Aggregate function would perhaps be:</p>
<pre><code>List<Payment> payments = ...;
double newDebt = payments.Aggregate(oldDebt, (debt, payment) => debt - payment.Amount);
</code></pre>
| 42,060
|
<p>My printer ran out of black toner and I didn’t have a spare, so I thought it’d be a good idea to “print” documents to .XPS files for now, then print them when the new toner arrives.</p>
<p>So, now I have my toner but I can’t work out how to print the files. I found <a href="http://www.timbarcz.com/blog/HowToPrintXPSDocumentsEasyAs11a1aI233a45.aspx" rel="nofollow noreferrer">this great post on Tim Barcz’s blog</a> which seems to indicate I’m not alone.</p>
<p>I can open them and view them in IE, but if I try to print them it either ignores the command altogether or crashes.</p>
<p>I downloaded the XPS Essentials Pack from the Microsoft website and tried to install it, but it refuses to install and keeps crashing with a ten-page error message. Ironically, I would normally print this message out to deal with it.</p>
<p>My “solution” is to open the .XPS files in IE, then screenshot them and paste them into Paint Shop Pro so I can print them as graphics.</p>
<p>As Tim Barcz says in his post that I linked to:</p>
<blockquote>
<p>That’s it…simple. What I don’t get is why people are so afraid to embrace new technology?</p>
</blockquote>
|
<p>I have had no problems printing XPS docs from IE. The first thing that comes to mind is what OS are you running, what version of IE, are all service packs installed, etc?</p>
<p>Another option would be to copy the XPS files to a thumb drive (or send over the network) and print from another computer that does not have any issues.</p>
<p>Edit:</p>
<p>Follow up questions...Can you print non-XPS docs? Have you restarted the printer? Is your print spooler messed up?</p>
<p>I have had many instances where I could not print due to a bad print job clogging the spooler. Restart the spooler or restarting your PC usually takes care of this issue.</p>
|
<p>Windows XP SP3, IE6, all up to date AFAIK.</p>
<p>I use Firefox mostly, so haven't updated IE for ages. Maybe IE7 would be more successful.</p>
<p>The point was that XPS is meant to be some kind of PDF-killer, but the difference is that PDF just works, while XPS has been a disaster. I don't mind errors, but I want it to tell me what is wrong, not just say it didn't work, as I can see that from the lack of pages coming out of the printer.</p>
| 27,952
|
<p>I am desiging a new website for my company and I am trying to implement switch navigation which is what I have used on all my sites in the past.</p>
<pre><code><?php
switch($x) {
default:
include("inc/main.php");
break;
case "products":
include("inc/products.php");
break;
}
?>
</code></pre>
<p>For some reason when I go to index.php?x=products nothing happens, it still displays inc/main.php, in other words it hasn't detected the X variable from the URL. Is this something to do with global variables?</p>
|
<p>Yes, your PHP configuration has <strong>correctly</strong> got <code>register_globals</code> turned off, because that's incredibly insecure.</p>
<p>Just put:</p>
<pre><code>$x = $_REQUEST['x']
</code></pre>
<p>at the top of your script.</p>
<p>You can also use <code>$_GET</code> if you specifically only want this to work for the <code>GET</code> HTTP method. I've seen some people claim that <code>$_REQUEST</code> is somehow insecure, but no evidence to back that up.</p>
|
<p>You can use <a href="http://php.net/manual/es/function.extract.php" rel="nofollow">http://php.net/manual/es/function.extract.php</a> to extract the variables if you want to do it, but keep in mind this lets any user set variables with the content they want in your script, which makes it as insecure as using register_globals</p>
| 32,259
|
<p>How do I retrieve an item at random from the following list?</p>
<pre><code>foo = ['a', 'b', 'c', 'd', 'e']
</code></pre>
|
<p>Use <a href="https://docs.python.org/library/random.html#random.choice" rel="noreferrer"><code>random.choice()</code></a>:</p>
<pre><code>import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
</code></pre>
<p>For <a href="https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator" rel="noreferrer">cryptographically secure</a> random choices (e.g., for generating a passphrase from a wordlist), use <a href="https://docs.python.org/library/secrets.html#secrets.choice" rel="noreferrer"><code>secrets.choice()</code></a>:</p>
<pre><code>import secrets
foo = ['battery', 'correct', 'horse', 'staple']
print(secrets.choice(foo))
</code></pre>
<p><code>secrets</code> is new in Python 3.6. On older versions of Python you can use the <a href="https://docs.python.org/library/random.html#random.SystemRandom" rel="noreferrer"><code>random.SystemRandom</code></a> class:</p>
<pre><code>import random
secure_random = random.SystemRandom()
print(secure_random.choice(foo))
</code></pre>
|
<p>We can also do this using randint.</p>
<pre><code>from random import randint
l= ['a','b','c']
def get_rand_element(l):
if l:
return l[randint(0,len(l)-1)]
else:
return None
get_rand_element(l)
</code></pre>
| 39,410
|
<p>When I publish my ASP.NET site in RELEASE mode, and set compilation debug="false", will my ASP.NET and System.Diagnostics Tracing still work?</p>
|
<p>I believe that tracing is set separately from debugging in the configuration, so yes, if properly configured.</p>
<pre><code><configuration>
<system.web>
<trace enabled="true" requestLimit="40" localOnly="false"/>
</system.web>
</configuration>
</code></pre>
|
<p>Beware that tracing completely breaks any msajax stuff you have going on</p>
| 40,438
|
<p>Specifically I have a PHP command-line script that at a certain point requires input from the user. I would like to be able to execute an external editor (such as vi), and wait for the editor to finish execution before resuming the script.</p>
<p>My basic idea was to use a temporary file to do the editing in, and to retrieve the contents of the file afterwards. Something along the lines of:</p>
<pre><code>$filename = '/tmp/script_' . time() . '.tmp';
get_user_input ($filename);
$input = file_get_contents ($filename);
unlink ($filename);
</code></pre>
<p>I suspect that this isn't possible from a PHP command-line script, however I'm hoping that there's some sort of shell scripting trick that can be employed to achieve the same effect.</p>
<p>Suggestions for how this can be achieved in other scripting languages are also more than welcome.</p>
|
<p>You can redirect the editor's output to the terminal: </p>
<pre><code>system("vim > `tty`");
</code></pre>
|
<pre><code>system('vi');
</code></pre>
<p><a href="http://www.php.net/system" rel="nofollow noreferrer">http://www.php.net/system</a></p>
| 15,321
|
<p>Is it posible to use table view to show just one row of a big amount of elements? What I'm looking for is for some kind of horizontal list, like we have in XCode preferences or Aperture image list.</p>
<p>It would behave just like a one columnt table view, but instead of showing the elements vertically, it should be horizontally.</p>
<p>Can you point me to where should I start from?</p>
|
<p>If you're okay with Leopard-only, The new NSCollectionView supports horizontal display. Just set the collection view's number of rows to 1 in Interface Builder; it'll even handle the horizontal scroll bar for you. The <a href="http://developer.apple.com/samplecode/IconCollection/index.html" rel="noreferrer">IconCollection</a> sample code provides a simple demonstration of how it works. It's bindings work similarly to a table view's, except instead of rows and columns, each object represented gets an 'item' (an object of type NSCollectionViewItem) that displays it, and those items will be laid out in a grid. The sample code above demonstrates how to set up these 'items' in Interface Builder, which is definitely the easiest way.</p>
|
<p>With a table view? No. If I'm understanding correctly what you want, in the past I've created my own NSView subclass for this type of control. Define a data source protocol similar to NSTableView, and in your NSView drawRect method, draw the elements in order one by one from left to right. You can either keep track of paging in your control, or put it in a scroll view and resize yourself whenever the number of items changes.</p>
<p>Usually this type of thing starts off pretty simple, and gets a bit complex once you start handling caching, paging, selection, mouse and keyboard input and so on. My advice, start as simple as possible and add new features one by one, only after you've finished the previous task.</p>
| 48,932
|
<p>When is memory allocated in the .NET compact framework? If there is a difference between value and reference types, please detail. Documentation or steps to confirm are appreciated.</p>
<p>In particular, consider this scenario...</p>
<pre><code>private MyClass item; // here?
public void MyMethod()
{
item = new MyClass(); // or here?
}
</code></pre>
|
<p>There are 3 different ways memory is allocated.</p>
<p><strong>Static:</strong></p>
<p>These are bound and allocated at compile time. Global static variables for example.</p>
<p><strong>Stack Dynamic:</strong></p>
<p>These are bound during runtime and pushed onto the stack. Such as a local variable in a function call.</p>
<p><strong>Heap Dynamic:</strong></p>
<p>Now heap dynamic also has a few different 'sub categories' such as implicit and explicit, but I won't go into that detail. </p>
<p>When you declare</p>
<pre><code>private MyClass item; // here?
</code></pre>
<p>a reference to MyClass is pushed onto the stack. It is only a reference and nothing more. Its value is null at that point.</p>
<pre><code>public void MyMethod()
{
item = new MyClass(); // or here?
}
</code></pre>
<p>It is at that point where memory is explicitly allocated on the heap by calling 'new MyClass()' and item then references it.</p>
<p>So in actuality, you have 2 variables after you call MyMethod. A refernce type named item, and an unnamed variable on the heap which item references that is of type MyClass.</p>
|
<p>I highly recommend that you look at the MSDN Webcase on <a href="https://msevents.microsoft.com/cui/WebCastRegistrationConfirmation.aspx?culture=en-US&RegistrationID=1299365950&Validate=false" rel="nofollow noreferrer">Compact Framework Memory Management</a>. It's not exactly the same as how it works on the desktop, and this talk covers it with a whole lot of detail and graphics to aid in understanding the GC Heap.</p>
| 30,794
|
<p>People also often ask "How can I compile Perl?" while what they really want is to create an executable that can run on machines even if they don't have Perl installed.</p>
<p>There are several solutions, I know of:</p>
<ol>
<li><a href="http://www.indigostar.com/perl2exe.htm" rel="noreferrer">perl2exe</a> of IndigoStar
It is commercial. I never tried. Its web site says it can cross compile Win32, Linux, and Solaris.</li>
<li><a href="http://www.activestate.com/Products/perl_dev_kit/" rel="noreferrer">Perl Dev Kit</a> from ActiveState.
It is commercial. I used it several years ago on Windows and it worked well for my needs. According to its web site it works on Windows, Mac OS X, Linux, Solaris, AIX and HP-UX.</li>
<li><a href="http://search.cpan.org/dist/PAR/" rel="noreferrer">PAR</a> or rather <a href="http://search.cpan.org/dist/PAR-Packer/" rel="noreferrer">PAR::Packer</a> that is free and open source. Based on the test reports it works on the Windows, Mac OS X, Linux, NetBSD and Solaris but theoretically it should work on other UNIX systems as well.
Recently I have started to use PAR for packaging on Linux and will use it on Windows as well.</li>
</ol>
<p>Other recommended solutions?</p>
|
<p>In addition to the three tools listed in the question, there's another one called <a href="http://www.cavapackager.com/" rel="nofollow noreferrer">Cava Packager</a> written by Mark Dootson, who has also contributed to <a href="http://par.perl.org" rel="nofollow noreferrer">PAR</a> in the past. It only runs under Windows, has a nice Wx GUI and works differently from the typical three contenders in that it assembles all Perl dependencies in a source / lib directory instead of creating a single archive containing everything. There's a free version, but it's not Open Source. I haven't used this except for testing.</p>
<p>As for PAR, it's really a toolkit. It comes with a packaging tool which does the dependency scanning and assembly of stand-alone executables, but it can also be used to generate and use so-called .par files, in analogy to Java's JARs. It also comes with <a href="http://search.cpan.org/dist/PAR-Repository-Client" rel="nofollow noreferrer">client</a> and <a href="http://search.cpan.org/dist/PAR-Repository" rel="nofollow noreferrer">server</a> for automatically loading missing packages over the network, etc. The <a href="http://steffen-mueller.net/talks/appdeployment/" rel="nofollow noreferrer">slides of my PAR talk</a> at <a href="http://yapceurope.org/" rel="nofollow noreferrer">YAPC::EU</a> 2008 go into more details on this.
There's also an active mailing list: par at perl dot org.</p>
|
<p>You could use the <code>perlcc</code> tool that's shipped with most distributions of Perl. I've also found both <code>perl2exe</code> and Active State's Perl Dev kit useful for shipping Perl applications.</p>
| 10,284
|
<p>I have a set of base filenames, for each name 'f' there are exactly two files, 'f.in' and 'f.out'. I want to write a batch file (in Windows XP) which goes through all the filenames, for each one it should:</p>
<ul>
<li>Display the base name 'f'</li>
<li>Perform an action on 'f.in'</li>
<li>Perform another action on 'f.out'</li>
</ul>
<p>I don't have any way to list the set of base filenames, other than to search for *.in (or *.out) for example.</p>
|
<p>Assuming you have two programs that process the two files, process_in.exe and process_out.exe:</p>
<pre><code>for %%f in (*.in) do (
echo %%~nf
process_in "%%~nf.in"
process_out "%%~nf.out"
)
</code></pre>
<p>%%~nf is a substitution modifier, that expands %f to a file name only.
See other modifiers in <a href="https://technet.microsoft.com/en-us/library/bb490909.aspx" rel="noreferrer">https://technet.microsoft.com/en-us/library/bb490909.aspx</a> (midway down the page) or just in the next answer.</p>
|
<p>Echoing f.in and f.out will seperate the concept of what to loop and what not to loop when used in a for /f loop.</p>
<pre><code>::Get the files seperated
echo f.in>files_to_pass_through.txt
echo f.out>>files_to_pass_through.txt
for /F %%a in (files_to_pass_through.txt) do (
for /R %%b in (*.*) do (
if "%%a" NEQ "%%b" (
echo %%b>>dont_pass_through_these.txt
)
)
)
::I'm assuming the base name is the whole string "f".
::If I'm right then all the files begin with "f".
::So all you have to do is display "f". right?
::But that would be too easy.
::Let's do this the right way.
for /f %%C in (dont_pass_through_these.txt)
::displays the filename and not the extention
echo %~nC
)
</code></pre>
<p>Although you didn't ask, a good way to pass commands into f.in and f.out would be to...</p>
<pre><code>for /F %%D "tokens=*" in (dont_pass_through_these.txt) do (
for /F %%E in (%%D) do (
start /wait %%E
)
)
</code></pre>
<p>A link to all the Windows XP commands:<a href="https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds.mspx?mfr=true" rel="nofollow noreferrer">link</a></p>
<p>I apologize if I did not answer this correctly. The question was very hard for me to read.</p>
| 6,071
|
<p>The assembly it's trying to find isn't the root assembly - it's a referenced one, but it's in the same folder, and Directory.GetCurrentDirectory() is the folder with all of the files in.</p>
<p>I'm stuck - any suggestions?</p>
|
<p>You can either:</p>
<ol>
<li>Create a new <code>AppDomain</code> to load the assembly (and set the <code>AppDomain</code>'s base directory to the directory containing all the assemblies).</li>
<li>Attach a handler for <code>AppDomain.AssemblyResolve</code> to help the CLR find the assembly's dependencies.</li>
<li>You might be able to add the directory in question to the list of paths to probe. However, it will need to reside somewhere under your application's directory. See the <a href="http://msdn.microsoft.com/en-us/library/823z9h8w.aspx" rel="nofollow noreferrer">probe</a> element for more info.</li>
</ol>
|
<p>You could try using something like this</p>
<pre><code>string myDll = string.Empty;
string location = Assembly.GetExecutingAssembly().Location;
if (location != null)
{
myDll = string.Format(@"{0}\my.assembly.name.dll", location.Substring(0, location.LastIndexOf(@"\")));
}
</code></pre>
<p>This should get physical directory in which the assemblies are running. This could be in the Windows .NET temporary directories. However, because the files are at the same level they should exist there side by side.</p>
| 36,934
|
<p>In short, I'd like to learn/develop an elegant method to save a binary tree to disk (a general tree, not necessarily a BST). Here is the description of my problem:</p>
<p>I'm implementing a game of "20-questions". I've written a binary tree whose internal nodes are questions and leaves are answers. The left child of a node is the path you'd follow if somebody answered "yes" to your current question, while the right child is a "no" answer. Note this is not a binary <em>search</em> tree, just a binary tree whose left child is "yes" and right is "no".</p>
<p>The program adds a node to a tree if it encounters a leaf that is null by asking the user to distinguish her answer from the one the computer was thinking of.</p>
<p>This is neat, because the tree builds itself up as the user plays. What's not neat is that I don't have a good way of saving the tree to disk.</p>
<p>I've thought about saving the tree as an array representation (for node i, left child is 2i+1, and 2i+2 right, (i-1)/2 for parent), but it's not clean and I end up with a lot of wasted space.</p>
<p>Any ideas for an elegant solution to saving a sparse binary tree to disk?</p>
|
<p>You can store it recursively:</p>
<pre><code> void encodeState(OutputStream out,Node n) {
if(n==null) {
out.write("[null]");
} else {
out.write("{");
out.write(n.nodeDetails());
encodeState(out, n.yesNode());
encodeState(out, n.noNode());
out.write("}");
}
}
</code></pre>
<p>Devise your own less texty output format. I'm sure I don't need to describe the method to read the resulting output.</p>
<p>This is depth-first traversal. Breadth-first works too.</p>
|
<p>I would store the tree like this:</p>
<pre><code><node identifier>
node data
[<yes child identfier>
yes child]
[<no child identifier>
no child]
<end of node identifier>
</code></pre>
<p>where the child nodes are just recursive instances of the above. The bits in [] are optional and the four identifiers are just constants/enum values.</p>
| 43,851
|
<p>I'd much rather code an app using pure C api such as OpenGL, rather that Cocoa Touch. So I'm wondering: is it feasible? Will I be able to maintain the same user experience that you get with Interface Builder?</p>
|
<p>None of the UI components have OpenGL equivalents. Is it possible? Yes. Is it <em>sensible</em>? No - you would be much better off learning how to use IB and the UIView classes. Coding the UI in OpenGL would be like painting your house with an artist's brush, using hand-made paint instead of Dulux.</p>
|
<p>Depends on your app. Mine's an "immersive" game, so I'm using openGL
instead of CocoaTouch,<br>
with a sprinkling of Core Graphics/UIKit calls to generate nice textures.</p>
<p>If I had to display any kind of standard, non-trivial widget, I'd use CocoaTouch.</p>
| 34,255
|
<p>I would like to match the time (10.00) from a string with the date and time ("21.01.08 10.00"). I'm using the following regular expression:</p>
<pre><code>new RegExp("\\b[0-9]{1,2}\\.[0-9]{1,2}\\b" "g");
</code></pre>
<p>But this matches 21.01 from 21.01.08 and 10.00.</p>
<p>I'm using PCRE as my regualar expression engine. </p>
<p>Update:</p>
<p>I'm sorry, i should have more been more clear. The data and time are part of a larger string. I want to extract the time from that string.</p>
<p>For example:</p>
<p>"On 21.01.08 from 10.00 a party will take place in the library"
"21.08.08 - At 10:00 there will be a party"
"On 21.08.08 you are scheduled for a ... . The ... will begin at 10.00"</p>
<p>Is this possible?</p>
|
<p>Your original regex didn't work because <code>\b</code> (word boundary) matches at the "." in "21.01.08." You need to code the boundaries more robustly:</p>
<pre><code>(?:[^\d:.]|^)(\d\d?[.:]\d\d)(?![.:\d])
</code></pre>
<p>This captures the time, in either of the notations you used, while excluding dates. Note that it does not validate the time. For example, it would match "88:99" Validating the time is possible but complicates the pattern significantly and is likely to be overkill for most situations.</p>
<p>It would be nice to use a look-behind instead of the non-capturing grouping but PCRE don't support variable-width look-behind.</p>
|
<p>try using </p>
<pre><code>new RegExp("\\b[0-9]{1,2}\\.[0-9]{1,2}$" "g");
</code></pre>
<p>$ indicates end of string</p>
| 25,666
|
<p>I'm trying to use Live Search 2.0 but even a simple example doesn't seem to work. Microsoft only has example code for 1.1 and they're not giving out AppIDs for that version.</p>
<p>Here's what I'm trying with:</p>
<pre><code><?php
$server = new SoapClient('http://soap.search.msn.com/webservices.asmx?wsdl');
class Search {
public $Request;
}
class SearchRequest {
public $AppID;
public $Query;
public $CultureInfo;
public $SafeSearch;
public $Flags;
public $Location;
public $Requests;
}
class SourceRequest {
public $Source;
public $Offset;
public $Count;
public $FileType;
public $SortBy;
public $ResultFields;
public $SearchTagFilters;
}
$searchRequest = new SourceRequest();
$searchRequest->Source = 'Web';
$searchRequest->Offset = 0;
$searchRequest->Count = 5;
$searchRequest->ResultFields = 'All SearchTagsArray';
$request = new SearchRequest();
$request->AppID = '...';
$request->Query = 'Bill Gates';
$request->CultureInfo = 'en-US';
$request->SafeSearch = 'Off';
$request->Flags = '';
$request->Requests = array($searchRequest);
$search = new Search();
$search->Request = $request;
$server->Search($search);
?>
</code></pre>
<p>AppID is correctly specified in the code: I just erased it from here. I'm getting the following error:</p>
<pre><code>Array ( [0] => SearchResponse Search(Search $parameters) )
Fatal error: Uncaught SoapFault exception: [soapenv:Client] Client Error in /Users/thardas/Sites/vt9/widgets/ms_livesearch.php:41
Stack trace:
#0 [internal function]: SoapClient->__call('Search', Array)
#1 /Users/thardas/Sites/vt9/widgets/ms_livesearch.php(41): SoapClient->Search(Object(SearchRequest))
#2 /Users/thardas/Sites/vt9/index.php(23): include('/Users/thardas/...')
#3 {main} thrown in /Users/thardas/Sites/vt9/widgets/ms_livesearch.php on line 41
</code></pre>
|
<p>You could begin by using the proper soap api url for 2.0.
It's now
"<a href="http://api.search.live.net/search.wsdl?AppID=YourAppId" rel="nofollow noreferrer">http://api.search.live.net/search.wsdl?AppID=YourAppId</a>" taken from (<a href="http://msdn.microsoft.com/en-us/library/dd250965.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/dd250965.aspx</a> )</p>
<p>You can also use the new JSON api with php.</p>
<pre><code>$appid = 'Your app id';
$searchitem = 'PHP Manual';
$request = 'http://api.search.live.net/json.aspx?Appid=' . $appid . '&sources=web&query=' . urlencode( $searchitem);
$response = file_get_contents($request);
$jsonobj = json_decode($response);
foreach($jsonobj->SearchResponse->Web->Results as $value)
{
//$value->Url
//$value->Title
//$value->Description
}
</code></pre>
<p>And finally theres a xml api you can look up at the msdn link as well and it can be fetched essentially the same way as the json you just need to decode it differently.</p>
|
<p>The sample code for API 2.0 is on MSDN but we do not have the complete PHP code sample out yet.
A first code sample (very similar to the one in the answer you already got) in included in the blog post <a href="http://dev.live.com/blogs/livesearch/archive/2009/01/05/444.aspx" rel="nofollow noreferrer">on the Live Search Developer Blog</a></p>
<p>You may be aware that there are currently some <a href="http://bugs.php.net/bug.php?id=43069" rel="nofollow noreferrer">issues with SOAP</a> in PHP 5.2.6 - the Live Search service seems to be affected by it in both 1.1 and 2.0. The simplest workaround is to use another interface (JSON or XML)</p>
| 49,055
|
<p>My rails app is in a svn repository, but several of the plugins are installed through git and later added to the svn repo. How can I update these plugins? I can't seem to get script/plugin update to do anything. I'd really like to update activemerchant to get rid of the Inflector warnings.</p>
|
<p>If you haven't made any local changes to the plugin and you don't need to track what changes to it the update will bring, you can just run <code>script/plugin install</code> again, passing in <code>--force</code> if you need to. For example:</p>
<pre><code>script/plugin install --force git://github.com/dchelimsky/rspec.git
</code></pre>
|
<p>You should just be able to navigate to the plugin's directory and hit:
<code>
git pull
</code>. I'm pretty sure that <code>script/install plugin</code> just checks the code out from the git repo.</p>
| 24,259
|
<p>What is the most efficient way to detect duplicates in a 10 column / 50K row table? I'm using MSSQL 8.0</p>
|
<p>To show an example of what others have been describing:</p>
<pre><code>SELECT
Col1, -- All of the columns you want to dedupe on
Col2, -- which is not neccesarily all of the columns
Col3, -- in the table
Col4,
Col5,
Col6,
Col7,
Col8,
Col9,
Col10
FROM
MyTable
GROUP BY
Col1,
Col2,
Col3,
Col4,
Col5,
Col6,
Col7,
Col8,
Col9,
Col10
HAVING
COUNT(*) > 1
</code></pre>
|
<p>To detect, just group by as Guge said.</p>
<pre><code>select fieldA, fieldB, count(*) from table
group by fieldA, fieldB
having count(*) > 1
</code></pre>
<p>If you want to delete dupes... pseudo.... </p>
<pre><code>select distinct into a temp table
truncate original table
select temp table back into original table
</code></pre>
<p>With truncate you may run into problems if you have FK constraints, so be smart about dropping constraints and making sure you don't orphan records.</p>
| 39,461
|
<p>I need to scale calls into Tomcat and it's been suggested to launch threads internally. Has anyone needed to do this and, if so, what solutions did they come up with?</p>
|
<p>Creating your own threads inside an application server is generally discouraged because the server should manage threads for better scalability. You can also run into problems if the container makes assumptions about what's available in a thread context, such as security information (e.g., authenticated Subject). That typically happens if you spawn a thread and then use a server resource from that thread which is unknown to the container.</p>
<p>Check to see if there is a way to get container managed threads from Tomcat. WebLogic and WebSphere support the commonj.WorkManager, which allows you to schedule work on container managed threads. Spring can also use commonj, but I'm not sure if that support is available on Tomcat.</p>
|
<p>as others asked, you should give more details as to what you're trying to accomplish.</p>
<p>Otherwise, tomcat uses thread pools. increase the number of threads in the pool. Use a newer version of tomcat -- 6.x. Use Java 6.0_10. If needed, tune the application using a profiler and fiddle with the JVM settings, if required.</p>
| 26,072
|
<p>Is there a way to start another application from within Compact .Net framework 1.0 similar to </p>
<pre><code>System.Diagnostics.Process.Start
</code></pre>
<p>on the Windows side?</p>
<p>I need to start a CAB file for installation.</p>
|
<p>Treat the share as if it were your source control system. Make the share read-only, which will force developers to get local copies in order to make changes. You then have a somewhat stable version to compare against. This would help facilitate being able to do "merges". "Checking" code in would have to consist of some sort of backup strategy for the file (possibly making a copy of the file with a timestamp and username as part of the new file name) and replacing the original with the new version.</p>
<p>That being said, doing this type of activity without a real source control system that is reliable is going to be difficult and error-prone.</p>
|
<p>Working off of a shared drive is not a good idea, and gets my vote of "no confidence".</p>
<p>It would be too easy to overwrite other's changes, you have no change tracking, no way to branch or tag/label, etc.</p>
| 24,707
|
<p>I use Visual Studio 2008. I haven't seen this behavior before and, as far as I know, I didn't change anything in the options.</p>
<p>When I press Start debugging all the possibly windows (watch 1 - 4), data sources, properties, registers (to be honest I have not even ever seen these windows before) appear in front of the code window and stay there after I stop the debugger.</p>
<p>Anyone has an idea what could be causing this ? (I am using CodeRush and Refactor for quite a while now)</p>
<p>When I close and restart visual studio all the windows are where they should be.</p>
<p>PS: Previously I have seen normal switching from normal to debug mode and back with some repositioning changes. That is the way it used to work. Now it is not. It has suddenly gone mad and when going to the debug mode it sometimes shows all possible IDE windows and sometimes not. When it does it no longer returns to the previous state. I cannot find this in the options anywhere.</p>
|
<p>Visual Studio <em>remembers</em> 2 sets of window layouts, normal mode and debugging mode. My solution is to arrange my normal windows exactly like I want them, then start debugging an application and once again arrange all of the windows the way I want, usually making it as similar to my <em>normal</em> layout as possible, then stopping the debugger and doing a File Exit so that VS saves my settings.</p>
<p>After doing that, it recalls my 2 different layouts each time.</p>
|
<p>I'm experiencing the same thing - whenever the debugger is running, switching focus back to the IDE immediately caused the debug panel to expand.</p>
<p>I ended up just pinning the debug panel so that it always appears when debugging, and just changing its height as needed.</p>
| 8,153
|
<p>Is there a simple way to sort an iterator in PHP (without just pulling it all into an array and sorting that).</p>
<p>The specific example I have is a <a href="http://www.php.net/directoryiterator" rel="noreferrer">DirectoryIterator</a> but it would be nice to have a solution general to any iterator.</p>
<pre><code>$dir = new DirectoryIterator('.');
foreach ($dir as $file)
echo $file->getFilename();
</code></pre>
<p>I'd like to be able to sort these by various criteria (filename, size, etc)</p>
|
<p>There is no way to do that. An iterator should "iterate" through the list. You have to sort the underlying list to achieve the needed behavior.</p>
<p>By the way, the more complete reference to the SPL is here:
<a href="http://www.php.net/~helly/php/ext/spl/" rel="noreferrer">http://www.php.net/~helly/php/ext/spl/</a></p>
|
<p>You'll have to reduce using iterator_to_array() then uasort(). And, in my performance testing, sufficiently fast.</p>
<p>To your specific example, the most compact way I know using iterators is below:</p>
<pre><code>// get (recursively) files matching a pattern, each file as SplFileInfo object
$matches = new RegexIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/files/')
),
'/(\.php|\.ini|\.xml)$/i'
);
$files = iterator_to_array($matches);
// sort them by name
uasort($files, create_function('$a,$b', 'return strnatcasecmp($a->getFilename(), $b->getFilename());'));
</code></pre>
| 31,284
|
<p>I'm looking for some examples or samples of routing for the following sort of scenario:</p>
<p>The general example of doing things is: {controller}/{action}/{id}</p>
<p>So in the scenario of doing a product search for a store you'd have:</p>
<pre><code>public class ProductsController: Controller
{
public ActionResult Search(string id) // id being the search string
{ ... }
}
</code></pre>
<p>Say you had a few stores to do this and you wanted that consistently, is there any way to then have: {category}/{controller}/{action}/{id}</p>
<p>So that you could have a particular search for a particular store, but use a different search method for a different store?</p>
<p>(If you required the store name to be a higher priority than the function itself in the url)</p>
<p>Or would it come down to:</p>
<pre><code>public class ProductsController: Controller
{
public ActionResult Search(int category, string id) // id being the search string
{
if(category == 1) return Category1Search();
if(category == 2) return Category2Search();
...
}
}
</code></pre>
<p>It may not be a great example, but basically the idea is to use the same controller name and therefore have a simple URL across a few different scenarios, or are you kind of stuck with requiring unique controller names, and no way to put them in slightly different namespaces/directories?</p>
<p>Edit to add:</p>
<p>The other reason I want this is because I might want a url that has the categories, and that certain controllers will only work under certain categories.</p>
<p>IE:</p>
<p>/this/search/items/search+term <-- works</p>
<p>/that/search/items/search+term <-- won't work - because the search controller isn't allowed.</p>
|
<p>I actually found it not even by searching, but by scanning through the ASP .NET forums in <a href="http://forums.asp.net/t/1296928.aspx?PageIndex=1" rel="nofollow noreferrer">this question</a>.</p>
<p>Using this you can have the controllers of the same name under any part of the namespace, so long as you qualify which routes belong to which namespaces (you can have multiple namespaces per routes if you need be!)</p>
<p>But from here, you can put in a directory under your controller, so if your controller was "MyWebShop.Controllers", you'd put a directory of "Shop1" and the namespace would be "MyWebShop.Controllers.Shop1"</p>
<p>Then this works:</p>
<pre><code> public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
var shop1namespace = new RouteValueDictionary();
shop1namespace.Add("namespaces", new HashSet<string>(new string[]
{
"MyWebShop.Controllers.Shop1"
}));
routes.Add("Shop1", new Route("Shop1/{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
action = "Index",
id = (string)null
}),
DataTokens = shop1namespace
});
var shop2namespace = new RouteValueDictionary();
shop2namespace.Add("namespaces", new HashSet<string>(new string[]
{
"MyWebShop.Controllers.Shop2"
}));
routes.Add("Shop2", new Route("Shop2/{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new
{
action = "Index",
id = (string)null
}),
DataTokens = shop2namespace
});
var defaultnamespace = new RouteValueDictionary();
defaultnamespace.Add("namespaces", new HashSet<string>(new string[]
{
"MyWebShop.Controllers"
}));
routes.Add("Default", new Route("{controller}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }),
DataTokens = defaultnamespace
});
}
</code></pre>
<p>The only other thing is that it will reference a view still in the base directory, so if you put the view into directories to match, you will have to put the view name in when you return it inside the controller.</p>
|
<p>The best way to do this without any compromises would be to implement your own ControllerFactory by inheriting off of IControllerFactory. The CreateController method that you will implement handles creating the controller instance to handle the request by the RouteHandler and the ControllerActionInvoker. The convention is to use the name of the controller, when creating it, therefore you will need to override this functionality. This will be where you put your custom logic for creating the controller based on the route since you will have multiple controllers with the same name, but in different folders. Then you will need to register your custom controller factory in the application startup, just like your routes.</p>
<p>Another area you will need to take into consideration is finding your views when creating the controller. If you plan on using the same view for all of them, then you shouldn't have to do anything different than the convention being used. If you plan on organizing your views also, then you will need to create your own ViewLocator also and assign it to the controller when creating it in your controller factory.</p>
<p>To get an idea of code, there are a few questions I have answered on SO that relate to this question, but this one is different to some degree, because the controller names will be the same. I included links for reference.</p>
<ul>
<li><a href="https://stackoverflow.com/questions/19746/views-in-seperate-assemblies-in-aspnet-mvc">Views in separate assemblies in ASP.NET MVC</a></li>
<li><a href="https://stackoverflow.com/questions/26715/aspnet-mvc-subfolders">asp.net mvc - subfolders</a></li>
</ul>
<p>Another route, but may require some compromises will be to use the new AcceptVerbs attribute. Check this <a href="https://stackoverflow.com/questions/36197/aspnet-mvc-structuring-controllers">question</a> out for more details. I haven't played with this new functionality yet, but it could be another route.</p>
| 6,479
|
<p>We altready have a similar question <a href="https://stackoverflow.com/questions/88950/is-there-any-reason-to-not-ship-the-pdbs-with-your-application">here</a> but the discussion do not cover all the aspect, so I'm asking again:</p>
<p><em>What is the best way to distribute a .Net application considering build mode (release vs. debug) and distribution of PDB files?</em> Having a good reference to an article covering these aspects would be great.</p>
<p>Consider also the distribution of web application vs. the distribution of windows form applications.</p>
<p>Thanks in advance</p>
<p>Massimo</p>
|
<p>Debug builds should not be distributed, they're really for your own private viewing. However, once you build a release build with symbols and generate .pdbs from them, you can keep the pdbs and happily ship the dlls.</p>
<p>If you store the .pdbs in a symbol server (see this excellent <a href="http://msdn.microsoft.com/en-gb/magazine/cc301459.aspx" rel="nofollow noreferrer">bugslayer article</a>) then you do not need to worry about which symbols match which version of the dll as the debugger handles that for you.</p>
<p>If your app crashes, get DrWatson to generate a minidump (run DrWtsn32.exe check the minidump checkbox), get that dump sent to you, and then load it up in windbg. It'll show you the exception, stack trace, variables, registers, threads, the lot (well, not the lot, for that you need a full crashdump but they are reasonably large, minidumps have all useful information at a fraction of the size).</p>
|
<p>Debug builds should not be distributed - you likely do not have the rights to do so. PDBs are most easily distribute using a Symbol Server.</p>
| 27,871
|
<p>Is it possible to enumerate all the current errors being displayed through an "Error Provider" without having to access the controls?</p>
|
<p>There is a summary validator that will give you all of the errors, but it's pretty ugly, and I'm not sure if you can use it without displaying it on the page. Technically, if you are doing things the "right way", all of you error handling should be handled in your midddle teir and then bubbled to the screen that way, so you already have access to all the errors in a collection or dictionary.</p>
|
<p>There is a summary validator that will give you all of the errors, but it's pretty ugly, and I'm not sure if you can use it without displaying it on the page. Technically, if you are doing things the "right way", all of you error handling should be handled in your midddle teir and then bubbled to the screen that way, so you already have access to all the errors in a collection or dictionary.</p>
| 18,925
|
<p>Large pages are available in <code>Windows Server 2003</code> and <code>Windows Vista</code>. </p>
<p>But how do I enable large pages for my application? </p>
|
<p>Martin's answer is correct on Windows Server 2003:</p>
<blockquote>
<p>You will have to assign the "Lock pages in memory" privilege to any user that runs your > application. This includes administrators</p>
<ol>
<li>Select Control Panel -> Administrative Tools -> Local Security Policy</li>
<li>Select Local Policies -> User Rights Assignment</li>
<li>Double click "Lock pages in memory", add users and/or groups</li>
<li>Reboot the machine</li>
</ol>
</blockquote>
<p>On Windows Vista you need also make sure that the application is run as Administrator (by right-clicking on the application or the shell and choosing "Run as adminstrator".</p>
<p>In addition, it helps to have a freshly booted machine since the large pages can "run out" due to fragmentation of the heap.</p>
|
<p>You will have to assign the <code>Lock pages in memory</code> privilege to any user that runs your application. This includes administrators.</p>
<ol>
<li>Select Control <strong>Panel -> Administrative Tools -> Local Security</strong> Policy </li>
<li>Select Local <strong>Policies -> User Rights Assignment</strong></li>
<li>Double click "Lock pages in memory", add users and/or groups </li>
<li>Reboot the machine </li>
</ol>
| 6,007
|
<p>I would like to sort a matrix according to a particular column. There is a <code>sort</code> function, but it sorts all columns independently.</p>
<p>For example, if my matrix <code>data</code> is:</p>
<pre><code> 1 3
5 7
-1 4
</code></pre>
<p>Then the desired output (sorting by the first column) would be:</p>
<pre><code>-1 4
1 3
5 7
</code></pre>
<p>But the output of <code>sort(data)</code> is:</p>
<pre><code>-1 3
1 4
5 7
</code></pre>
<p>How can I sort this matrix by the first column?</p>
|
<p>I think the <a href="http://www.mathworks.com/help/matlab/ref/sortrows.html" rel="noreferrer">sortrows</a> function is what you're looking for.</p>
<pre><code>>> sortrows(data,1)
ans =
-1 4
1 3
5 7
</code></pre>
|
<p>An alternative to <code>sortrows()</code>, which can be applied to broader scenarios.</p>
<ol>
<li><p>save the sorting indices of the row/column you want to order by:</p>
<pre><code>[~,idx]=sort(data(:,1));
</code></pre></li>
<li><p>reorder all the rows/columns according to the previous sorted indices</p>
<pre><code>data=data(idx,:)
</code></pre></li>
</ol>
| 16,310
|
<p>We have a vxWorks design which requires one task to process both high and low priority messages sent over two message queues.<br>
The messages for a given priority have to be processed in FIFO order. </p>
<p>For example, process all the high priority messages in the order they were received, then process the low priority messages. If there is no high priority message, then process the low priority message immediately.</p>
<p>Is there a way to do this?</p>
|
<p>If you use named pipes (pipeDevCreate(), write(), read()) instead of message queues, you can use select() to block until there are messages in either pipe. <br></p>
<p>Whenever select() triggers, you process all messages in the high priority pipe. Then you process a single message from the low priority pipe. Then call select again (loop).</p>
<p>Example Code snippets:</p>
<pre><code> // Initialization: Create high and low priority named pipes
pipeDrv(); //initialize pipe driver
int fdHi = pipeDevCreate("/pipe/high",numMsgs,msgSize);
int fdLo = pipeDevCreate("/pipe/low",numMsgs,msgSize);
...
// Message sending thread: Add messages to pipe
write(fdHi, buf, sizeof(buf));
...
// Message processing Thread: select loop
fd_set rdFdSet;
while(1)
{
FD_ZERO(&rdFdSet);
FD_SET(fdHi, &rdFdSet);
FD_SET(fdLo, &rdFdSet;
if (select(FD_SETSIZE, &rdFdSet, NULL, NULL, NULL) != ERROR)
{
if (FD_ISSET(fdHi, &rdFdSet))
{
// process all high-priority messages
while(read(fdHi,buf,size) > 0)
{
//process high-priority
}
}
if (FD_ISSET(fdLo, &rdFdSet))
{
// process a single low priority message
if (read(fdLo,buf,size) > 0)
{
// process low priority
}
}
}
}
</code></pre>
|
<p>In vxWorks, you can't wait directly on multiple queues. You can however use the OS events (from eventLib) to achieve this result.
Here is a simple code snippet:</p>
<pre><code>
MSG_Q_ID lowQ, hiQ;
void Init() {
// Task Initialization Code. This should be called from the task that will
// be receiving the messages
...
hiQ = msgQCreate(...);
lowQ = msgQCreate(...);
msgQEvStart(hiQ, VX_EV01); // Event 1 sent when hiQ receives message
msgQEvStart(loQ, VX_EV02); // Event 2 sent when loQ receives message
...
}
void RxMessages() {
...
UINT32 ev; // Event received
// Blocks until we receive Event 1 or 2
eventReceive(VX_EV01 | VX_EV02, EVENT_WAIT_ANY, WAIT_FOREVER, &ev);
if(ev & VX_EV01) {
msgQReceive(hiQ, ...);
}
if(ev & VX_EV02) {
msgQReceive(loQ, ...);
}
}
</code></pre>
<p>Note that you need to modify that code to make sure you drain all your queues in case there is more than one message that was received.</p>
<p>The same mechanism can also be applied to Binary semaphores using the semEvStart() function.</p>
| 14,657
|
<p>I have this function in VB.net "ENCRYPT" (see below)</p>
<pre><code>Private key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
Private iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219}
Public Function Encrypt(ByVal plainText As String) As Byte()
' Declare a UTF8Encoding object so we may use the GetByte
' method to transform the plainText into a Byte array.
Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText)
' Create a new TripleDES service provider
Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
' The ICryptTransform interface uses the TripleDES
' crypt provider along with encryption key and init vector
' information
Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv)
' All cryptographic functions need a stream to output the
' encrypted information. Here we declare a memory stream
' for this purpose.
Dim encryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write)
' Write the encrypted information to the stream. Flush the information
' when done to ensure everything is out of the buffer.
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
encryptedStream.Position = 0
' Read the stream back into a Byte array and return it to the calling method.
Dim result(encryptedStream.Length - 1) As Byte
encryptedStream.Read(result, 0, encryptedStream.Length)
cryptStream.Close()
Return result
End Function
</code></pre>
<p>I want to save the encrypted string in the SQL database. How do I do it?</p>
|
<p>Simply store in a binary column. (Mostly done from memory, corrections welcome!)</p>
<pre><code>CREATE TABLE [Test]
(
[Id] NOT NULL IDENTITY(1,1) PRIMARY KEY,
[Username] NOT NULL VARCHAR(500),
[Password] NOT NULL VARBINARY(500)
)
</code></pre>
<p>Then insert such:</p>
<pre><code>Dim conn As SqlConnection
Try
conn = New SqlConnection("<connectionstring>")
Dim command As New SqlCommand("INSERT INTO [Test] ([Username], [Password]) VALUES (@Username, @Password)", conn)
Dim usernameParameter = New SqlParameter("@Username", SqlDbType.VarChar)
usernameParameter.Value = username
command.Parameters.Add(usernameParameter)
Dim passwordParameter = New SqlParameter("@Password", SqlDbType.VarBinary)
passwordParameter.Value = password
command.Parameters.Add(passwordParameter)
command.ExecuteNonQuery()
Finally
If (Not (conn Is Nothing)) Then
conn.Close()
End If
End Try
</code></pre>
|
<p>Encode the array of byte into a string. 0x00 can be "00" and 0xFF can be "FF." Or you can take at look at <a href="http://en.wikipedia.org/wiki/Base64" rel="nofollow noreferrer">Base64</a>.</p>
| 17,738
|
<p>I've implemented an image/video transformation technique called discrete cosine transform. This technique is used in MPEG video encoding. I based my algorithm on the ideas presented at the following URL:</p>
<p><a href="http://vsr.informatik.tu-chemnitz.de/~jan/MPEG/HTML/mpeg_tech.html" rel="noreferrer"><a href="http://vsr.informatik.tu-chemnitz.de/~jan/MPEG/HTML/mpeg_tech.html" rel="noreferrer">http://vsr.informatik.tu-chemnitz.de/~jan/MPEG/HTML/mpeg_tech.html</a></a></p>
<p>Now I can transform an 8x8 section of a black and white image, such as:</p>
<pre>
0140 0124 0124 0132 0130 0139 0102 0088
0140 0123 0126 0132 0134 0134 0088 0117
0143 0126 0126 0133 0134 0138 0081 0082
0148 0126 0128 0136 0137 0134 0079 0130
0147 0128 0126 0137 0138 0145 0132 0144
0147 0131 0123 0138 0137 0140 0145 0137
0142 0135 0122 0137 0140 0138 0143 0112
0140 0138 0125 0137 0140 0140 0148 0143
</pre>
<p>Into this an image with all the important information at the top right. The transformed block looks like this:</p>
<pre>
1041 0039 -023 0044 0027 0000 0021 -019
-050 0044 -029 0000 0009 -014 0032 -010
0000 0000 0000 0000 -018 0010 -017 0000
0014 -019 0010 0000 0000 0016 -012 0000
0010 -010 0000 0000 0000 0000 0000 0000
-016 0021 -014 0010 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 -010 0013 -014 0010 0000 0000
</pre>
<p>Now, I need to know how can I take advantage of this transformation? I'd like to detect other 8x8 blocks in the same image ( or another image ) that represent a good match.</p>
<p>Also, What does this transformation give me? Why is the information stored in the top right of the converted image important?</p>
|
<p>The result of a DCT is a transformation of the original source into the frequency domain. The top left entry stores the "amplitude" the "base" frequency and frequency increases both along the horizontal and vertical axes. The outcome of the DCT is usually a collection of amplitudes at the more usual lower frequencies (the top left quadrant) and less entries at the higher frequencies. As lassevk mentioned, it is usual to just zero out these higher frequencies as they typically constitute very minor parts of the source. However, this does result in loss of information. To complete the compression it is usual to use a lossless compression over the DCT'd source. This is where the compression comes in as all those runs of zeros get packed down to almost nothing.</p>
<p>One possible advantage of using the DCT to find similar regions is that you can do a first pass match on low frequency values (top-left corner). This reduces the number of values you need to match against. If you find matches of low frequency values, you can increase into comparing the higher frequencies.</p>
<p>Hope this helps</p>
|
<p>If I remember correctly, this matrix allows you to save the data to a file with compression.</p>
<p>If you read further down, you'll find the zig-zag pattern of data to read from that final matrix. The most important data are in the top left corner, and least important in the bottom right corner. As such, if you stop writing at some point and just consider the rest as 0's, even though they aren't, you'll get a lossy approximation of the image.</p>
<p>The number of values you throw away increases compression at the cost of image fidelity.</p>
<p>But I'm sure someone else can give you a better explanation.</p>
| 2,657
|
<p>I need an easy way to allow users to upload multiple files at once (ie I need to allow a user to upload a folder). I do not wish to put the burden of zipping on the user. </p>
<p><em>I would prefer to avoid Flash or variants if possible.</em> I'm looking for a straight javascript / HTML solution if it is possible. Please note, this rules out the answers at: <a href="https://stackoverflow.com/questions/159600/multiple-file-upload">What is the best client side browser library to upload multiple files over http?</a>.</p>
|
<p>You won't be able to do it with just HTML and Javascript. I'd recommend trying <a href="http://digitarald.de/project/fancyupload/" rel="noreferrer">Fancy Upload</a>, a <a href="http://mootools.net/" rel="noreferrer">MooTools</a> plugin for multiple file uploads. It uses a mixture of JavaScript and Flash, but degrades gracefully. It works with all major browsers including IE6 and there is also a Flash 10 compatible release available for download (though the demo hasn't been updated yet).</p>
<hr>
<p>Update (2012-11-26):</p>
<p><strong>Multiple file</strong> uploads are possible with <a href="https://github.com/valums/file-uploader" rel="noreferrer">valums</a> or <a href="https://github.com/blueimp/jQuery-File-Upload" rel="noreferrer">blueimp</a> file uploaders.</p>
<p>For <strong>recursive directory</strong> uploads, your best solution is using <a href="https://stackoverflow.com/a/5849341/486547">Chrome 11's new <strong>folder upload API</strong></a>. It also seems to work on Firefox if you use a vendor prefix.</p>
|
<p>This isn't a pure js/html solution. As EndangeredMassa has pointed out, it's not possible. In fact, this idea is an IE/Windows only solution. I don't recommend it, but it can work.</p>
<p>So, all disclaimers aside ... </p>
<p>Many years and several employers ago, we used to do some client side stuff that instantiated the FileSystemObject. It would iterate through each of the files and pass them through to the server one at a time. Can't remember the details of how we did that :o( </p>
<p>Anyway, this usually meant that the client box would need to have to add the site to the list of trusted sites and give trusted sites a bunch of permissions that are turned off (for very good reasons). Stuff like the ability to Initialize and script ActiveX controls not marked as safe. That kind of thing.</p>
<p>I know that this isn't a perfect answer, but it could point you in the right direction.</p>
| 31,709
|
<p>I have this quiz rails app linked to an IRC bot who asks questions (yes, on IRC), where I have this <code>Question</code> model which contains, well, questions, answers, hints, and a few more things.</p>
<p>I started with <code>Quiz</code> model (like, say, the special Halloween or Christmas quiz) with a <code>quiz_id</code> in the <code>questions</code> table, then, I told myself, that it would be nice to be able to categorize the questions, so I added a <code>Category</code> model (like, say, Movies or Books), with a <code>category_id</code> in the <code>questions</code>.</p>
<p>Now, my users would like to be able to add a question to one or more quiz, and to assign one or more categories to questions…</p>
<p>So, I've been thinking about removing the <code>Quiz</code> and <code>Category</code> models and replace them with tags, so that, there will be a halloween tag, a movie tag, and a question can have "halloween movie christmas" for tags.</p>
<p>In my searchs, I've seen quite a few ways to include tags like <code>acts_as_taggable</code>, <code>acts_as_taggable_on_steroids</code> or whatever else someone has imagined :-)</p>
<p>Now, I'm wondering what I should do, and so, I'm asking, what you have done, how you've done it, why you did it this way.</p>
|
<p><strong>Please don't do this.</strong> It's a really, really, really, really, really <em>bad idea</em>.</p>
<p>Maybe not as bad as deleting files randomly, if the hard drive runs out of room - but just about as bad.</p>
|
<p>Mark's code is probably better, but here's mine...</p>
<p>If you <strong>really</strong> want to do something like this, I'd use code something like this. Yes, you still have to manually call it, but your idea of indiscriminately retrying ALL excepting methods is a really, really bad idea.</p>
<pre><code>public class TryAgain
{
public delegate void CodeToTryAgain ();
public static void Repeat<E>(int count, CodeToTryAgain code) where E : Exception
{
while (count-- > 0)
{
try
{
code();
return;
}
catch (E ex)
{
Console.WriteLine("Caught an {0} : {1}", typeof(E).Name, ex.Message);
// ignoring it!
}
}
}
}
</code></pre>
<p>And then you'd call your failing method, <code>ThrowTwice</code>, or whatever you want to do, like this:</p>
<pre><code>TryAgain.Repeat<MyException>(5, delegate()
{
ThrowTwice();
});
</code></pre>
<p>In this example, the Repeat method will ignore all exceptions of type MyException, trying to call ThrowTwice up to 5 times...</p>
<p>You can add your own sleeping and time-outs, and whatever.</p>
| 43,552
|
<p>One of the topics that seems to come up regularly on mailing lists and online discussions is the merits (or lack thereof) of doing a Computer Science Degree. An argument that seems to come up time and again for the negative party is that they have been coding for some number of years and they have never used recursion.</p>
<p>So the question is:</p>
<ol>
<li>What is recursion?</li>
<li>When would I use recursion?</li>
<li>Why don't people use recursion?</li>
</ol>
|
<p>There are a number of good explanations of <a href="http://en.wikipedia.org/wiki/Recursion_%28computer_science%29" rel="noreferrer">recursion</a> in this thread, this answer is about why you shouldn't use it in most languages.* In the majority of major imperative language implementations (i.e. every major implementation of C, C++, Basic, Python, Ruby,Java, and C#) <a href="http://en.wikipedia.org/wiki/Iteration" rel="noreferrer">iteration</a> is vastly preferable to recursion.</p>
<p>To see why, walk through the steps that the above languages use to call a function:</p>
<ol>
<li>space is carved out on <a href="http://en.wikipedia.org/wiki/Call_stack" rel="noreferrer">the stack</a> for the function's arguments and local variables</li>
<li>the function's arguments are copied into this new space</li>
<li>control jumps to the function</li>
<li><strong><em>the function's code runs</em></strong></li>
<li>the function's result is copied into a return value</li>
<li>the stack is rewound to its previous position</li>
<li>control jumps back to where the function was called</li>
</ol>
<p>Doing all of these steps takes time, usually a little bit more than it takes to iterate through a loop. However, the real problem is in step #1. When many programs start, they allocate a single chunk of memory for their stack, and when they run out of that memory (often, but not always due to recursion), the program crashes due to a <a href="http://en.wikipedia.org/wiki/Stack_overflow" rel="noreferrer">stack overflow</a>.</p>
<p>So in these languages recursion is slower and it makes you vulnerable to crashing. There are still some arguments for using it though. In general, code written recursively is shorter and a bit more elegant, once you know how to read it.</p>
<p>There is a technique that language implementers can use called <a href="http://en.wikipedia.org/wiki/Tail_call_optimization" rel="noreferrer">tail call optimization</a> which can eliminate some classes of stack overflow. Put succinctly: if a function's return expression is simply the result of a function call, then you don't need to add a new level onto the stack, you can reuse the current one for the function being called. Regrettably, few imperative language-implementations have tail-call optimization built in. </p>
<p>* <em>I love recursion. <a href="http://www.haskell.org/" rel="noreferrer">My favorite static language</a> doesn't use loops at all, recursion is the only way to do something repeatedly. I just don't think that recursion is generally a good idea in languages that aren't tuned for it.</em></p>
<p>** By the way Mario, the typical name for your ArrangeString function is "join", and I'd be surprised if your language of choice doesn't already have an implementation of it.</p>
|
<p>I have created a recursive function to concatenate a list of strings with a separator between them. I use it mostly to create SQL expressions, by passing a list of fields as the '<em>items</em>' and a '<em>comma+space</em>' as the separator. Here's the function (It uses some Borland Builder native data types, but can be adapted to fit any other environment):</p>
<pre><code>String ArrangeString(TStringList* items, int position, String separator)
{
String result;
result = items->Strings[position];
if (position <= items->Count)
result += separator + ArrangeString(items, position + 1, separator);
return result;
}
</code></pre>
<p>I call it this way:</p>
<pre><code>String columnsList;
columnsList = ArrangeString(columns, 0, ", ");
</code></pre>
<p>Imagine you have an array named '<em>fields</em>' with this data inside it: '<em>albumName</em>', '<em>releaseDate</em>', '<em>labelId</em>'. Then you call the function:</p>
<pre><code>ArrangeString(fields, 0, ", ");
</code></pre>
<p>As the function starts to work, the variable '<em>result</em>' receives the value of the position 0 of the array, which is '<em>albumName</em>'.</p>
<p>Then it checks if the position it's dealing with is the last one. As it isn't, then it concatenates the result with the separator and the result of a function, which, oh God, is this same function. But this time, check it out, it call itself adding 1 to the position.</p>
<pre><code>ArrangeString(fields, 1, ", ");
</code></pre>
<p>It keeps repeating, creating a LIFO pile, until it reaches a point where the position being dealt with IS the last one, so the function returns only the item on that position on the list, not concatenating anymore. Then the pile is concatenated backwards.</p>
<p>Got it? If you don't, I have another way to explain it. :o)</p>
| 2,515
|
<p>I want to write a script which cleans the 'run' dialogue automatically every log off. Where is the history stored?</p>
|
<p>From:</p>
<p><a href="http://www.pchell.com/support/editrunmrulistentries.shtml" rel="noreferrer">How to Remove Individual Entries from Run Command History</a></p>
<blockquote>
<p>Where is the Run MRU (Most Recently
Used) List?</p>
<p>The RUNMRU list is stored in the
Windows Registry in the following
location:</p>
<p>HKEY_CURRENT_USER\ Software\
Microsoft\ Windows\ CurrentVersion\
Explorer\ RunMRU\</p>
<p>Is There a Program to Delete
Individual Entries from the RUNMRU
List?</p>
<p>Many of my customers would rather not
edit the Windows registry to remove
these individual entries, so I setup a
VBScript that you can download and run
to delete individual commands from
this list. Follow these instructions
to download and use this program to
clear unwanted entries from the Run
Command history.</p>
<p>1) Click on the following link and
download the EditRunMRUList.vbs script
to your desktop</p>
<p>Download <a href="http://www.pchell.com/downloads/editrunmrulist.vbs" rel="noreferrer">EditRunMRUList.vbs</a></p>
</blockquote>
|
<p>Never use registry, just use Win32 SH api to clean it.</p>
| 20,508
|
<p>Speaking as a non-C# savvy programmer, I'm curious as to the evaluation semantics of LINQ queries like the following:</p>
<pre><code>var people = from p in Person
where p.age < 18
select p
var otherPeople = from p in people
where p.firstName equals "Daniel"
select p
</code></pre>
<p>Assuming that <code>Person</code> is an ADO entity which defines the <code>age</code> and <code>firstName</code> fields, what would this do from a database standpoint? Specifically, would the <code>people</code> query be run to produce an in-memory structure, which would then be queried by the <code>otherPeople</code> query? Or would the construction of <code>otherPeople</code> merely pull the data regarding the query from <code>people</code> and then produce a new database-peered query? So, if I iterated over both of these queries, how many SQL statements would be executed?</p>
|
<p>They are composable. This is possible because LINQ queries are actually expressions (code as data), which LINQ providers like LINQ-to-SQL can evaluate and generate corresponding SQL.</p>
<p>Because LINQ queries are lazily evaluated (e.g. won't get executed until you iterate over the elements), the code you showed won't actually touch the database. Not until you iterate over otherPeople or people will SQL get generated and executed.</p>
|
<p>Both these queries will be executes when you'll try to access final results. You can try to view original SQL generated from DataContext object properties.</p>
| 11,477
|
<p>A J2ME client is sending HTTP POST requests with chunked transfer encoding.</p>
<p>When ASP.NET (in both IIS6 and WebDev.exe.server) tries to read the request it sets the Content-Length to 0. I guess this is ok because the Content-length is unknown when the request is loaded.</p>
<p>However, when I read the Request.InputStream to the end, it returns 0.</p>
<p>Here's the code I'm using to read the input stream.</p>
<pre><code>using (var reader = new StreamReader(httpRequestBodyStream, BodyTextEncoding)) {
string readString = reader.ReadToEnd();
Console.WriteLine("CharSize:" + readString.Length);
return BodyTextEncoding.GetBytes(readString);
}
</code></pre>
<p>I can simulate the behaiviour of the client with Fiddler, e.g.</p>
<p><strong>URL</strong>
<a href="http://localhost:15148/page.aspx" rel="nofollow noreferrer">http://localhost:15148/page.aspx</a></p>
<p><strong>Headers:</strong>
User-Agent: Fiddler
Transfer-Encoding: Chunked
Host: somesite.com:15148</p>
<p><strong>Body</strong>
rabbits rabbits rabbits rabbits. thanks for coming, it's been very useful!</p>
<p>My body reader from above will return a zero length byte array...lame...</p>
<p>Does anyone know how to enable chunked encoding on IIS and ASP.NET Development Server (cassini)?</p>
<p>I found <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;278998" rel="nofollow noreferrer">this script</a> for IIS but it isn't working.</p>
|
<p>Seems to be official: <a href="http://msdn.microsoft.com/en-us/library/ee960144.aspx" rel="nofollow">Cassini does not support <code>Transfer-Encoding: chunked</code> requests.</a></p>
<blockquote>
<p>By default, the client sends large
binary streams by using a chunked HTTP
Transfer-Encoding. <strong>Because the ASP.NET
Development Server does not support
this kind of encoding</strong>, you cannot use
this Web server to host a streaming
data service that must accept large
binary streams.</p>
</blockquote>
|
<p>That url does not work any more, so it's hard to test this directly. I wondered if this would work, and google turned up someone who has experience with it at <a href="http://bytes.com/forum/thread246706.html" rel="nofollow noreferrer">bytes.com</a>. If you put your website up again, I can see if this really works there. </p>
<p><strong>Joerg Jooss</strong> wrote: (<em>slightly modified for brevity</em> )</p>
<pre><code>string responseText = null;
WebRequest rabbits= WebRequest.Create(uri);
using (Stream resp = rabbits.GetResponse().GetResponseStream()) {
MemoryStream memoryStream = new MemoryStream(0x10000);
byte[] buffer = new byte[0x1000];
int bytes;
while ((bytes = resp.Read(buffer, 0, buffer.Length)) > 0) {
memoryStream.Write(buffer, 0, bytes);
}
// use the encoding to match the data source.
Encoding enc = Encoding.UTF8;
reponseText = enc.GetString(memoryStream.ToArray());
}
</code></pre>
| 9,455
|
<p>I'm looking for computationally heavy tasks to implement with CUDA and wonder if neural networks or bayesian networks might apply. This is not my question, though, but rather what the relation between the two network types is. They seem very related, especially if you look at bayesian networks with a learning capability (which the article on wikipedia mentions). At a glance, bayesian networks look at bit like a specific type of neural networks. Can anyone sum up their relationship, and if there is any connection beyond the apparent similarity?</p>
|
<p>Bayesian networks represent independence (and dependence) relationships between variables. Thus, the links represent conditional relationships in the probabilistic sense. Neural networks, generally speaking, have no such direct interpretation, and in fact the intermediate nodes of most neural networks are discovered features, instead of having any predicate associated with them in their own right. </p>
|
<p>Indeed they are. I see a bayesian network as a neural network applying the Baye's Theorem on large scale, but I don't remember details. I know where you can find them and I recommend <a href="https://rads.stackoverflow.com/amzn/click/com/0471056693" rel="nofollow noreferrer" rel="nofollow noreferrer">this</a> book for that.</p>
| 39,255
|
<p>When I make the same query twice, the second time it does not return new rows form the database (I guess it just uses the cache).</p>
<p>This is a Windows Form application, where I create the dataContext when the application starts.</p>
<p>How can I force Linq to SQL not to use the cache?</p>
<p>Here is a sample function where I have the problem:</p>
<pre><code>public IEnumerable<Orders> NewOrders()
{
return from order in dataContext.Orders
where order.Status == 1
select order;
}
</code></pre>
|
<p>The simplest way would be to use a new DataContext - given that most of what the context gives you is caching and identity management, it really sounds like you just want a new context. Why did you want to create just the one and then hold onto it?</p>
<p>By the way, for simple queries like yours it's more readable (IMO) to use "normal" C# with extension methods rather than query expressions:</p>
<pre><code>public IEnumerable<Orders> NewOrders()
{
return dataContext.Orders.Where(order => order.Status == 1);
}
</code></pre>
<p>EDIT: If you <em>never</em> want it to track changes, then set <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.objecttrackingenabled.aspx" rel="noreferrer">ObjectTrackingEnabled</a> to false before you do anything. However, this will severely limit it's usefulness. You can't just flip the switch back and forward (having made queries between). Changing your design to avoid the singleton context would be much better, IMO.</p>
|
<p>It can matter HOW you add an object to the DataContext as to whether or not it will be included in future queries.</p>
<p><strong>Will NOT add the new InventoryTransaction to future in memory queries</strong></p>
<p>In this example I'm adding an object with an ID and then adding it to the context.</p>
<pre><code>var transaction = new InventoryTransaction()
{
AdjustmentDate = currentTime,
QtyAdjustment = 5,
InventoryProductId = inventoryProductId
};
dbContext.InventoryTransactions.Add(transaction);
dbContext.SubmitChanges();
</code></pre>
<p>Linq-to-SQL isn't clever enough to see this as needing to be added to the previously cached list of in memory items in <code>InventoryTransactions</code>.</p>
<p><strong>WILL add the new InventoryTransaction to future in memory queries</strong></p>
<pre><code>var transaction = new InventoryTransaction()
{
AdjustmentDate = currentTime,
QtyAdjustment = 5
};
inventoryProduct.InventoryTransactions.Add(transaction);
dbContext.SubmitChanges();
</code></pre>
<p>Wherever possible use the collections in Linq-to-SQL when creating relationships and not the IDs.</p>
<p>In addition as Jon says, try to minimize the scope of a DataContext as much as possible.</p>
| 38,504
|
<p>I'd like to write a MessageConverter class that can wrap another MessageConverter. This MessageConverter would call the child converter, which is assumed to generate a TextMessage. It would take the payload and GZIP compress it, creating a BytesMessage which is ultimately returned to the sender.</p>
<p>The problem is in writing fromMessage(). I can convert the payload back into the string, but then I want to create a "dummy" TextMessage to stuff the string into to then pass to the child MessageConverter's fromMessage() method. There I'm hitting a brick wall because I can't create a TextMessage without a JMS session object, and it appears that there is no way at all to get a session in this context.</p>
<p>I could create additional properties to wire up more stuff to this class, but it doesn't look like I can easily even obtain a session from a JMSTemplate object, and I can't imagine what else I'd need to have.</p>
<p>I am on the verge of creating a private TextMessage implementation within this code just for the purpose of wrapping a string for the child MessageConverter. That class will require tons of dummy methods to flesh out the Interface, and all of that typing makes baby Jesus cry.</p>
<p>Can anyone suggest a better way?</p>
|
<p>So I did, in fact, make one of these:</p>
<pre><code> private static class FakeTextMessage implements TextMessage {
public FakeTextMessage(Message m) { this.childMessage = m; }
private String text;
private Message childMessage;
public void setText(String t) { this.text = t; }
public String getText() { return this.text; }
// All the rest of the methods are simply pass-through
// implementations of the rest of the interface, handing off to the child message.
public void acknowledge() throws JMSException { this.childMessage.acknowledge(); }
public void clearBody() throws JMSException { this.childMessage.clearBody(); }
public void clearProperties() throws JMSException { this.childMessage.clearProperties(); }
public Enumeration getPropertyNames() throws JMSException { return this.childMessage.getPropertyNames(); }
public boolean propertyExists(String pn) throws JMSException { return this.childMessage.propertyExists(pn); }
// and so on and so on
}
</code></pre>
<p>Makes me long for Objective C. How is THAT possible? :)</p>
|
<p>So I did, in fact, make one of these:</p>
<pre><code> private static class FakeTextMessage implements TextMessage {
public FakeTextMessage(Message m) { this.childMessage = m; }
private String text;
private Message childMessage;
public void setText(String t) { this.text = t; }
public String getText() { return this.text; }
// All the rest of the methods are simply pass-through
// implementations of the rest of the interface, handing off to the child message.
public void acknowledge() throws JMSException { this.childMessage.acknowledge(); }
public void clearBody() throws JMSException { this.childMessage.clearBody(); }
public void clearProperties() throws JMSException { this.childMessage.clearProperties(); }
public Enumeration getPropertyNames() throws JMSException { return this.childMessage.getPropertyNames(); }
public boolean propertyExists(String pn) throws JMSException { return this.childMessage.propertyExists(pn); }
// and so on and so on
}
</code></pre>
<p>Makes me long for Objective C. How is THAT possible? :)</p>
| 29,852
|
<p>Are there any templates/patterns/guides I can follow for designing a multithreaded server? I can't find anything terribly useful online through my google searches.</p>
<p>My program will start a thread to listen for connections using TcpListener.
Every client connection will be handled by it's own IClientHandler thread. The server will wrap the clientHandler.HandleClient in a delegate, call BeginInvoke, and then quit caring about it.</p>
<p>I also need to be able to cleanly shutdown the listening thread, which is something I'm not finding a lot of exampes of online.</p>
<p>I'm assuming some mix of lock/AutoResetEvents/threading magic combined with the async BeginAceptTcpClient and EndAcceptTcpClient will get me there, but when it comes to networking code, to me it's all been done. So I have to believe there's just some pattern out there I can follow and not get totally confused by the myriad multithreaded corner cases I can never seem to get perfect.</p>
<p>Thanks.</p>
|
<p>Oddly enough you may find something on a Computer Science Assignment, <a href="http://homepage.cs.uri.edu/courses/attic/csc512/assn3.html" rel="noreferrer"><strong>CSC 512 Programming Assignment 4: Multi-Threaded Server With Patterns</strong></a>. Altough it's C++ voodoo but the theory is quite understandable for someone who can do C#.</p>
<ul>
<li><a href="http://www.cs.wustl.edu/~schmidt/PDF/Acc-Con.pdf" rel="noreferrer">Acceptor/ Connector</a></li>
<li><a href="http://www.cs.wustl.edu/~schmidt/PDF/monitor.pdf" rel="noreferrer">Monitor Object</a></li>
<li><a href="http://www.cs.wustl.edu/~schmidt/PDF/dispatching.pdf" rel="noreferrer">Thread Safe Interface</a></li>
<li><a href="http://www.cs.wustl.edu/~schmidt/PDF/wrapper-facade.pdf" rel="noreferrer">Wrapper Facade</a></li>
<li><a href="http://www.cs.wustl.edu/~schmidt/PDF/dispatching.pdf" rel="noreferrer">Scoped Locking</a></li>
<li><a href="http://www.cs.wustl.edu/~schmidt/PDF/locking-patterns.pdf" rel="noreferrer">Strategized Locking</a></li>
<li><a href="http://www.cs.wustl.edu/~schmidt/PDF/reactor-siemens.pdf" rel="noreferrer">Reactor</a></li>
<li><a href="http://www.cs.wustl.edu/~schmidt/PDF/PLoP-95.pdf" rel="noreferrer">Half Sync/Half-Async</a></li>
<li><a href="http://www.cs.wustl.edu/~schmidt/PDF/lf.pdf" rel="noreferrer">Leaders/Followers</a></li>
</ul>
<p>Altough you can get the whole list of nice readings on the <a href="http://homepage.cs.uri.edu/courses/attic/csc512/" rel="noreferrer">main page</a>.</p>
|
<p>Take a look at this previous question:</p>
<p><a href="https://stackoverflow.com/questions/32198/how-do-you-minimize-the-number-of-threads-used-in-a-tcp-server-application">How do you minimize the number of threads used in a tcp server application?</a></p>
<p>It's not strictly C# specific, but it has some good advice.</p>
| 17,978
|
<p><a href="https://stackoverflow.com/questions/374572/need-help-variable-creation-in-python#374604">That</a> was helpful kgiannakakis.
I'm facing a problem as below:</p>
<pre><code>a = ['zbc','2.3']
for i in range(0,5):
exec('E%d=%s' %(i,a[i]))
</code></pre>
<p>This results in:</p>
<pre>
Traceback (most recent call last):
File "", line 2, in
exec('E%d=%s' %(i,a[i]))
File "", line 1, in
NameError: name 'zbc' is not defined
</pre>
|
<p>It looks like the code you're generating expands to:</p>
<pre><code>E0=zbc
E1=2.3
</code></pre>
<p>At the next iteration through the loop, you'll get an IndexError exception because <code>a</code> is only two elements long.</p>
<p>So given the above, you are trying to assign the value of <code>zbc</code> to <code>E0</code>. If <code>zbc</code> doesn't exist (which it seems that it doesn't), then you will get the NameError you mention.</p>
<p>It's hard to determine what you're actually trying to do with this code, so I'm not sure what to recommend. You could assign strings instead:</p>
<pre><code>exec('E%d="%s"' %(i,a[i]))
</code></pre>
<p>This would expand to:</p>
<pre><code>E0="zbc"
E1="2.3"
</code></pre>
<p>You would still get the IndexError because your array <code>a</code> is not 5 elements long. That should be an easy fix for you.</p>
|
<p>Okay. this code is very weird.</p>
<p>As a one liner like this, it's not syntactically correct, but I suspect you're missing line breaks for some reason. But then it becomes</p>
<pre><code>a = ['zbc','2.3']
for i in range(0,5):
exec('E%d=%s' %(i,a[i]))
</code></pre>
<p>But that will result in an index error on the reference to a[i] as shown:</p>
<pre><code>>>> a
['zbc', '2.3']
>>> for i in range(0,5):
... print a[i]
...
zbc
2.3
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: list index out of range
</code></pre>
<p>If you avoided that issue, you'd get</p>
<pre><code>exec("E2.3=1")
</code></pre>
<p>on the second pass through the lopp, and that's a syntax error too.</p>
| 49,356
|
<p>Is there a typedef equivalent in C#, or someway to get some sort of similar behaviour? I've done some googling, but everywhere I look seems to be negative. Currently I have a situation similar to the following:</p>
<pre><code>class GenericClass<T>
{
public event EventHandler<EventData> MyEvent;
public class EventData : EventArgs { /* snip */ }
// ... snip
}
</code></pre>
<p>Now, it doesn't take a rocket scientist to figure out that this can very quickly lead to a lot of typing (apologies for the horrible pun) when trying to implement a handler for that event. It'd end up being something like this:</p>
<pre><code>GenericClass<int> gcInt = new GenericClass<int>;
gcInt.MyEvent += new EventHandler<GenericClass<int>.EventData>(gcInt_MyEvent);
// ...
private void gcInt_MyEvent(object sender, GenericClass<int>.EventData e)
{
throw new NotImplementedException();
}
</code></pre>
<p>Except, in my case, I was already using a complex type, not just an int. It'd be nice if it were possible to simplify this a little...</p>
<p>Edit: ie. perhaps typedefing the EventHandler instead of needing to redefine it to get similar behaviour.</p>
|
<p>No, there's no true equivalent of typedef. You can use 'using' directives within one file, e.g.</p>
<pre><code>using CustomerList = System.Collections.Generic.List<Customer>;
</code></pre>
<p>but that will only impact that source file. In C and C++, my experience is that <code>typedef</code> is usually used within .h files which are included widely - so a single <code>typedef</code> can be used over a whole project. That ability does not exist in C#, because there's no <code>#include</code> functionality in C# that would allow you to include the <code>using</code> directives from one file in another.</p>
<p>Fortunately, the example you give <em>does</em> have a fix - implicit method group conversion. You can change your event subscription line to just:</p>
<pre><code>gcInt.MyEvent += gcInt_MyEvent;
</code></pre>
<p>:)</p>
|
<p>Since the introduction of C# 10.0, we now have the <code>global using</code> directive.</p>
<pre><code>global using CustomerList = System.Collections.Generic.List<Customer>;
</code></pre>
<p>This introduces <code>CustomerList</code> as alias of <code>List<Customer></code> on a global scope (throughout the whole project and all references to it).</p>
<p>Though I would have liked to be able to limit its scope (say for instance 'internal using') this does actually do a terrific job of fulfilling a typedef variant in C#.</p>
| 19,515
|
<p>I'd like to gain better knowledge of operating system internals. Process management, memory management, and stuff like that. <br>
I was thinking of learning by getting to know either linux or BSD kernel.<br>
Which one kernel is better for learning purposes?<br>
What's the best place to start?<br>
Can you recommend any good books?<br></p>
|
<p>In college, I had an operating systems class where we used a <a href="https://rads.stackoverflow.com/amzn/click/com/0003458903" rel="noreferrer" rel="nofollow noreferrer">book by Tanenbaum</a>. In the class, we implemented a device driver in the <a href="http://minix1.woodhull.com/teaching/teach_ver.html" rel="noreferrer">Minix operating system</a>. It was a lot of fun, and we learned a lot.</p>
<p>One thing to note though, if you pick Minix, it is designed for learning. It is a microkernel, while Linux and BSD are a monolithic kernel, so what you learn may not be 100% translatable to be able to work with Linux or BSD, but you can still gain a lot out of it, without having to process quite as much information.</p>
<p>As a side note, if you've read <a href="https://rads.stackoverflow.com/amzn/click/com/0066620732" rel="noreferrer" rel="nofollow noreferrer">Just for Fun</a>, Linus actually was playing with Minix before he wrote Linux, but it just wasn't enough for his purposes.</p>
|
<p>When I was at uni I spent a semester studying operating systems, and as part of this had an assignment where we had to implement a RAM-based filesystem in Linux.</p>
<p>It was a fantastic way to get to understand the internals of the Linux keurnel and to get a grasp on how everything fits together - And a heck of a lot of fun playing around with how it interacts with standard tools too.</p>
| 4,431
|
<p>I'm using the current version of restful_authentication that is found on github and I'm having a bunch of strange session issues. The server seems to be somehow assigning sessions to users it shouldn't be. This only happens when crossing the logged out/logged in barrier.</p>
<p>Here's an example. With no sessions active on the server, I log in to an account with user A. On another machine, I log in with user B. Then when logging out of user B, sometime after the logout redirect happens, I will be logged in as user A. From this point, I can continue to navigate the site as if I had logged in as that user! Something I've observed via the logs is that when this hijack happens, the session IDs are not the same. User A is logged in in both sessions, but the session ID's are completely different. This is just one example of what might happen. I can't reproduce the issue reliably as it is seemingly random. </p>
<p>It doesn't seem to be a symptom of the environment or the server it's running on. I can reproduce the problem using both mongrel and passenger. I've also seen it in development and production. I am using db-based sessions in this application and it is running on Rails 2.1.1. I applied the stateful option when calling the generator. Otherwise no other modifications have been made to how sessions are handled.</p>
<p>Update
Here is the offending method which came directly from restful_authentication.</p>
<pre><code># Accesses the current user from the session.
# Future calls avoid the database because nil is not equal to false.
def current_user
@current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie) unless @current_user == false
end
</code></pre>
|
<p>I don't know if this is so much of an answer as it is a work around. All I did was switch over to cookie based sessions and everything is working smoothly.</p>
|
<p>Is this site remote? Are you logging into it onto two separate computers on the same network?</p>
| 17,502
|
<p>I'm a little hesitant to post this, as I'm not completely sure what I'm doing. Any help would be wonderful.</p>
<p>I'm on a computer with a firewall/filter on it. I can download files without any difficulty. When I try to clone files from Github, though, the computer just hangs. Nothing happens. It creates a git file in the folder, but the key files don't get loaded in. For context, I'm working on a Rails app, trying to load in Restful Authentication.</p>
<p>Have any of you dealt with this? Any suggestions for getting the clone to work? Disabling the firewall might be an option, but if I can do something without going through that process, I'd appreciate it.</p>
|
<p>Github supports cloning using both the git protocol over port 9418 and HTTP over port 80. Using the later is very slow (<a href="http://github.com/blog/92-http-cloning" rel="noreferrer">Reference</a>).
You should open port 9418 on your firewall or use HTTP cloning otherwise.</p>
|
<pre><code>git config --global url."https://".insteadOf git://
</code></pre>
<p>Done!</p>
| 11,410
|
<p>What are the steps required to enable Hibernate's second-level cache, when using the Java Persistence API (annotated entities)? How do I check that it's working? I'm using JBoss 4.2.2.GA.</p>
<p>From the Hibernate documentation, it seems that I need to enable the cache and specify a cache provider in <em>persistence.xml</em>, like:</p>
<pre><code><property name="hibernate.cache.use_second_level_cache"
value="true" />
<property name="hibernate.cache.provider_class"
value="org.hibernate.cache.HashtableCacheProvider" />
</code></pre>
<p>What else is required? Do I need to add <em>@Cache</em> annotations to my JPA entities?</p>
<p>How can I tell if the cache is working? I have tried accessing cache statistics after running a Query, but <em>Statistics.getSecondLevelCacheStatistics</em> returns null, perhaps because I don't know what 'region' name to use.</p>
|
<p>I believe you need to add the cache annotations to tell hibernate how to use the second-level cache (read-only, read-write, etc). This was the case in my app (using spring / traditional hibernate and ehcache, so your mileage may vary). Once the caches were indicated, I started seeing messages that they were in use from hibernate.</p>
|
<p>Follow-up: in the end, after adding annotations, I have it working with EhCache, i.e.</p>
<pre><code><property name="hibernate.cache.provider_class"
value="net.sf.ehcache.hibernate.EhCacheProvider" />
</code></pre>
| 7,707
|
<p>OK, probably best to give an example here of what I mean.</p>
<p>Imagine a web based forum system, where the user authentication is done by some external method, which the system is aware of.</p>
<p>Now, say for example, a user enters the URL for a thread that they do not have access to. For this should I return a 403 (Forbidden), letting the user know that they should try another authentication method, or a 404, not letting them know that there is something there to access.</p>
<p>Assuming I return a 403, should I also return a 403 when they access a URL for a topic that doesn't exist yet?</p>
<p>Edit: the example above was more of an example that something IRL.</p>
<p>Another Example, say I expose something like</p>
<pre><code>/adminnotes/user
</code></pre>
<p>if there are Administrator notes about the user. Now, returning a 403 would let the user know that there is something there being said about them. A 404 would say nothing.</p>
<p>But, if I were to return a 403 - I could return it for adminnotes/* - which would resolve that issue.</p>
<p>Edit 2: Another example. Soft deleted Questions here return a 404. Yet, with the right authentication and access, you can still see them (I'd presume)</p>
|
<p>Above everything else, <strong>comply with HTTP spec.</strong> Returning 403 in place of 404 is not a good thing. Returning 404 in place of 403 probably is ok (or not a big blunder), but I would just <strong>let the software tell the truth</strong>. If user only knows the ID of a topic, it's not much anyway. And he could try <em>timing attacks</em> to determine whether this topic exists.</p>
|
<p>Lets say you did return a "page not found" error when you detect that the user does not have the correct access rights. A malicious person with the intent of hacking will soon figure out that you would return this in place of the access denied. </p>
<p>But the real users who mistype a url or use a wrong login etc would be confused and it would take no end of explanations and release notes to explain your position to the customers, TAC etc. In exchange for what ? </p>
<p>The intention is good, but i'm afraid this policy you propose might not work out the way you wanted it to. </p>
| 17,792
|
<p>I have got a simple page with a HtmlInputHidden field. I use Javascript to update that value and, when posting back the page, I want to read the value of that HtmlInputHidden field. The Value property of that HtmlInputHidden field is on postback the default value (the value it had when the page was created, not the value reflected through the Javascript). I also tried to Register the HtmlInputHidden field with ScriptManager.RegisterHiddenField(Page, "MyHtmlImputHiddenField", "initialvalue") but it still only lets me read the 'initialvalue' even though I (through javascript) can inspect that the value has changed.</p>
<p>I tried to hardcoded the rowid and, to my surprise, after postback gridview was exactly the same before the delete but the record was deleted from the database. (I´ve called the databind method). </p>
<pre><code> protected void gridViewDelete(object sender, GridViewDeleteEventArgs e)
{
bool bDelete = false;
bool bCheck = false;
if (hfControl.Value != "1")
{
// check relationship
bCheck = validation_method(.......);
if (bCheck)
{
bDelete = true;
}
}
else
{
hfControl.Value = "";
bDelete = true;
}
if (bDelete)
{
//process delete
}
else
{
string script = string.Empty;
script += " var x; ";
script += " x = confirm('are u sure?'); ";
script += " if (x){ " ;
script += " document.getElementById('hfControl').value = '1'; ";
script += " setTimeOut(__doPostBack('gridView','Delete$"
+ e.RowIndex + "'),0);";
script += " } ";
ScriptManager.RegisterClientScriptBlock(this,
Page.GetType()
, "confirm"
, script
,true);
}
}
</code></pre>
|
<p>Warning, as said <a href="http://www.eggheadcafe.com/software/aspnet/30020406/trouble-getting-logoff-sc.aspx" rel="nofollow noreferrer"><strong>here</strong></a>, <code>gpedit.msc</code> will allow you to configure a logoff script <strong>for <em>all</em> users</strong>.</p>
<p>If you need that script only for one user, you need to declare it directly in the registry, both in <code>HKCU</code> and <code>HKLM</code>.</p>
|
<p>If you need something simple and working for a single (or any) user you can make a simple application in C++ or C# for example.</p>
<p>The simplest is having a C# in tray (by simply adding the tray component to the form) and register and event handler for the <strong>FormClosing</strong> event. It'd look like this:</p>
<pre><code> private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason != CloseReason.UserClosing)
{
// It's not the user closing the application,
// Let's do whatever you want here, for example starting a process
Process notePad = new Process();
notePad.StartInfo.FileName = "notepad.exe";
notePad.StartInfo.Arguments = "ProcessStart.cs";
notePad.Start();
}
}
</code></pre>
<p>So your application will be started with Windows or with the user. It'll wait (using a little bit of memory) and will do something when the system shuts down, or the user log off, etc (by checking "CloseReason" above).</p>
| 41,987
|
<p>The client connects to the server using GenuineChannels (we are considering switching to DotNetRemoting). What I mean by find is obtain the IP and port number of a server to connect to.</p>
<p>It seems like a brute-force approach would be try every IP on the network try the active ports (not even sure if that's possible) but there must be a better way.</p>
|
<p>Consider broadcasting a specific UDP packet. When the server or servers see the broadcasted UDP packet they send a reply. The client can collect the replies from all the servers and start connecting to them or based on an election algorithm.</p>
<p>See example for client (<strong>untested code</strong>):</p>
<hr>
<pre><code>using System.Net;
using System.Net.Sockets;
[STAThread]
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Any, 8002));
socket.Connect(new IPEndPoint(IPAddress.Broadcast, 8001));
socket.Send(System.Text.ASCIIEncoding.ASCII.GetBytes("hello"));
int availableBytes = socket.Available;
if (availableBytes > 0)
{
byte[] buffer = new byte[availableBytes];
socket.Receive(buffer, 0, availableBytes, SocketFlags.None);
// buffer has the information on how to connect to the server
}
}
</code></pre>
|
<p>Have the server listen for broadcast on a specific port on the network (must use UDP), When client starts have it broadcast some "ping" request on that port. when the server sees a "ping" it send back a message with the TCP address and port required for the client to connect to it.</p>
| 25,828
|
<p>What is the reason browsers do not correctly recognize:</p>
<pre><code><script src="foobar.js" /> <!-- self-closing script element -->
</code></pre>
<p>Only this is recognized:</p>
<pre><code><script src="foobar.js"></script>
</code></pre>
<p>Does this break the concept of XHTML support?</p>
<p>Note: This statement is correct at least for all IE (6-8 beta 2).</p>
|
<p>The non-normative appendix ‘HTML Compatibility Guidelines’ of the XHTML 1 specification says:</p>
<p><a href="http://www.w3.org/TR/xhtml1/#C_3" rel="noreferrer">С.3. Element Minimization and Empty Element Content</a></p>
<blockquote>
<p>Given an empty instance of an element whose content model is not <code>EMPTY</code> (for example, an empty title or paragraph) do not use the minimized form (e.g. use <code><p> </p></code> and not <code><p /></code>).</p>
</blockquote>
<p><a href="http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict" rel="noreferrer">XHTML DTD</a> specifies script elements as:</p>
<pre><code><!-- script statements, which may include CDATA sections -->
<!ELEMENT script (#PCDATA)>
</code></pre>
|
<p>Difference between 'true XHTML', 'faux XHTML' and 'ordinary HTML' as well as importance of the server-sent MIME type had been <a href="https://stackoverflow.com/a/70288/540955">already described here well</a>.</p>
<p>If you want to try it out right now, here is simple editable snippet with live preview including self-closed script tag (see <code><script src="data:text/javascript,/*functionality*/" /></code>) and XML entity (unrelated, see <code>&x;</code>).</p>
<p>As you can see, depending on the MIME type of embedding document the data-URI JavaScript functionality is either executed and consecutive text displayed (in <code>application/xhtml+xml</code> mode) or not executed and consecutive text 'devoured' by the script (in <code>text/html</code> mode).</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div { display: flex; }
div + div {flex-direction: column; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>Mime type: <label><input type="radio" onchange="t.onkeyup()" id="x" checked name="mime"> application/xhtml+xml</label>
<label><input type="radio" onchange="t.onkeyup()" name="mime"> text/html</label></div>
<div><textarea id="t" rows="4"
onkeyup="i.src='data:'+(x.checked?'application/xhtml+xml':'text/html')+','+encodeURIComponent(t.value)"
><?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
[<!ENTITY x "true XHTML">]>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<p>
<span id="greet" swapto="Hello">Hell, NO :(</span> &x;.
<script src="data:text/javascript,(g=document.getElementById('greet')).innerText=g.getAttribute('swapto')" />
Nice to meet you!
<!--
Previous text node and all further content falls into SCRIPT element content in text/html mode, so is not rendered. Because no end script tag is found, no script runs in text/html
-->
</p>
</body>
</html></textarea>
<iframe id="i" height="80"></iframe>
<script>t.onkeyup()</script>
</div></code></pre>
</div>
</div>
</p>
<p>You should see <code>Hello, true XHTML. Nice to meet you!</code> below textarea.</p>
<p>For incapable browsers you can copy content of the textarea and save it as a file with <code>.xhtml</code> (or <code>.xht</code>) extension (<a href="https://stackoverflow.com/questions/69913/why-dont-self-closing-script-tags-work?rq=1#comment44088198_70288">thanks Alek for this hint</a>).</p>
| 9,530
|
<p>I'm having an issue dragging a file from Windows Explorer on to a Windows Forms application. </p>
<p>It works fine when I drag text, but for some reason it is not recognizing the file. Here is my test code:</p>
<pre><code>namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_DragDrop(object sender, DragEventArgs e)
{
}
private void Form1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
}
</code></pre>
<p>AllowDrop is set to true on Form1, and as I mentioned, it works if I drag text on to the form, just not an actual file.</p>
<p>I'm using Vista 64-bit ... not sure if that is part of the problem.</p>
|
<p>The problem comes from Vista's <a href="http://en.wikipedia.org/wiki/User_Account_Control" rel="noreferrer">UAC</a>. DevStudio is running as administrator, but explorer is running as a regular user. When you drag a file from explorer and drop it on your DevStudio hosted application, that is the same as a non-privileged user trying to communicate with a privileged user. It's not allowed.</p>
<p>This will probably not show up when you run the app outside of the debugger. Unless you run it as an administrator there (or if Vista auto-detects that it's an installer/setup app). </p>
<p>You could also <a href="http://www.neowin.net/forum/lofiversion/index.php/t575104.html" rel="noreferrer">run explorer as an admin</a>, at least for testing. Or disable UAC (which I would not recommend, since you really want to catch these issues during development, not during deployment!)</p>
|
<p>The code you posted <em>should</em> work.</p>
<p>Try putting this at the beginning of the DragEnter method</p>
<pre><code>string formats = string.Join( "\n", e.Data.GetFormats(false) );
MessageBox.Show( formats );
</code></pre>
<p>which will dump data formats associated with the d'n'd operation. Might help us narrowing down where the problem lies.</p>
| 35,654
|
<p>I'm asking for a suitable architecture for the following Java web application: </p>
<p>The goal is to build several web applications which all operate on the same data. Suppose a banking system in which account data can be accessed by different web applications; it can be accessed by customers (online banking), by service personal (mostly read) and by the account administration department (admin tool). These applications run as separate web applications on different machines but they use the same data and a set of common data manipulation and search queries.</p>
<p>A possible approach is to build a core application which fits the common needs of the clients, namely data storage, manipulation and search facilities. The clients can then call this core application to fulfil their requests. The requirement is the applications are build on top of a Wicket/Spring/Hibernate stack as WARs.</p>
<p>To get a picture, here are some of the possible approaches we thought of:</p>
<p>A The monolithic approach. Build one huge web application that fits all needs (this is not really an option)</p>
<p>B The API approach. Build a core database access API (JAR) for data access/manipulation. Each web application is build as a separate WAR which uses the API to access a database. There is no separate core application.</p>
<p>C RMI approach. The core application runs as a standalone application (possibly a WAR) and offers services via RMI (or HttpInvoker).</p>
<p>D WS approach. Just like C but replace RMI with Web Services</p>
<p>E OSGi approach. Build all the components as OSGi modules and which run in an OSGi container. Possibly use SpringSource dm Server or ModuleFusion. This approach was not an option for us for some reasons ...</p>
<p>Hope I could make clear the problem. We are just going the with option B, but I'm not very confident with it. What are your opinions? Any other solutions? What are the drawbacks of each solution?</p>
|
<p>B, C, and D are all just different ways to accomplish the same thing.</p>
<p>My first thought would be to simply have all consumer code connecting to a common database. This is certainly doable, and would eliminate the code you don't want to place in the middle. The drawback, of course, is that if the schema changes, all consumers need to be updated.</p>
<p>Another solution you may want to consider is giving each consumer its own database, using some sort of replication to keep them in sync.</p>
|
<p>Apart from the provided responses, if you are considering having multiple applications working with the database at the same time, consider a distributed cache as part of your solution, as well. The beauty of the distributed cache is that it can be accessed by multiple applications at the same time, apart from being distributed. I am not sure if this holds true for all of the Java variations, such as Ehcache, etc, as I do not come from a Java background.</p>
<p>What we are currently doing is abstracting the data a level further than before. We now have a DAL that can be accessed directly, but we have put a "Model Factory" in front of the DAL. The purpose of the Model Factory is to broker both the cache and the data layer, acting as a passthrough. So, the caller always calls the Model Factory and not the DAL or caching code directly. This abstraction layer will basically retrieve data from the DAL on a cache miss without adding the complexity to the API.</p>
| 43,917
|
<p>I've been creating CSS/Javascript to style an upcoming site differently on iPhone - mostly to enhance usability. On the desktop app, I use <a href="http://www.digitalia.be/software/slimbox" rel="nofollow noreferrer">slimbox</a> in combination with mootools for an image gallery. This doesn't work on iPhone because it won't show the image fullscreen (safari chrome gets in the way). The solution I have at the moment is just to display image links.</p>
<p>I was wondering if there is some way to display images fullscreen through Mobile Safari - like the App Store and Photos.app. Anyone found such a solution?</p>
|
<p>You probably already know this - but you can get rid of the address bar with:
document.body.onload = function(){setTimeout("window.scrollTo(0,1);",100);};</p>
<p>To create the illusion of a native app even more, you can disable scrolling:
document.body.ontouchmove = function(e){e.preventDefault();};</p>
|
<p>There is a meta tag, <a href="http://daringfireball.net/linked/2008/10/03/fullscreen-iphone-web-apps" rel="nofollow noreferrer">apple-mobile-web-app-capable</a>, that you can use to launch mobile safari in fullscreen mode. Keep in mind though that the user needs to add a web bookmark to their home screen in order for it to work, and any links they click on are sent to regular mobile Safari, which opens as a new application.</p>
| 46,589
|
<p>I am not sure whether is it possible to change attribute's parameter during runtime? For example, inside an assembly I have the following class</p>
<pre><code>public class UserInfo
{
[Category("change me!")]
public int Age
{
get;
set;
}
[Category("change me!")]
public string Name
{
get;
set;
}
}
</code></pre>
<p>This is a class that is provided by a third party vendor and <strong>I can't change the code</strong>. But now I found that the above descriptions are not accurate, and I want to change the "change me" category name to something else when i bind an instance of the above class to a property grid.</p>
<p>May I know how to do this?</p>
|
<p>Well you learn something new every day, apparently I lied:</p>
<blockquote>
<p>What isn’t generally realised is that
you can change attribute <strong>instance</strong> values fairly
easily at runtime. The reason is, of
course, that the instances of the
attribute classes that are created are
perfectly normal objects and can be
used without restriction. For example,
we can get the object:</p>
<pre><code>ASCII[] attrs1=(ASCII[])
typeof(MyClass).GetCustomAttributes(typeof(ASCII), false);
</code></pre>
<p>…change the value of its public variable and show that it has changed:</p>
<pre><code>attrs1[0].MyData="A New String";
MessageBox.Show(attrs1[0].MyData);
</code></pre>
<p>…and finally create another instance
and show that its value is unchanged:</p>
<pre><code>ASCII[] attrs3=(ASCII[])
typeof(MyClass).GetCustomAttributes(typeof(ASCII), false);
MessageBox.Show(attrs3[0].MyData);
</code></pre>
</blockquote>
<p><a href="http://www.vsj.co.uk/articles/display.asp?id=713" rel="noreferrer">http://www.vsj.co.uk/articles/display.asp?id=713</a></p>
|
<p>You can change Attribute values at runtime at Class level (not object):</p>
<pre><code>var attr = TypeDescriptor.GetProperties(typeof(UserContact))["UserName"].Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;
attr.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(attr, username_readonly);
</code></pre>
| 7,429
|
<p>I am creating an application in .NET that will serve as a second UI for my already-deployed Django app. For some operations users need to authenticate themselves (as Django users). I used a super-simple way to do this (without encrypting credentials for simplicity):-</p>
<p>Step 1. I created a django view that accepted the username and password through two HTTP GET parameters and passed them on to django.contrib.auth.authenticate() as keyword arguments. See the code below:
<pre>
def authentication_api(request, raw_1, raw_2):
user = authenticate(username=raw_1, password=raw_2)
if user is not None:
if user.is_active:
return HttpResponse("correct", mimetype="text/plain")
else:
return HttpResponse("disabled", mimetype="text/plain")
else:
return HttpResponse("incorrect", mimetype="text/plain")</pre></p>
<p>Step 2. I called this using the following code in .NET. The 'strAuthURL' in the following representes a simple django URL mapped to the django view above:
<pre>
Dim request As HttpWebRequest = CType(WebRequest.Create(strAuthURL), HttpWebRequest)
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
Dim reader As StreamReader = New StreamReader(response.GetResponseStream())
Dim result As String = reader.ReadToEnd()
HttpWResp.Close()</pre></p>
<p>This works flawlessly, although it is nothing more than a proof-of-concept.</p>
<p>Now I want to do this via HTTP POST so I have done the following: - </p>
<p>I created a django view for the doing authentication using POST data
<pre>
def post_authentication_api(request):
if request.method == 'POST':
user = authenticate(username=request.POST['username'], password=request.POST['password'])
if user is not None:
if user.is_active:
return HttpResponse("correct", mimetype="text/plain")
else:
return HttpResponse("disabled", mimetype="text/plain")
else:
return HttpResponse("incorrect", mimetype="text/plain")</pre></p>
<p><code>I have tested this using restclient and this view works as expected. However I can't get it to work from the .NET code below:</code>
<pre>
Dim request As HttpWebRequest = CType(WebRequest.Create(strAuthURL), HttpWebRequest)
request.ContentType = "application/x-www-form-urlencoded"
request.Method = "POST"
Dim encoding As New UnicodeEncoding
Dim postData As String = "username=" & m_username & "&password=" & m_password
Dim postBytes As Byte() = encoding.GetBytes(postData)
request.ContentLength = postBytes.Length
Try
Dim postStream As Stream = request.GetRequestStream()
postStream.Write(postBytes, 0, postBytes.Length)
postStream.Close()
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
Dim responseStream As New StreamReader(response.GetResponseStream(), UnicodeEncoding.Unicode)
result = responseStream.ReadToEnd()
response.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try</pre></p>
<p>The server is giving me a 500 internal server error. My guess is that the POST request is not properly set up in .NET. So I basically need some guidance on how to call the django view from .NET sending POST data.</p>
<p>Thanks,
CM</p>
|
<p>Looks ok to me. I recommend using Wireshark to see what your restclient is sending in the headers and and see what your app sending in the headers.</p>
|
<p>It's working now. The HTTP headers were OK, the source of the problem were the following lines:
<pre>
Dim encoding As New UnicodeEncoding
.
Dim postBytes As Byte() = encoding.GetBytes(postData)</pre></p>
<p>Essentially, this was resulting in a data stream with null bytes between the character bytes. That of course is not what Django authentication expects in the parameters. Changing to ASCIIEncoding solved the problem.</p>
<blockquote>> Looks ok to me. I recommend using Wireshark to see what your restclient is sending in the headers and and see what your app sending in the headers.</blockquote>
<p>This set me off on the right path towards troubleshooting this. I tried with Wireshark, but then used HTTP Debugger which seemed more suited for the job.</p>
<p>The right tools can save one hours!</p>
| 48,869
|
<p>I am deploying new versions of java servlets with JRun as the host. I am having difficulty finding good sources for information about JRun and tutorials about how to configure and manage it.</p>
<p>After installing JRun and opening the launcher it can't start the admin server that it creates by default...so obviously I'm running into some issues just getting started.</p>
<p><strong>edit for clarity:</strong> I'm not looking for an answer or help with a specific error but if anyone knows of good sources for information about JRun and how to work with it so I can quickly bring myself up to speed on it.</p>
|
<p><a href="http://www.adobe.com/products/jrun/productinfo/faq/eod/" rel="nofollow noreferrer">Jrun development has pretty much stopped</a>. You should look into running another application server. <a href="http://www.jboss.org/" rel="nofollow noreferrer">Jboss</a> or <a href="http://glassfish.java.net/" rel="nofollow noreferrer">Glassfish</a> are good alternatives.</p>
|
<p>This is probably going to be difficult to resolve unless you post either the error message from the log file or the list of steps that you took so far.</p>
<p>I have JRun 3.1 configured on my machine so maybe I can duplicate your issue if you give us more information.</p>
| 5,508
|
<p>I have a method that I would like to call. However, I'm looking for a clean, simple way to kill it or force it to return if it is taking too long to execute.</p>
<p>I'm using Java.</p>
<p>to illustrate:</p>
<pre><code>logger.info("sequentially executing all batches...");
for (TestExecutor executor : builder.getExecutors()) {
logger.info("executing batch...");
executor.execute();
}
</code></pre>
<p>I figure the <code>TestExecutor</code> class should <code>implement Callable</code> and continue in that direction.</p>
<p>But all i want to be able to do is stop <code>executor.execute()</code> if it's taking too long.</p>
<p>Suggestions...?</p>
<p><strong>EDIT</strong></p>
<p>Many of the suggestions received assume that the method being executed that takes a long time contains some kind of loop and that a variable could periodically be checked.
However, this is not the case. So something that won't necessarily be clean and that will just stop the execution whereever it is is acceptable.</p>
|
<p>You should take a look at these classes :
<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html" rel="noreferrer">FutureTask</a>, <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Callable.html" rel="noreferrer">Callable</a>, <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html" rel="noreferrer">Executors</a></p>
<p>Here is an example :</p>
<pre><code>public class TimeoutExample {
public static Object myMethod() {
// does your thing and taking a long time to execute
return someResult;
}
public static void main(final String[] args) {
Callable<Object> callable = new Callable<Object>() {
public Object call() throws Exception {
return myMethod();
}
};
ExecutorService executorService = Executors.newCachedThreadPool();
Future<Object> task = executorService.submit(callable);
try {
// ok, wait for 30 seconds max
Object result = task.get(30, TimeUnit.SECONDS);
System.out.println("Finished with result: " + result);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
System.out.println("timeout...");
} catch (InterruptedException e) {
System.out.println("interrupted");
}
}
}
</code></pre>
|
<p>The correct answer is, I believe, to create a Runnable to execute the sub-program, and run this in a separate Thread. THe Runnable may be a FutureTask, which you can run with a timeout ("get" method). If it times out, you'll get a TimeoutException, in which I suggest you</p>
<ul>
<li>call thread.interrupt() to attempt to end it in a semi-cooperative manner (many library calls seem to be sensitive to this, so it will probably work)</li>
<li>wait a little (Thread.sleep(300))</li>
<li>and then, if the thread is still active (thread.isActive()), call thread.stop(). This is a deprecated method, but apparently the only game in town short of running a separate process with all that this entails.</li>
</ul>
<p>In my application, where I run untrusted, uncooperative code written by my beginner students, I do the above, ensuring that the killed thread never has (write) access to any objects that survive its death. This includes the object that houses the called method, which is discarded if a timeout occurs. (I tell my students to avoid timeouts, because their agent will be disqualified.) I am unsure about memory leaks...</p>
<p>I distinguish between long runtimes (method terminates) and hard timeouts - the hard timeouts are longer and meant to catch the case when code does not terminate at all, as opposed to being slow.</p>
<p>From my research, Java does not seem to have a non-deprecated provision for running non-cooperative code, which, in a way, is a gaping hole in the security model. Either I can run foreign code and control the permissions it has (SecurityManager), or I cannot run foreign code, because it might end up taking up a whole CPU with no non-deprecated means to stop it.</p>
<pre><code>double x = 2.0;
while(true) {x = x*x}; // do not terminate
System.out.print(x); // prevent optimization
</code></pre>
| 29,747
|
<p>I've recently switched to Linux on my work machine and, new to the Linux desktop environment, I'd like to find a decent ERD tool for database design. Booting back into my Windows partition every time I need to create a diagram is going to get unpleasant quickly. I looked at Dia, but didn't see any DB tools - only UML, networking, etc.</p>
<p>Anyone have any recommendations? For what it's worth, I'm using Ubuntu (Hardy Heron).</p>
<p>Thanks.</p>
|
<p>MySQL just officially released the alpha of "MySQL Workbech for linux":</p>
<p>See the announcement here:
<a href="http://dev.mysql.com/workbench/?p=153" rel="noreferrer">MySQL Workbench 5.1 Alpha for Linux available</a>.</p>
|
<p>You can try Base from <a href="https://www.libreoffice.org/features/base/" rel="nofollow">LibreOffice</a>. It can connect to any database and you can easily create, design and write queries using visual wizards and tools.</p>
| 3,491
|
<p>I have a WCF service which will be hosted under IIS. Now I have some resources(Connections) that I create within service constructor. I need to free up those resources when IIS which is hosting the service shuts down or resets. These are not the resources that I will be clearing out every time client disconnects but they are application wide resources which will only free up when the service itself or IIS shuts down.</p>
<p>I saw another post where someone mentioned that he has created a listener to capture the events of <code>ServiceHost</code>. Can someone help me with figuring out how to get a handle of the <code>ServiceHost</code> and capture the IIS reset or IIS shutdown event and free up my resources in WCF service?</p>
|
<p>Well, I'm out of ideas, but I think that <a href="http://msdn.microsoft.com/en-us/library/bb332338.aspx" rel="nofollow noreferrer">this article</a> contains your answer in the chapter: "Accessing ServiceHost in IIS". It seems you need to build your own HostFactory because out of the box IIS uses the standard HostFactory and practically controls the creation and destruction of Hosts. By providing your own HostFactory you can add your own code to control the initialization and destruction...</p>
|
<p>The whole point of WCF services and IIS hosting is to achieve scalability and allow easy hosting. Although you could connect to events exposed by the ServiceHostBase class (see <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehostbase_events.aspx" rel="nofollow noreferrer">here</a>), I would recommend against it and analyzing if you really need those shared resources. The main reasons for asking you to re-think are: shared resources need to be thread safe (IIS can serve many requests simultaneously), so this creates a bottleneck for the scalability of your application and secondly, it's best if your services are stateless, and this includes (I guess) the usage of share resources (or application wide resources).</p>
| 44,008
|
<p>How would you convert a parapraph to hex notation, and then back again into its original string form?</p>
<p>(C#)</p>
<p>A side note: would putting the string into hex format shrink it the most w/o getting into hardcore shrinking algo's?</p>
|
<p>What exactly do you mean by "hex notation"? That usually refers to encoding binary data, not text. You'd need to encode the text somehow (e.g. using UTF-8) and then encode the binary data as text by converting each byte to a pair of characters.</p>
<pre><code>using System;
using System.Text;
public class Hex
{
static void Main()
{
string original = "The quick brown fox jumps over the lazy dog.";
byte[] binary = Encoding.UTF8.GetBytes(original);
string hex = BytesToHex(binary);
Console.WriteLine("Hex: {0}", hex);
byte[] backToBinary = HexToBytes(hex);
string restored = Encoding.UTF8.GetString(backToBinary);
Console.WriteLine("Restored: {0}", restored);
}
private static readonly char[] HexChars = "0123456789ABCDEF".ToCharArray();
public static string BytesToHex(byte[] data)
{
StringBuilder builder = new StringBuilder(data.Length*2);
foreach(byte b in data)
{
builder.Append(HexChars[b >> 4]);
builder.Append(HexChars[b & 0xf]);
}
return builder.ToString();
}
public static byte[] HexToBytes(string text)
{
if ((text.Length & 1) != 0)
{
throw new ArgumentException("Invalid hex: odd length");
}
byte[] ret = new byte[text.Length/2];
for (int i=0; i < text.Length; i += 2)
{
ret[i/2] = (byte)(ParseNybble(text[i]) << 4 | ParseNybble(text[i+1]));
}
return ret;
}
private static int ParseNybble(char c)
{
if (c >= '0' && c <= '9')
{
return c-'0';
}
if (c >= 'A' && c <= 'F')
{
return c-'A'+10;
}
if (c >= 'a' && c <= 'f')
{
return c-'A'+10;
}
throw new ArgumentOutOfRangeException("Invalid hex digit: " + c);
}
}
</code></pre>
<p>No, doing this would not shrink it at all. Quite the reverse - you'd end up with a lot more text! However, you could compress the binary form. In terms of representing arbitrary binary data as text, Base64 is more efficient than plain hex. Use <a href="http://msdn.microsoft.com/en-us/library/dhx0d524.aspx" rel="noreferrer">Convert.ToBase64String</a> and <a href="http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx" rel="noreferrer">Convert.FromBase64String</a> for the conversions.</p>
|
<p>While I can't help much on the C# implementation, I would highly recommend <a href="http://en.wikipedia.org/wiki/Lzw" rel="nofollow noreferrer">LZW</a> as a simple-to-implement data compression algorithm for you to use.</p>
| 27,038
|
<p>Navision 5.0 includes a feature to export to Word or Excel. Is it possible to make this work with OpenOffice.org Writer or Calc instead? If so, what has to be done to set it up?</p>
<p>I have been told by my Navision reseller that the feature works best with Office 2007, and export to Excel 2003 works. No mention of Office 2000 (which is what we mostly have installed currently) or OpenOffice.org. I'm hoping to be able to standardise on OpenOffice.org across the company when 3.0 is released, to avoid the expense of upgrading everyone to Microsoft Office 2007.</p>
|
<p>I know this is an old question, but I'll add the answer just in case anyone comes here:</p>
<p>You can export directly to OpenOffice without customizations. The only thing you need is to go into Tools > Manage Style Sheets... and modify the existing StyleSheets so that they open OpenCalc and OpenWrite instead of Excel and Word.</p>
<p>Note: it's been a while since I last configured it, but I seem to remember that you might need to export and reimport the stylesheets to change the associated program.</p>
<p>It's quite easy, and you can actually keep both options (Export to Excel/Export to OpenCalc) so that users who need MS Office can use Excel, while the rest use OpenCalc.</p>
<p>This answer applies to the functionality to export to Word and Excel in Dynamics Nav 5.0 and Nav 5.0SP1. I haven't tried it in Dynamics Nav 2009 (Role Tailored Client).</p>
|
<p>You should be able to export the documents to word or excel and then use OpenOffice to open the documents. No additional set up required.</p>
| 7,302
|
<p>Does using STL increase footprint significantly? Could you guys share your experience regarding this matter? What are the best practices to build a small footprint library?</p>
|
<p>There's no one answer since STL is a set of templates. Templates, by their very nature, are only compiled in when used. So you can include all of STL and if none of it is actually used, the footprint added by STL will be zero. If you have a very small app that manages to use a lot of different templates with different specializations, the footprint can be large.</p>
|
<p>On an embedded project with a 64kb limit I once did, I couldn't even link the standard C libraries. So it depends on what you need to do</p>
| 47,930
|
<p>I'm trying to connect to an MDF. I've even gone to the lengths of re-installing sql server express entirely (it is now the only flavor of SQL installed on my box, where previously I had 05 dev and express). I've verified that the paths are all correct, and thus far my google-fu hasn't helped.</p>
<p>The Full exception message is: </p>
<blockquote>
<p>Failed to generate a user instance of SQL Server due to a failure in
starting the process for the user instance. The connection will be
closed.</p>
</blockquote>
<p>The Connection string is:</p>
<pre><code><add name= "CustomerEntities"
connectionString="metadata=res://*/Data.CustomerModel.csdl|res://*/Data.CustomerModel.ssdl|res://*/Data.CustomerModel.msl;
provider=System.Data.SqlClient;
provider connection string='Data Source=.\SQLEXPRESS;
AttachDbFilename=\App_Data\CustomerDb.mdf;
Integrated Security=True;
User Instance=True'"
providerName="System.Data.EntityClient" />
</code></pre>
<h3>Additional info:</h3>
<p>Several of the references to this error I've found online do not apply to me. For example, one I've seen is where this error occurs when trying to start the user instance over remote desktop (I'm doing this locally). While another suggests that it has to do with leftover files from an old express installation ... I've looked in the prescribed locations and not found those artifacts. I also tried running <code>sp_configure 'user instances enabled', '1'</code>, but it said that it was already set to 1.</p>
|
<p>ok, it works now! guess it was a compound problem ... the steps I took to resolve it are as such:</p>
<ol>
<li>Changed the following property in the connection string (note the subtle difference): <code>AttachDbFilename=|DataDirectory|CustomerDb.mdf;</code></li>
<li>Deleted the contents of the following directory: <code>c:\Users\<user name>\AppData\Local\Microsoft\Microsoft SQL Server Data\SQLEXPRESS</code>. I thought I had looked for this before, but I had actually looked in the <code>Microsoft Sql Server</code> folder. Again, a subtle difference.</li>
</ol>
<p>Once I did these two things, the connection started working :-D</p>
|
<p>Have you tried to connect to the SQL Server instance by using SQL Management Studio?</p>
<p>If this also doesn't allow you to connect then it could be because the SQL service is not starting correctly.</p>
<p>Verify that the service is running by checking the services in the control panel.</p>
| 35,618
|
<p>I'm developing an operating system and rather than programming the kernel, I'm designing the kernel. This operating system is targeted at the x86 architecture and my target is for modern computers. The estimated number of required RAM is 256Mb or more.</p>
<p>What is a good size to make the stack for each thread run on the system? Should I try to design the system in such a way that the stack can be extended automatically if the maximum length is reached?</p>
<p>I think if I remember correctly that a page in RAM is 4k or 4096 bytes and that just doesn't seem like a lot to me. I can definitely see times, especially when using lots of recursion, that I would want to have more than 1000 integars in RAM at once. Now, the real solution would be to have the program doing this by using <code>malloc</code> and manage its own memory resources, but really I would like to know the user opinion on this.</p>
<p>Is 4k big enough for a stack with modern computer programs? Should the stack be bigger than that? Should the stack be auto-expanding to accommodate any types of sizes? I'm interested in this both from a practical developer's standpoint and a security standpoint.</p>
<p>Is 4k too big for a stack? Considering normal program execution, especially from the point of view of classes in C++, I notice that good source code tends to <code>malloc/new</code> the data it needs when classes are created, to minimize the data being thrown around in a function call.</p>
<p>What I haven't even gotten into is the size of the processor's cache memory. Ideally, I think the stack would reside in the cache to speed things up and I'm not sure if I need to achieve this, or if the processor can handle it for me. I was just planning on using regular boring old RAM for testing purposes. I can't decide. What are the options?</p>
|
<p>Stack size depends on what your threads are doing. My advice:</p>
<ul>
<li>make the stack size a parameter at thread creation time (different threads will do different things, and hence will need different stack sizes)</li>
<li>provide a reasonable default for those who don't want to be bothered with specifying a stack size (4K appeals to the control freak in me, as it will cause the stack-profligate to, er, get the signal pretty quickly)</li>
<li>consider how you will detect and deal with stack overflow. Detection can be tricky. You can put guard pages--empty--at the ends of your stack, and that will generally work. But you are relying on the behavior of the Bad Thread not to leap over that moat and start polluting what lays beyond. Generally that won't happen...but then, that's what makes the really tough bugs tough. An airtight mechanism involves hacking your compiler to generate stack checking code. As for dealing with a stack overflow, you will need a dedicated stack somewhere else on which the offending thread (or its guardian angel, whoever you decide that is--you're the OS designer, after all) will run.</li>
<li>I would strongly recommend marking the ends of your stack with a distinctive pattern, so that when your threads run over the ends (and they always do), you can at least go in post-mortem and see that something did in fact run off its stack. A page of 0xDEADBEEF or something like that is handy.</li>
</ul>
<p>By the way, x86 page sizes are generally 4k, but they do not have to be. You can go with a 64k size or even larger. The usual reason for larger pages is to avoid TLB misses. Again, I would make it a kernel configuration or run-time parameter.</p>
|
<p>Why not make the stack size a configurable item, either stored with the program or specified when a process creates another process?</p>
<p>There are any number of ways you can make this configurable.</p>
<p>There's a guideline that states "0, 1 or n", meaning you should allow zero, one or any number (limited by other constraints such as memory) of an object - this applies to sizes of objects as well.</p>
| 23,901
|
<p>I'm running Repetier Host v1.6.1 with Repetier Firmware v0.92.9. My computer is running Windows 7 Pro SP1, 64-bit.</p>
<p>If I set a print going via USB then switch to another user (note: I do not log out), then the pinter's display shows that the command buffer drops from 16 to 0 until it stops printing altogether. If I switch back to the user that is running Repetier Host then the buffer fills up again and the print job resumes.</p>
<p>Before I updated Repetier Host this didn't happen, I could leave it running while I switched users and the job would run just fine. I'm not sure why this behaviour has changed, but is there any way to get it to run properly under a background user?</p>
|
<p>Is it possible that in updating Repetier you inadvertently installed it for a single user rather than for everyone? If so, that might account for its stopping when the user is changed. </p>
|
<p>I believe what happens here is that Windows suspends the process running the print job, either due to the program not being in focus, because you switch user, or both.</p>
<p>You could try to <em>increase the priority of the print process in task manager</em>, and see if that helps.</p>
<p><strong>In Windows 7:</strong></p>
<ol>
<li>Open Task Manager</li>
<li>In the <em>Applications</em> tab, right click the application, and select <em>Go To Process</em>, which will take you to its background process in the <em>Process</em> tab.</li>
<li>Right click the process, go to <em>Set Priority</em> and select some priority higher than the current level.</li>
</ol>
<p><strong>In Windows 10:</strong></p>
<ol>
<li>Open Task Manager</li>
<li>In the <em>Processes</em> tab, right click the application, and select <em>Go To Details</em>, which will take you to its background process in the <em>Details</em> tab.</li>
<li>Right click the process, go to <em>Set Priority</em> and select some priority higher than the current level.</li>
</ol>
<p><em>PS: <a href="https://stackoverflow.com/questions/1663993/what-is-the-realtime-process-priority-setting-for">Avoid setting the priority to Realtime</a>, as that effectively will give the process full control of your computer's resources, which could kneel your computer if the program is poorly written.</em></p>
| 297
|
<p>I have a WPF user control I created that is used to show the state of tasks in my UI. I get the odd report back that the control sometimes has a nasty looking border to the left and I cannot reproduce it.</p>
<p>The control looks like this (when working) (grey tick=not run, green=OK,red cross=fail,hourglass=running);</p>
<p><a href="http://img504.imageshack.us/img504/1772/wpfgoodpw9.png" rel="nofollow noreferrer">alt text http://img504.imageshack.us/img504/1772/wpfgoodpw9.png</a></p>
<p>It looks like this when the problem occurs;</p>
<p><a href="http://img369.imageshack.us/img369/4201/wpfbadar6.png" rel="nofollow noreferrer">alt text http://img369.imageshack.us/img369/4201/wpfbadar6.png</a></p>
<p>It may have something to do with the layering of those icons, when the state changes the others are made invisible and the relevant icon is made visible. The four icons are all stacked on top of each other.</p>
<p>It could also be the background in theory, which I'll look at next. Problem is reported on both flat panel and CRT displays.</p>
<p>Any guidance greatly appreciated.</p>
<p>Update:
1) SnapsToDevicePixels does not affect the issue.
2) Grid is not used, only a canvas.</p>
|
<p>Could it have something to do with <a href="http://msdn.microsoft.com/en-us/library/aa970908.aspx" rel="nofollow noreferrer">pixel snapping</a>?</p>
|
<p>Are they in a grid? It could be related to <a href="https://stackoverflow.com/questions/267364/wpf-eliminate-transparency-between-grid-cells#267954">WPF: Eliminate transparency between grid cells</a> which we never really resolved.</p>
| 38,218
|
<p>I am having an ASP.net page in my page i am having this as my code behind files.
on first access the page the page preinit, init, load methods are called. on postbacks
the preinit, init, load methods are called.</p>
<p>My question is LoadViewstate and control state events (Overridden methods) are not firing after postbacks also</p>
<pre><code>protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
}
protected override void LoadControlState(object savedState)
{
base.LoadControlState(savedState);
}
protected void Page_Init(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
// lblName.Text = ViewState["Test"].ToString();
}
</code></pre>
|
<p>For 2.3 or after:</p>
<pre><code>class Enumerate(object):
def __init__(self, names):
for number, name in enumerate(names.split()):
setattr(self, name, number)
</code></pre>
<p>To use:</p>
<pre><code> codes = Enumerate('FOO BAR BAZ')
</code></pre>
<p><code>codes.BAZ</code> will be 2 and so on. </p>
<p>If you only have 2.2, precede this with:</p>
<pre><code> from __future__ import generators
def enumerate(iterable):
number = 0
for name in iterable:
yield number, name
number += 1
</code></pre>
<p>(<em>This was taken from <a href="http://www.velocityreviews.com/forums/t322211-enum-in-python.html" rel="noreferrer">here</a></em>)</p>
|
<p>In Python, strings are immutable and so they are better for constants than numbers. The best approach, in my opinion, is to make an object that keeps constants as strings:</p>
<pre><code>class Enumeration(object):
def __init__(self, possibilities):
self.possibilities = set(possibilities.split())
def all(self):
return sorted(self.possibilities)
def __getattr__(self, name):
if name in self.possibilities:
return name
raise AttributeError("Invalid constant: %s" % name)
</code></pre>
<p>You could then use it like this:</p>
<pre><code>>>> enum = Enumeration("FOO BAR")
>>> print enum.all()
['BAR', 'FOO']
>>> print enum.FOO
FOO
>>> print enum.FOOBAR
Traceback (most recent call last):
File "enum.py", line 17, in <module>
print enum.FOOBAR
File "enum.py", line 11, in __getattr__
raise AttributeError("Invalid constant: %s" % name)
AttributeError: Invalid constant: FOOBAR
</code></pre>
| 23,925
|
<p>I had a discussion a few weeks back with some co-workers on refactoring, and I seem to be in a minority that believes "Refactor early, refactor often" is a good approach that keeps code from getting messy and unmaintainable. A number of other people thought that it just belongs in the maintenance phases of a project.</p>
<p>If you have an opinion, please defend it.</p>
|
<p>Just like you said: refactor early, refactor often.</p>
<p>Refactoring early means the necessary changes are still fresh on my mind. Refactoring often means the changes tend to be smaller.</p>
<p>Delaying refactoring only ends up making a big mess which further makes it harder to refactor. Cleaning up as soon as I notice the mess prevents it from building up and becoming a problem later.</p>
|
<p>I think you should refactor something when you're currently working on a part of it. Means if you have to enhance function A, then you should refactor it before (and afterwards?). If you don't do anything with this function, then leave it as it is, as long as you have something else to do.</p>
<p>Do not refactor a working part of the system, unless you already have to change it.</p>
| 17,004
|
<p>I need to test a serial port application on Linux, however, my test machine only has one serial port. </p>
<p>Is there a way to add a virtual serial port to Linux and test my application by emulating a device through a shell or script?</p>
<p>Note: I cannot remap the port, it hard coded on ttys2 and I need to test the application as it is written.</p>
|
<p>Complementing the @slonik's answer.</p>
<p>You can test socat to create Virtual Serial Port doing the following procedure (tested on Ubuntu 12.04):</p>
<p><strong>Open a terminal (let's call it Terminal 0) and execute it:</strong></p>
<pre><code>socat -d -d pty,raw,echo=0 pty,raw,echo=0
</code></pre>
<p><strong>The code above returns:</strong></p>
<pre><code>2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/2
2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/3
2013/11/01 13:47:27 socat[2506] N starting data transfer loop with FDs [3,3] and [5,5]
</code></pre>
<p><strong>Open another terminal and write (Terminal 1):</strong></p>
<pre><code>cat < /dev/pts/2
</code></pre>
<p>this command's port name can be changed according to the pc. it's depends on the previous output.</p>
<pre><code>2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/**2**
2013/11/01 13:47:27 socat[2506] N PTY is /dev/pts/**3**
2013/11/01 13:47:27 socat[2506] N starting data transfer loop with FDs
</code></pre>
<p>you should use the number available on highlighted area.</p>
<p><strong>Open another terminal and write (Terminal 2):</strong></p>
<pre><code>echo "Test" > /dev/pts/3
</code></pre>
<p>Now back to Terminal 1 and you'll see the string "Test".</p>
|
<p>Combining all other amazingly useful answers, I found the below command to be VERY useful for testing on different types of Linux distros where there's no guarantee you're <a href="https://unix.stackexchange.com/questions/590302/getting-the-virtual-comport-addr-from-socat-command-with-grep?newreg=03ecb0aa86ea426d847f58952f48aa1b">going to get the same /dev/pts/#'s every time</a> and/or you need to test multiple psuedo serial devices and connections at once.</p>
<pre><code>parallel 'i="{1}"; socat -d -d pty,raw,echo=0,link=$HOME/pty{1} pty,raw,echo=0,link=$HOME/pty$(($i+1))' ::: $(seq 0 2 3;)
</code></pre>
<p>Breaking this down:</p>
<p><code>parallel</code> runs the same command for each argument supplied to it.
So for example if we run it with the <code>--dryrun</code> flag it gives us:</p>
<pre><code>i="0"; socat -d -d pty,raw,echo=0,link=$HOME/pty0 pty,raw,echo=0,link=$HOME/pty$(($i+1))
i="2"; socat -d -d pty,raw,echo=0,link=$HOME/pty2 pty,raw,echo=0,link=$HOME/pty$(($i+1))
</code></pre>
<p>This is due to the <code>$(seq x y z;)</code> at the end, where
x = start #, y = increment by, and z = end # (or # of devices you need to spawn)</p>
<p><code>parallel 'i="{1}"; echo "make psuedo_devices {1} $(($i+1))"' ::: $(seq 0 2 3;)</code></p>
<p>Outputs:</p>
<pre><code>make psuedo_devices 0 1
make psuedo_devices 2 3
</code></pre>
<p>Gathering all this together the final above command symlinks the proper psuedo devices together regardless of whats in /dev/pts/ to whatever directory supplied to socat via the <code>link</code> flag.</p>
<p><code>pstree -c -a $PROC_ID</code> gives:</p>
<pre><code>perl /usr/bin/parallel i="{1}"; socat -d -d pty,raw,echo=0,link=$HOME/pty{1} pty,raw,echo=0,link=$HOME/pty$(($i+1)) ::: 0 2
├─bash -c i="0"; socat -d -d pty,raw,echo=0,link=$HOME/pty0 pty,raw,echo=0,link=$HOME/pty$(($i+1))
│ └─socat -d -d pty,raw,echo=0,link=/home/user/pty0 pty,raw,echo=0,link=/home/user/pty1
└─bash -c i="2"; socat -d -d pty,raw,echo=0,link=$HOME/pty2 pty,raw,echo=0,link=$HOME/pty$(($i+1))
└─socat -d -d pty,raw,echo=0,link=/home/user/pty2 pty,raw,echo=0,link=/home/user/pty3
</code></pre>
<p>ls -l $HOME/pty* yield:</p>
<pre><code>lrwxrwxrwx 1 user user 10 Sep 7 11:46 /home/user/pty0 -> /dev/pts/4
lrwxrwxrwx 1 user user 10 Sep 7 11:46 /home/user/pty1 -> /dev/pts/6
lrwxrwxrwx 1 user user 10 Sep 7 11:46 /home/user/pty2 -> /dev/pts/7
lrwxrwxrwx 1 user user 10 Sep 7 11:46 /home/user/pty3 -> /dev/pts/8
</code></pre>
<p>This was all because I was trying running tests against a platform where I needed to generated a lot of mach-serial connections and to test their input/output via containerization (Docker). Hopefully someone finds it useful.</p>
| 7,545
|
<p>This is something that I have always wondered about, but never bothered to profile.</p>
<p>Is it more efficient to assign a value to a temp variable, than to keep using that value. An Example may be clearer:</p>
<pre><code>string s = reader.GetItem[0].ToString();
someClass.SomeField = s;
someOtherClass.someField = s;
</code></pre>
<p>OR</p>
<pre><code>someClass.SomeField = reader.GetItem[0].ToString();
someOtherClass.someField = reader.GetItem[0].ToString();
</code></pre>
<p>My initial thought would the top example would be more efficient as it doesn't have to access the Item collection or call ToString.</p>
<p>Would be interested to hear other peoples ideas, or definitive answer either way.</p>
|
<p>The compiler cannot know if the expression on the right-hand-side has side-effects, so it must re-evaluate it if you code it twice. Hence the first is more efficient in the sense that it will not re-do the GetItem & ToString calls.</p>
<p>So if you the programmer know that these calls are pure/idempotent, then you should write the code the first way.</p>
|
<p>Well assuming that the <code>ToString</code> function not just hands out a reference to some pre-made internal object, it must be pretty clear that the first version, where only one call to it is being made, will be the fastest. However, if this is a performance issue you should care about or not is a completely different story.</p>
<p>One issue to <strong>do</strong> think bout, however, is that the second example might render different results in the first and second line if the item is accessed/changed simultaneously from another thread. </p>
| 29,959
|
<p>I am completely new to ruby and I inherited a ruby system for a product catalogue. Most of my users are able to view everything as they should but overseas users (specifically Mexico) cannot contact the server once logged in. They are an active user. I'm sorry I cannot be more specific, and the system is private so I cannot grant access.
Has anyone had any issues similar to this before? Is it a user-end issue or a system error?</p>
|
<p>Speaking as somebody who <em>regularly</em> ends up on your user's side of the fence, the number one culprit for this symptom is "Clueless administrator". There are many, many sites which generically block either large blocks of IP space or which geolocate and carve out big portions of the world. </p>
<p>For example, a surprising number of American blogs block Asian countries (including Japan) out of a misplaced effort to avoid DDOS attacks (which actually probably originated in Russia or China but, hey, this species of administrator isn't very good on fine tuning solutions). I have to hop over to my American proxy server to access those sites.</p>
<p>So the first thing I'd do to diagnose your problems is to see whether your Mexican users are making it to the server at all, or whether they're being blocked somewhere earlier (router? firewall? etc). Then, to determine whether the problem is on your end or their end, I'd try to replicate the issue with you proxying your connection through a Mexican proxy and repeating the actions they took to cause the issue. </p>
<p>The fact that they get blocked after logging in could indicate that you have https issues , for example with an HTTPS accelerator installed [1], or it could be that your frontend server is properly serving up the static content but doing the checking on dynamic requests only.</p>
<p>[1] We've seen some <strong>really</strong> weird bugs at work caused by a malfunctioning HTTPS accelerator.</p>
|
<p>If it's working for everyone else then it would appear that the problem is not with Ruby or Rails working, since they are...</p>
<p>My first thought would be to check for a network issue: are the Mexican users all behind the same proxy server and/or firewall?</p>
<p>Is login handled within the Rails application or via some other resource? Can you see any evidence that requests from Mexican users are reaching your web server at all?</p>
| 18,362
|
<p>Looking for some help with a Labview data collection program. If I could collect 2ms of data at 8kHz (gives 16 data points) per channel (I am collecting data on 4 analog channels with an National Instruments data acquisition board). The DAQ-MX collection task gives a 1D array of 4 waveforms.</p>
<p>If I don't display the data I can do all my computation time is about 2ms and it is OK if the processing loop lags a little behind the collection loop. Updating the chart in Labview's front panel introduces an unacceptable delay. We don't need to update the display very quickly probably at 5-10Hz would be sufficient. But I don't know how to set this up.</p>
<p>My current Labview VI has three parallel loops</p>
<ol>
<li>A timed-loop for data collection</li>
<li>A loop for analysis and processing</li>
<li>A low priority loop for caching data to disk as a TDMS file</li>
</ol>
<p>Data is passed from the collection loop to the other loops using a queue. Labview examples gave me some ideas but I am stuck.</p>
<p>Any suggestions, references, ideas would be appreciated.</p>
<p>Thanks</p>
<p>Azim</p>
<p><strong><em>Follow Up Question</em></strong></p>
<p>eaolson suggests that I re-sample the data for display purposes. The data coming from the DAQ-MX read is a one dimensional array of waveforms. So I would need to somehow build or concatenate the waveform data for each channel. And then re-sample the data before updating the front panel chart. I suppose the best approach would be to queue the data and in a display loop dequeue the stack build and re-sample the data based on screen resolution and then update the chart. Would there be any other approach. I will look on
(NI Labview Forum)[<a href="http://forums.ni.com/ni/board?board.id=170]" rel="nofollow noreferrer">http://forums.ni.com/ni/board?board.id=170]</a> for more information as suggetsted by eaolson.</p>
<p><strong><em>Updates</em></strong></p>
<ol>
<li>changed acceptable update rate for graphs to 5-10Hz (thanks Underflow and eaolson)</li>
<li>disk cache loop is a low priority one (thanks eaolson)</li>
<li>Thanks for all the responses.</li>
</ol>
|
<p>Your overall architecture description sounds solid, but... getting to 30Hz for any non-trivial graph is going to be challenging. Make sure you <em>really need</em> that rate before trying to make it happen. Optimizing to that level might take some time.</p>
<p><strong>References that should be helpful:</strong></p>
<p>You can <a href="http://zone.ni.com/reference/en-XX/help/371361E-01/lvprop/pnl_defer_pnl_updts/" rel="noreferrer">defer panel updates</a>. This keeps the front panel from refreshing until you're ready for it to do so, allowing you to buffer data in the background, and only draw it occasionally.</p>
<p>You should know about <a href="http://forums.ni.com/ni/board/message?board.id=170&message.id=213981" rel="noreferrer">(a)synchronous display</a>. This option allows some control over display rates.</p>
<p>There is some <a href="http://zone.ni.com/reference/en-XX/help/371361E-01/lvconcepts/vi_execution_speed/" rel="noreferrer">general advice</a> available about speeding execution.</p>
<p>There is a (somewhat dated) <a href="http://forums.lavag.org/Chart-and-Graph-Performance-Report-t2646.html&mode=linear" rel="noreferrer">report</a> on execution speed on the LAVA forums. Googling around the LAVA forums is a great idea if you need to optimize your speed.</p>
|
<p>Television updates at about 30 Hz. Any more than that is faster than the human eye can see. 30 Hz should be at the maximum update rate you should consider for a display, not the starting point. Consider an update rate of 5-10 Hz.</p>
<p><a href="http://zone.ni.com/reference/en-XX/help/371361B-01/lvconcepts/types_of_graphs_and_charts/" rel="nofollow noreferrer">LabVIEW charts</a> append the most recent data to the historical data they store and display all the data at once. At 8 kHz, you're acquiring at least 8000 data points per channel per second. That means the array backing that graph has to continuously be resized to hold the new data. Also, even if your graph is 1000 pixels across, that means you're displaying 8 data points per screen pixel. There's not usually any reason to display any more than one data point per pixel. If you really need fast update rates, plot less data. Create an array to hold the historical data and plot only every Nth data point, where N is chosen so you're plotting, say, only a few hundred points.</p>
<p>Remember that your loops can run at different rates. It may be satisfactory to run the write-to-disk loop at a much lower frequency than the data collection rate, maybe every couple of seconds.</p>
<p>Avoid <a href="http://zone.ni.com/reference/en-XX/help/371361A-01/glang/property_node/" rel="nofollow noreferrer">property nodes</a> if you can. They run in the UI thread, which is slower than most other execution.</p>
<p>Other than that, it's really hard to offer a lot of substantial advice without seeing code or more specifics. Consider also asking your question at the <a href="http://forums.ni.com/ni/board?board.id=170" rel="nofollow noreferrer">NI LabVIEW forums</a>. There are a lot of helpful people there.</p>
| 45,005
|
<p>Can I use JavaScript to check (irrespective of scrollbars) if an HTML element has overflowed its content? For example, a long div with small, fixed size, the overflow property set to visible, and no scrollbars on the element.</p>
|
<p>Normally, you can compare the <code>client[Height|Width]</code> with <code>scroll[Height|Width]</code> in order to detect this... but the values will be the same when overflow is visible. So, a detection routine must account for this:</p>
<pre><code>// Determines if the passed element is overflowing its bounds,
// either vertically or horizontally.
// Will temporarily modify the "overflow" style to detect this
// if necessary.
function checkOverflow(el)
{
var curOverflow = el.style.overflow;
if ( !curOverflow || curOverflow === "visible" )
el.style.overflow = "hidden";
var isOverflowing = el.clientWidth < el.scrollWidth
|| el.clientHeight < el.scrollHeight;
el.style.overflow = curOverflow;
return isOverflowing;
}
</code></pre>
<p>Tested in FF3, FF40.0.2, IE6, Chrome 0.2.149.30.</p>
|
<p>This is a javascript solution (with Mootools) that will reduce the font size to fit the bounds of elHeader. </p>
<pre><code>while (elHeader.clientWidth < elHeader.scrollWidth || elHeader.clientHeight < elHeader.scrollHeight) {
var f = parseInt(elHeader.getStyle('font-size'), 10);
f--;
elHeader.setStyle('font-size', f + 'px');
}
</code></pre>
<p>The CSS of elHeader:</p>
<pre><code> width:100%;
font-size:40px;
line-height:36px;
font-family:Arial;
text-align:center;
max-height:36px;
overflow:hidden;
</code></pre>
<p>Note the wrapper of elHeader sets the width of elHeader.</p>
| 17,355
|
<p>Does anyone know how to show a asp:TreeView always expanded to the leaves? So if I have a 2-level tree, I want it to be expanded at all times. Is there a property on TreeView that does this or could you show the code snippet on how to do this?</p>
<p>Thank you very much!
Ray.</p>
|
<p>aspx.cs:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
TreeView1.ExpandAll();
}
</code></pre>
<p>if you also want to disable expand-collapse symbols in the tree:</p>
<pre><code><asp:TreeView ID="TreeView1" runat="server" ShowExpandCollapse="false">
</asp:TreeView>
</code></pre>
|
<p>And you can use an Integer if you only want to show the roots item per defualt:</p>
<pre><code> protected void Page_Load(object sender, EventArgs e)
{
TreeView1.ExpandDepth = 1;
}
</code></pre>
| 47,577
|
<p>What do I need to install to begin learning Silverlight 2? I know how to build web applications and use c#, I just have very little experience with Silverlight. I used it a little when it first came out and decided to wait until more .net integration took place. In the past I have used Visual Studio 2005 Pro. for my applications, but now get away with 2008 Express, so I don't have the full version.</p>
<p>I saw this question:</p>
<p><a href="https://stackoverflow.com/questions/60620/getting-started-with-silverlight-development">Getting started with Silverlight development</a></p>
<p>But it is from September. I want to know if anything has changed.</p>
<p>I guess the question should be: What free applications do I install to learn and use in production Silverlight 2?</p>
<p>Thank you.</p>
|
<p>See <a href="http://timheuer.com/blog/archive/2008/10/14/silverlight-2-released-officially.aspx" rel="nofollow noreferrer">Silverlight 2 Released: New controls, tools, announcements!</a>:</p>
<blockquote>
<p>The requirement to install the Silverlight Tools is that you have to have Visual Studio 2008 SP1 installed. If you are a Visual Web Developer Express user, these tools work for you as well! You still have to have SP1 of VWD Express, but you can install these tools to developer Silverlight applications. So you can have a <strong>free development tools environment for Silverlight with Visual Web Developer Express 2008 SP1 and Silverlight tools!</strong></p>
</blockquote>
<p>Here are the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=c22d6a7b-546f-4407-8ef6-d60c8ee221ed&displaylang=en" rel="nofollow noreferrer">Microsoft® Silverlight™ Tools for Visual Studio 2008 SP1</a>.</p>
<p>I don't think <a href="http://www.microsoft.com/expression/try-it/Default.aspx?filter=blend" rel="nofollow noreferrer">Blend</a> is free, but you can just author all your XAML by hand.</p>
|
<p>you might want to look at this too:</p>
<p><a href="https://stackoverflow.com/questions/203466/good-resource-for-learning-silverlight-2-development">good-resource-for-learning-silverlight-2-development</a></p>
| 49,017
|
<p>I'm getting a FileIOPermssion exception thrown when trying to create a folder in Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) on some computers. I've established that there is some form of antivirus running on the computer in question, but I haven't been able to get in contact with their IT department to find out what specifically they are using.</p>
<p>Has anyone else run into an issue an issue like this? I've tried googling for a while and haven't come up with anything. Is there something I need to do to guarantee write permissions to the ApplicationData?</p>
|
<p>I received another answer on a different forum that might be the answer but I've got to verify it first. Basically what they suggested is that the user might have installed the app on a network share instead of directly on the harddrive which would mean the application wouldn't run with full trust. The recommended fix was to use <a href="http://msdn.microsoft.com/en-us/library/3ak841sy(VS.80).aspx" rel="nofollow noreferrer">isolated storage</a> instead of ApplicationData if that was the case.</p>
<p>I'll verify that this is the problem and update if using isolated storage resolves it.</p>
|
<p>Vista or XP. Or more importantly, no problems on XP, but problems on Vista? You might be running afoul of UAC which is more stringent about checking the security permissions required for various actions. I ran into a similar problem with a printer set up program I wrote -- works fine on XP, but requires strong-naming and some GPO tweaks when run from network share in Vista.</p>
<p><strong>EDIT:</strong> Since that doesn't seem to be the problem you might check whether they have folder redirection turned on and, if so, how it is configured. It might be an issue with writing to a network share rather than local disk. Or perhaps there is a GPO that blocks write access to the ApplicationData folder -- or software installation in general.</p>
| 44,100
|
<p>I am working on a small webapp and I want to use Groovy to write some unit testing for my app. Most of my coding is done on Eclipse and I really want to run all the unit testing with the graphical test runner within Eclipse (I really like the green bar :) )</p>
<p>Sadly, after 4 hours of try-and-error, I'm still not able to setup properly. I tried to use the Eclipse Junit4 test runner to run a Groovy file with method annotated for testing using <code>@Test</code>. But it keeps complaining <code>NoClassDefFoundException</code></p>
<p>Anyone can help? </p>
<p>Here is content of my groovy file, named simpleTest.groovy</p>
<pre><code>import org.junit.Test
import static org.junit.Assert.assertEquals
class simpleTest{
@Test
void trial(){
assertEquals 6, 3+3
}
}
</code></pre>
<p>Anyone can help?</p>
|
<p>You might want to give the updated plugin a try, see the <a href="http://blog.springsource.com/2009/07/30/a-groovier-eclipse-experience" rel="nofollow noreferrer">the recent blog post</a> for more details. The theme of this alpha release is <em>providing an optimized edit/save/compile/test experience</em>, which seems to be your exact use case.</p>
<p><img src="https://i.stack.imgur.com/0joPq.png" alt="Groovy Eclipse 2.0"></p>
|
<p>Unfortunately, the Groovy Eclipse plugin is pretty horrible at giving actual helpful information to let you know what is going wrong with your setup. I'm going to assume you already did the verification to make sure the plugin is actually building your Groovy files (i.e. doing a sample with no dependencies, checking the properly output directory, etc...) After that, it's a lot of really small configuration verification...I've run into problems where the particular "runner" I'm using in Eclipse (i.e. in the Run menu) doesn't have the write class name defined there or for some reason my project didn't get the JUnit library dependency properly inserted into it. </p>
<p>Ultimately, it can be a configuration headache, but long term you'll end up saving some time and gaining some cool functionality if you can knock it out...</p>
| 3,124
|
<p>What's the simplest way to convert a Unicode codepoint into a UTF-8 byte sequence in C? The only way that springs to mind is using <code>iconv</code> to map from the UTF-32LE codepage to UTF-8, but that seems like overkill.</p>
|
<p>Unicode conversion is not a simple task. Using iconv doesn't seem like overkill at all to me. Perhaps there is a library version of iconv you can use to avoid make a system() call, if that's what you want to avoid.</p>
|
<p>UTF8 works by coding the length of the encoded codepoint into the highest bits of the encoded bytes. see <a href="http://en.wikipedia.org/wiki/UTF-8#Description" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/UTF-8#Description</a></p>
<p>I found this small function in C here <a href="http://www.deanlee.cn/programming/convert-unicode-to-utf8/" rel="nofollow noreferrer">http://www.deanlee.cn/programming/convert-unicode-to-utf8/</a> , didn't test it though.</p>
| 29,846
|
<p>Are there any real world applications written in the <a href="http://clean.cs.ru.nl/" rel="nofollow noreferrer">Clean</a> programming language? Either open source or proprietary.</p>
|
<p>This is not a direct answer, but when I checked last time (and I find the language very interesting) I didn't find anything ready for real-world.</p>
<p>The idealist in myself always wants to try out new languagages, very hot on my list (apart from the aforementioned very cool Clean Language) is currently (random order) <a href="http://www.iolanguage.com/" rel="noreferrer">IO</a>, <a href="http://www.fandev.org/" rel="noreferrer">Fan</a> and <a href="http://www.scala-lang.org/" rel="noreferrer">Scala</a>...</p>
<p>But in the meantime I then get my pragmatism out and check the <a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html" rel="noreferrer">Tiobe Index</a>. I know you can discuss it, but still: It tells me what I will be able to use in a year from now and what I possibly won't be able to use...</p>
<p>No pun intended!</p>
|
<p><a href="http://clean.cs.ru.nl/Projects" rel="nofollow noreferrer">http://clean.cs.ru.nl/Projects</a> page doesn't look promising :) It looks like just another research project with no real-world use to date.</p>
| 15,351
|
<p>Is there an elegant way to create and initialize a <code>const std::vector<const T></code> like <code>const T a[] = { ... }</code> to a fixed (and small) number of values?<br>
I need to call a function frequently which expects a <code>vector<T></code>, but these values will never change in my case.</p>
<p>In principle I thought of something like</p>
<pre><code>namespace {
const std::vector<const T> v(??);
}
</code></pre>
<p>since v won't be used outside of this compilation unit.</p>
|
<p>For C++11:</p>
<pre><code>vector<int> luggage_combo = { 1, 2, 3, 4, 5 };
</code></pre>
<p><strong>Original answer:</strong></p>
<p>You would either have to wait for C++0x or use something like <a href="http://www.boost.org/doc/libs/1_36_0/libs/assign/doc/index.html" rel="nofollow noreferrer">Boost.Assign</a> to do that.</p>
<p>e.g.:</p>
<pre><code>#include <boost/assign/std/vector.hpp>
using namespace boost::assign; // bring 'operator+=()' into scope
vector<int> v;
v += 1,2,3,4,5;
</code></pre>
|
<p>Not sure if I understood you right. I understand your question like this: you want to initialize a vector to a large number of elements. What's wrong with using <code>push_back()</code> on the vector? :-)</p>
<p>If you know the number of elements to be stored (or are sure that it will store less than the next power of 2) you can do this, if you have a vector of pointers of type X (works only with pointers):</p>
<pre><code>std::vector< X* > v;
v.reserve(num_elems);
X* p = v.begin();
for (int count = 0; count < num_elems; count++)
p[count] = some_source[count];
</code></pre>
<p>Beware of adding more than the next power of 2 elements, even if using <code>push_back()</code>. Pointers to <code>v.begin()</code> will then be invalid.</p>
| 28,657
|
<p>What's the best way to store a linked list in a MySQL database so that inserts are simple (i.e. you don't have to re-index a bunch of stuff every time) and such that the list can easily be pulled out in order?</p>
|
<p>Store an integer column in your table called 'position'. Record a 0 for the first item in your list, a 1 for the second item, etc. Index that column in your database, and when you want to pull your values out, sort by that column.</p>
<pre><code> alter table linked_list add column position integer not null default 0;
alter table linked_list add index position_index (position);
select * from linked_list order by position;
</code></pre>
<p>To insert a value at index 3, modify the positions of rows 3 and above, and then insert:</p>
<pre><code> update linked_list set position = position + 1 where position >= 3;
insert into linked_list (my_value, position) values ("new value", 3);
</code></pre>
|
<p>A list can be stored by having a column contain the offset (list index position) -- an insert in the middle is then incrementing all above the new parent and then doing an insert.</p>
| 9,098
|
<p>Given a declaration like this:</p>
<pre><code>class A {
public:
void Foo() const;
};
</code></pre>
<p>What does it mean?</p>
<p>Google turns up this:</p>
<blockquote>
<p>Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const object, and the compiler will give an error message.</p>
</blockquote>
<p>But I find that somewhat confusing; can anyone out there put it in better terms?</p>
<p>Thanks. </p>
|
<p>Consider a variation of your class <code>A</code>.</p>
<pre><code>class A {
public:
void Foo() const;
void Moo();
private:
int m_nState; // Could add mutable keyword if desired
int GetState() const { return m_nState; }
void SetState(int val) { m_nState = val; }
};
const A *A1 = new A();
A *A2 = new A();
A1->Foo(); // OK
A2->Foo(); // OK
A1->Moo(); // Error - Not allowed to call non-const function on const object instance
A2->Moo(); // OK
</code></pre>
<p>The <code>const</code> keyword on a function declaration indicates to the compiler that the function is contractually obligated not to modify the state of <code>A</code>. Thus you are unable to call non-<code>const</code> functions within <code>A::Foo</code> nor change the value of member variables.</p>
<p>To illustrate, <em>Foo()</em> may not invoke <code>A::SetState</code> as it is declared non-<code>const</code>, <code>A::GetState</code> however is ok because it is explicitly declared <code>const</code>. The member <code>m_nState</code> may not be changed either unless declared with the keyword <code>mutable</code>.</p>
<p>One example of this usage of <code>const</code> is for 'getter' functions to obtain the value of member variables.</p>
<blockquote>
<p>@1800 Information: I forgot about mutable!</p>
</blockquote>
<p>The <code>mutable</code> keyword instructs the compiler to accept modifications to the member variable which would otherwise cause a compiler error. It is used when the function needs to modify state but the object is considered logically consistent (constant) regardless of the modification.</p>
|
<p>that will cause the method to not be able to alter any member variables of the object</p>
| 7,145
|
<p>What are some good algorithms for automatically labeling text with the city / region or origin? That is, if a blog is about New York, how can I tell programatically. Are there packages / papers that claim to do this with any degree of certainty? </p>
<p>I have looked at some tfidf based approaches, proper noun intersections, but so far, no spectacular successes, and I'd appreciate ideas! </p>
<p>The more general question is about assigning texts to topics, given some list of topics.</p>
<p>Simple / naive approaches preferred to full on Bayesian approaches, but I'm open.</p>
|
<p>You're looking for a <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Named_entity_recognition" rel="noreferrer">named entity recognition</a> system, or short NER. There are <a href="http://nltk.sourceforge.net/index.php/Main_Page" rel="noreferrer">several</a> <a href="http://opennlp.sourceforge.net/index.html" rel="noreferrer">good</a> <a href="http://alias-i.com/lingpipe" rel="noreferrer">toolkits</a> available to help you out. LingPipe in particular has a very <a href="http://alias-i.com/lingpipe/demos/tutorial/ne/read-me.html" rel="noreferrer">decent tutorial</a>. <a href="http://cageclass.sourceforge.net/" rel="noreferrer">CAGEclass</a> seems to be oriented around NER on geographical place names, but I haven't used it yet.</p>
<p><a href="http://lingpipe-blog.com/2008/08/10/wheres-georgia-db-linkage-isnt-easy/" rel="noreferrer">Here's</a> a nice blog entry about the difficulties of NER with geographical places names.</p>
<p>If you're going with Java, I'd recommend using the LingPipe NER classes. OpenNLP also has some, but the former has a better documentation.</p>
<p>If you're looking for some theoretical background, <a href="http://www.linguateca.pt/documentos/gkb_technical_report.pdf" rel="noreferrer">Chavez et al. (2005)</a> have constructed an interesting syntem and documented it.</p>
|
<p><a href="http://en.wikipedia.org/wiki/Latent_semantic_mapping" rel="nofollow noreferrer">Latent Semantic Mapping</a> seems like potentially a good fit. That's just about as naive of an algorithm as you're likely to find.</p>
| 19,816
|
<p>I'm using Amazon's tools to build a web app. I'm very happy with them, but I have a security concern.</p>
<p>Right now, I'm using multiple EC2 instances, S3, SimpleDB and SQS. In order to authenticate requests to the different services, you include your <a href="https://aws-portal.amazon.com/gp/aws/developer/account/index.html?ie=UTF8&awscredential=&action=access-key" rel="nofollow noreferrer">Access Identifiers</a> (login required). </p>
<p>For example, to upload a file to S3 from an EC2 instance, your EC2 instance needs to have your <em>Access Key ID</em> and your <em>Secret Access Key</em>.</p>
<p>That basically means your username and password need to be in your instances.</p>
<p>If one of my instances were to be compromised, all of my Amazon assets would be compromised. The keys can be used upload/replace S3 and SimpleDB data, start and stop EC2 instances, etc.</p>
<p>How can I minimize the damage of a single compromised host?</p>
<p>My first thought is to get multiple identifiers per account so I can track changes made and quickly revoke the 'hacked' account. Amazon doesn't support more than one set of credentials per account.</p>
<p>My second thought was to create multiple accounts and use ACL's to control access. Unfortunately, not all the services support granting other accounts access to your data. Plus bandwidth is cheaper the more that you use, so having it all go through one account is ideal.</p>
<p>Has anyone dealt with, or at least thought about this problem?</p>
|
<p>What you can do is have a single, super-locked down 'authentication server'. The secret key only exists on this one server, and all the other servers will need to ask it for permission. You can assign your own keys to the various servers, and lock it down by IP address as well. That way if a server gets compromised, you simply revoke its key from the 'authentication server'.</p>
<p>This is possible, because of the way the AWS authentication works. Say your webserver needs to upload a file to S3. First, it will generate the AWS request, and send that request along with your custom server key to the 'authentication server'. The authentication server will authenticate the request, doing the crypto magic stuff, and return the authenticated string back to the webserver. The webserver can then use this to actually submit the request along with the file to upload to S3.</p>
|
<p>AWS offers "Consolidated Billing" which addresses your concern in the second thought.</p>
<p><a href="https://aws-portal.amazon.com/gp/aws/developer/account/index.html?ie=UTF8&action=consolidated-billing" rel="nofollow noreferrer">https://aws-portal.amazon.com/gp/aws/developer/account/index.html?ie=UTF8&action=consolidated-billing</a></p>
<p>"Consolidated Billing enables you to consolidate payment for multiple Amazon Web Services (AWS) accounts within your company by designating a single paying account. You can see a combined view of AWS costs incurred by all accounts, as well as obtain a detailed cost report for each of the individual AWS accounts associated with your paying account. Consolidated Billing may also lower your overall costs since the rolled up usage across all of your accounts could help you reach lower-priced volume tiers more quickly."</p>
| 15,818
|
<p>I am running NUnit with the project named AssemblyTest.nunit. The test calls another assembly which uses the log4net assembly. This is using nunit version 2.4.3 with the .net 2.0 framework.</p>
<p>In TestFixtureSetup I am calling log4net.Config.XmlConfigurator.Configure( ) and am getting the following error:</p>
<pre>
System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section log4net. (C:\path\to\assembly.dll.config line 7)
</pre>
<p>Is there a way to fix this without renaming the config file to 'AssemblyTest.config'?</p>
|
<p>I had the same problem because I forget to add the <em>log4net</em> definition in the <em>configSections</em> element.</p>
<p>So, if you want to put <em>log4net</em>-elements into the app.config, you need to include the <em>configSections</em> element (which tells where <em>log4net</em>-elements are defined) at the top of the config file.</p>
<p>Try it like this:</p>
<pre><code><configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
...
</log4net>
</configuration>
</code></pre>
|
<p>Create a separate config file for log4net with root element log4net.</p>
<p>In TestFixtureSetup create a FileInfo object for this config file and give it as argument to log4net.Config.XmlConfigurator.Configure( ).</p>
| 19,331
|
<p>I just got burned by the <a href="http://cygwin.com/ml/cygwin-xfree-announce/2008-11/msg00000.html" rel="nofollow noreferrer">Cygwin X11R7.4 update</a> and I find the official mailing lists hostile and clunky. So I thought I'd ask here.</p>
<p>If you have survived the upgrade (or at least made progress on fixing things), what steps did you take to make things work?</p>
|
<p>I actually found a different sort of solution and now i feel kind of stupid for even asking the question. What I did inside the Service.Outputs.Add() method was really the problem:</p>
<pre><code>public void Add(Output output)
{
OutputCollectionItem oci = new OutputCollectionItem();
oci.item = output;
this.OutputCollection.Add(oci);
}
</code></pre>
<p>What I should have done is: </p>
<pre><code>public void Add(Output output)
{
OutputCollectionItem oci = new OutputCollectionItem();
oci.itemID = output.itemID;
this.OutputCollection.Add(oci);
}
</code></pre>
|
<p>I ran into this same issue, I couldn't come up with an elegant solution. But the only solution I found was to either use "stitching," or to use reflection.</p>
<p>Stitching looks something like this.</p>
<pre><code>Person existingPerson - DB.GetPerson(1);
existingPerson.BirthDate = newPerson.BirthDate;
existingPerson.JobTitle = newPerson.JobTitle;
</code></pre>
<p>I once read something about using a callback but I can't find it for the life of me.</p>
| 38,948
|
<p>How does the data go from the MVC to the browser and back again? Does it use Microsoft's own technology like ASMX or WCF or something completely different? </p>
<p>This sounds like MVC is using a ASMX Web Service they are using but I can't seem to find any documentation which gives the real answer. </p>
|
<p>The data from the MVC app <-> browser is just plain ole HTTP request/response data. To see what this raw data is, install <a href="https://addons.mozilla.org/en-US/firefox/addon/1843" rel="nofollow noreferrer" title="FireBug:Firefox addon">Firebug</a> or <a href="https://addons.mozilla.org/en-US/firefox/addon/1843" rel="nofollow noreferrer" title="FireBug:Firefox addon">Fiddler</a> on your PC and use that to show you the raw in and out data. It's all pretty simple.</p>
<p>WebForms use this same request/response model. the browser passes some info to the webserver (ie. the Request ... like .. i want to see <a href="http://www.mysite.com/foo" rel="nofollow noreferrer">http://www.mysite.com/foo</a>) and the web server replies with some html, json, xml, binary data (for images), etc... this is the Response.</p>
<p>All browsers talk to all websites using this <em>Request/Response</em> model.</p>
<p>Now .. the difference with MVC and WebForms is HOW the webserver handles the request and how it generates the response. So they both follow the same concept, just handle it differently. For example, MVC uses controllers to determine what to show the user, while WebForms have a 'pages' which determine what data (for that page) to show.</p>
<p>So - in essence - you program your site to say:</p>
<ul>
<li>If a user goes <em>here</em>, then <em>show</em> them <em>this data</em>.</li>
</ul>
|
<p>AJAX requests are performed in the page using normal HTTP request/response. That is, in javascript the client will create a AJAX request object, send it off to a URL and it gets back a string. If that string is json, it can be eval'd and become a live javascript object.</p>
<p>The philosophy of MVC is that <em>all</em> http requests go through controllers. WCF is only for other types of web services that where the client doesn't consume html-json-css-etc.</p>
<p>You can return JSON from a controller action using the Json(object model) method on System.Web.Mvc.Controller.</p>
<p>for example</p>
<pre><code>ActionResult MyAction() {
return Json(new { success=false, for_lunch="mmm, chicken"});
}
</code></pre>
<p>That will return the json your webpage can consume.
So, that leaves the question - how does the browser call the MyAction for the json?</p>
<p>Several posts exist on this topic, and the first one i could find that did this was <a href="https://web.archive.org/web/20200813151408/http://geekswithblogs.net/michelotti/archive/2008/06/28/mvc-json---jsonresult-and-jquery.aspx" rel="nofollow noreferrer">this post</a>.</p>
<p>Hope that helps</p>
| 37,621
|
<p>We are using c++ to develop an application that runs in Windows CE 4 on an embedded system.</p>
<p>One of our constraint is that all the memory used by the application shall be allocated during <b>startup only</b>. We wrote a lot of containers and algorithms that are using only preallocated memory instead of allocating new one.</p>
<p>Do you think it is possible for us to use the boost libraries instead of our own containers in these conditions?</p>
<p>Any comments and/or advice are welcomed!</p>
<p>Thanks a lot,</p>
<p>Nic</p>
|
<p>You could write your own allocator for the container, which allocates from a fixed size static buffer. Depending on the usage patterns of the container the allocator could be as simple as incrementing a pointer (e.g. when you only insert stuff into the container once at app startup, and don't continuously add/remove elements.)</p>
|
<p>Do not use Boost. </p>
<p>It is a big library and your basic memory allocation requirements are very different from those of the libraries designers.</p>
<p>Even if you can get a current version of Boost to work according to your requirements with custom allocators it may break with a new version of Boost.</p>
<p>Feel free to look at the Boost source code though for some useful ideas but use your own implementation for what you need.</p>
| 20,116
|
<p>Given the following:</p>
<pre><code>declare @a table
(
pkid int,
value int
)
declare @b table
(
otherID int,
value int
)
insert into @a values (1, 1000)
insert into @a values (1, 1001)
insert into @a values (2, 1000)
insert into @a values (2, 1001)
insert into @a values (2, 1002)
insert into @b values (-1, 1000)
insert into @b values (-1, 1001)
insert into @b values (-1, 1002)
</code></pre>
<p>How do I query for all the values in @a that completely match up with @b? </p>
<p><code>{@a.pkid = 1, @b.otherID = -1}</code> would not be returned (only 2 of 3 values match)</p>
<p><code>{@a.pkid = 2, @b.otherID = -1}</code> would be returned (3 of 3 values match)</p>
<p>Refactoring tables can be an option.</p>
<p><strong>EDIT:</strong> I've had success with the answers from James and Tom H. </p>
<p>When I add another case in @b, they fall a little short.</p>
<pre><code>insert into @b values (-2, 1000)
</code></pre>
<p>Assuming this should return two additional rows (<code>{@a.pkid = 1, @b.otherID = -2}</code> and <code>{@a.pkid = 2, @b.otherID = -2}</code>, it doesn't work. However, for my project this is not an issue.</p>
|
<p>Probably not the cheapest way to do it:</p>
<pre><code>SELECT a.pkId,b.otherId FROM
(SELECT a.pkId,CHECKSUM_AGG(DISTINCT a.value) as 'ValueHash' FROM @a a GROUP BY a.pkId) a
INNER JOIN (SELECT b.otherId,CHECKSUM_AGG(DISTINCT b.value) as 'ValueHash' FROM @b b GROUP BY b.otherId) b
ON a.ValueHash = b.ValueHash
</code></pre>
<p>You can see, basically I'm creating a new result set for each representing one value for each Id's set of values in each table and joining only where they match.</p>
|
<p>As CQ says, a simple inner join is all you need.</p>
<pre><code>Select * -- all columns but only from #a
from #a
inner join #b
on #a.value = #b.value -- only return matching rows
where #a.pkid = 2
</code></pre>
| 12,945
|
<p>Is there a definitive scalable 3D printer? </p>
<p>I've seen examples of Chinese companies printing entire houses, and I'm curious as to printers / filaments that are intended (or at least able) be scaled up for (very) large print jobs. </p>
<p>Since most hobby printers can take hundreds of hours for something that can still be held in our hands, so I'm curious if there are any designs for printers that are meant to extrude material efficiently with a easily scalable printing area. </p>
<p>Open sourced / free is preferable; though I'm interested in <strong>any</strong> designs that exist, commercial included.</p>
|
<p>One big challenge with scaling anything up (or down), is that not all properties or characteristics scale linearly.</p>
<p>Consider a trivial case: a small cube. If you double the size, you've quadrupled the surface area and octupled the weight.</p>
<p>If you take a desktop-sized 3d printer design, and just double the size, it will weigh 8 times as much. But all the bolts holding it together are only 4 times as strong. So weight-bearing bolts are effectively under twice the strain (per unit of cross-sectional area); the exact factor depends of lots of things (orientation, leverage, etc).</p>
<p>If you scale up by 10x, they'll potentially be under 10 times greater stress, and probably snap.</p>
<p>Many, many parts will have similar issues: Drive belts that are twice as wide and twice as thick will still have 1/2 the (relative) strength -- and stiffness for the motors to overcome. </p>
<p>The stepper motors have to move 8 times the weight, <em>and</em> you'll want them to move far, far faster. But steppers lose torque when you spin them faster.</p>
<p>My main printer is pretty much a MendelMax 2, but the Y axis is about 6 times bigger (X and Z are normal). On MM2 the whole build platform moves along Y -- on my printer it weighs far more than on a regular-size MM2 -- it's 6 times the mass just because of size, besides that it has to be much stiffer to avoid sagging over that distance. I went to a larger motor, but it could still barely move the axis. I eventually got it to move at pretty normal speed, but to print long objects it really should be 6 times faster or so.</p>
<p>That would require an amazing motor -- and really big electronics to drive it.</p>
<p>Another challenge is the printing material -- 20mm diameter PLA fiber would be really impressive, but a little hard to find, and a spool would be hard to lift. The power needed to melt it fast enough would be impressive, too. Bridge and house printers I've seen in reports, use pumped concrete through about a 100mm wide nozzle (I have no idea what the nozzle is made of, to stand up to the abrasion). See <a href="http://www.wired.co.uk/news/archive/2015-09/21/giant-3d-printer-builds-houses" rel="nofollow noreferrer">Watch this giant 3D printer build a house</a> for some cool pictures and video.</p>
<p>Scaling up is a fascinating project -- but it's harder than it looks.</p>
|
<p>As far as I know, right now, all the "3D printers" that can print houses, bridges, etc. are experimental models (and sometimes, vey elaborate art projects) - they just don't exist except as one-off creations designed as a proof-of-concept showing this can be done.</p>
<p>Maybe some of those project published their plans and code but they are not designed for mass production or general use, even if you manage to build another copy of one of them it will probably be able to print just the same project the original printed. </p>
<p>You specifically asked about speed, material and build area:</p>
<p><strong>Speed:</strong> the speed really depends on the size of the printer's nozzle, the typical desktop printer has a 0.4mm nozzle, if you replace it with a 1mm nozzle the printer will be approximately twice as fast (1.25 nozzle area vs 3.14 nozzle area, assuming you have an hotend designed for larger nozzles that can melt the plastic fast enough).</p>
<p>Now, the "house printer" does not use a standard desktop hotend (see material below) and buildings don't have fine details so you can make the head much larger.</p>
<p>However, as far as I know the early prototypes are still much slower then conventional construction methods.</p>
<p><strong>Material:</strong> houses are typically not made of plastic, the printers I know of have welding equipment instead of an hotend and extrude steel</p>
<p>There are probably other methods but I bet all of them use typical construction materials such as steel and not thermoplastic.</p>
<p><strong>Size:</strong> and last but not least, it's obviously not practical to build a printer with as house sized platform, the house printers are actually relatively small robots that travel across the construction project, leaving material behind them and then climb over the previous layer to print the next part.</p>
| 200
|
<p>how do i get a list of user that have completed or not completed or not responded to a survey. </p>
<p>so i have a survey, lets say "survey A". in this survey i have a list of people or groups that must fill the survey. sharepoint already gives us a list of respondents, but i want to make a list of people that have not responded or not completed the survey.</p>
<p>i'm using c#, thanks..</p>
|
<pre><code>bool isSubset = !t2.Except(t1).Any();
</code></pre>
|
<p>Try this</p>
<pre><code>static bool IsSubSet<A>(A[] set, A[] toCheck) {
return set.Length == (toCheck.Intersect(set)).Count();
}
</code></pre>
<p>The idea here is that Intersect will only return the values that are in both Arrays. At this point if the length of the resulting set is the same as the original set, then all elements in "set" are also in "check" and therefore "set" is a subset of "toCheck"</p>
<p>Note: My solution does not work if "set" has duplicates. I'm not changing it because I don't want to steal other people's votes.</p>
<p>Hint: I voted for Cameron's answer. </p>
| 43,158
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.