instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p><a href="http://www.djangoproject.com/" rel="noreferrer">Django</a> view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach.</p> <p>For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc...</p> <p>One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea? </p>
<p>I've created and used my own generic view classes, defining <strong><code>__call__</code></strong> so an instance of the class is callable. I really like it; while Django's generic views allow some customization through keyword arguments, OO generic views (if their behavior is split into a number of separate methods) can have much more fine-grained customization via subclassing, which lets me repeat myself a lot less. (I get tired of rewriting the same create/update view logic anytime I need to tweak something Django's generic views don't quite allow).</p> <p>I've posted some code at <a href="http://www.djangosnippets.org/snippets/1009/" rel="noreferrer">djangosnippets.org</a>.</p> <p>The only real downside I see is the proliferation of internal method calls, which may impact performance somewhat. I don't think this is much of a concern; it's rare that Python code execution would be your performance bottleneck in a web app.</p> <p><strong>UPDATE</strong>: Django's own <a href="http://docs.djangoproject.com/en/dev/topics/class-based-views/" rel="noreferrer">generic views</a> are now class-based.</p> <p><strong>UPDATE</strong>: FWIW, I've changed my opinion on class-based views since this answer was written. After having used them extensively on a couple of projects, I feel they tend to lead to code that is satisfyingly DRY to write, but very hard to read and maintain later, because functionality is spread across so many different places, and subclasses are so dependent on every implementation detail of the superclasses and mixins. I now feel that <a href="https://docs.djangoproject.com/en/dev/ref/template-response/" rel="noreferrer">TemplateResponse</a> and view decorators is a better answer for decomposing view code.</p>
<p>Sounds to me like you're trying to combine things that shouldn't be combined. If you need to do different processing in your view depending on if it's a User or Group object you're trying to look at then you should use two different view functions.</p> <p>On the other hand there can be common idioms you'd want to extract out of your object&#95;detail type views... perhaps you could use a decorator or just helper functions?</p> <p>-Dan</p>
2,315
<p>I have a update method in my data layer such this:</p> <pre><code>public clacc datalayerSec_User private objUIData as new UIData Public Function Update(ByVal objUser As SEC_USER) As Boolean Try objUIData.SEC_USERs.Attach(objUser) objUIData.Refresh(RefreshMode.KeepCurrentValues, objUser) objUIData.SubmitChanges(ConflictMode.ContinueOnConflict) Return True Catch ex As Exception Throw ex End Try End Function end class </code></pre> <p>And I write this code to update my data:</p> <pre><code>Dim tmpUser As New UI_Class.BAL.Security.cls_SEC_USER Dim tblUser = tmpUser.GetAll.SingleOrDefault(Function(x) x.DS_OPENID = pOpenID) tblUser.DT_LAST_LOGIN = DateTime.Now tmpUser.Update(tblUser) </code></pre> <p>When I run it, I have this error message: Cannot attach an entity that already exists.</p> <p>How can it be fixed?</p>
<p>The easiest way to get around this issue is to use the same DataContext when retrieving the user object and updating.</p> <p>In general, a DataContext should be kept alive for a "unit of work", in other words, you use it to retrieve whatever object you want to change, then change its properties, and then just do SubmitChanges() on the DataContext. No need to reattach the entity to the DataContext, since it already has a reference to it.</p> <p>My VB skills are none existing, but something like this should work (note: very crude pseudo code coming up, things like properly disposing of the DataContext is recommended):</p> <pre><code>class cls_SEC_USER { private _UIData = new UIData(); public User SingleOrDefault(int x) { return _UIData.Users.SingleOrDefault(y =&gt; y.UserId == x); } public void Update(User u) { _UIData.SubmitChanges(); } } // .......... cls_SEC_USER tmpUser = new cls_SEC_USER(); User u = tmpUser.SingleOrDefault(4); if(u != null) { u.DT_LAST_LOGIN = DateTime.Now; tmpUser.Update(u); } </code></pre> <p><a href="http://borrell.parivedasolutions.com/2008/02/linq-to-sql-updating-in-aspnet-right.html" rel="nofollow noreferrer">Brian Orrell has a pretty good run-down</a> of the issues that you are experiencing, if you want to dig in deeper. </p>
<p>I dont know the answer to you question, and I have been stuck with the same issue too, but I adopted a simple strategy to prevent these little issues.</p> <p>Instead of trying to attach/detach, fetch the actual object as soon as possible; this works quite well in web scenario's.</p>
47,468
<p>I want to select the topmost element in a document that has a given namespace (prefix).</p> <p>More specifically: I have XML documents that either start with /html/body (in the XHTML namespace) or with one of several elements in a particular namespace. I effectively want to strip out /html/body and just return the body contents OR the entire root namespaced element. </p>
<p>In XPath 2.0 and XQuery 1.0 you can test against the namespace prefix using the <a href="http://www.w3.org/TR/xquery-operators/#func-in-scope-prefixes" rel="noreferrer">in-scope-prefixes()</a> function in a predicate. e.g.</p> <pre><code>//*[in-scope-prefixes(.)='html'] </code></pre> <p>If you cant use v2, in XPath 1.0 you can use the <a href="http://www.w3.org/TR/xpath#function-namespace-uri" rel="noreferrer">namespace-uri()</a> function to test against the namespace itself. e.g.</p> <pre><code>//*[namespace-uri()='http://www.w3c.org/1999/xhtml'] </code></pre>
<p>The XPath expression that I want is:</p> <pre><code>/html:html/html:body/node()|/foo:* </code></pre> <p>Where the "html" prefix is mapped to the XHTML namespace, and the "foo" prefix is mapped to my target namespace.</p>
13,764
<p>I've written a control that inherits from the <code>System.Web.UI.WebControls.DropDownList</code> and so I don't have any code in front for this control, but I still want to set the OutputCache directive. I there any way to set this in the C# code, say with an attribute or something like that? </p> <p>I'm particularly hoping to be able to replicate the <code>VaryByParam</code> property</p>
<p>I realize this is an incredibly old question but it is still worthy of an answer.</p> <p>What you are talking about isn't a User Control it is a Custom Control. What you want to do with the OutputCache can be done simply with the Context Cache.</p> <p>In your code where you are getting the data and binding to your DropDownList do something like this:</p> <pre><code> List&lt;Object&gt; listOfObjects = null; //assuming a List of Objects... it doesn't matter whatever type of data you use if (Context.Cache["MyDataCacheKey"] == null) { // data not cached, load it from database listOfObjects = GetDataFromDB(); //add your data to the context cache with a sliding expiration of 10 minutes. Context.Cache.Add("MyDataCacheKey", listOfObjects, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10.0), System.Web.Caching.CacheItemPriority.Normal, null); } else listOfObjects = (List&lt;Object&gt;)Context.Cache["MyDataCacheKey"]; DropDownList1.DataSource = listOfObjects; DropDownList1.DataBind(); </code></pre>
<pre><code>Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Server); Response.Cache.SetValidUntilExpires(true); </code></pre>
10,439
<p>I'm using HTTPService with a POST operation to submit a Base64 encoded file (taken from bitmap data within the app) but I could really do with getting some idea of the progress of the POST operation (e.g. like the FileReference.upload()).</p> <p>I don't think this is possible, but it would be awesome if it is (via any means, I'm willing to change my setup to get this).</p>
<p>Do not use HTTPService. Use URLRequest, URLLoader, and URLVariables.</p> <p>If your using an HTTPService tag, get ride of it and replace it with a Script tag filled with something like ...</p> <pre><code> private function forYou() : void{ var req : URLRequest = new URLRequest("PUT YOUR URL HERE") var loader : URLLoader = new URLLoader(); var params : URLVariables = new URLVariables(); params.WHATEVER = WHATEVER YOU WANT IT TO BE; req.data = params; req.method = URLRequestMethod.POST; loader.addEventListener(ProgressEvent.PROGRESS, YOUR LISTENER FUNCTION NAME); loader.load(req); } </code></pre> <p>Assign this function name to the creationComplete attribute of the root tag.</p> <p>If your not using an HTTPService tag, just get ride of the HTTPService object in your actionscript and use the above code.</p>
<p>This worked well for me to consume a REST web service:</p> <p><a href="http://code.google.com/p/as3httpclient/wiki/Links" rel="nofollow noreferrer">http://code.google.com/p/as3httpclient/wiki/Links</a></p> <p><a href="http://www.abdulqabiz.com/blog/archives/flash_and_actionscript/http_authentica.php" rel="nofollow noreferrer">Example</a></p>
49,515
<p>If anyone has experience using Oracle text (<code>CTXSYS.CONTEXT</code>), I'm wondering how to handle user input when the user wants to search for names that may contain an apostrophe.</p> <p>Escaping the ' seems to work in some cases, but not for 's at the end of the word - s is in the list of stop words, and so seems to get removed.</p> <p>We currently change simple query text (i.e. anything that's just letters) to <code>%text%</code>, for example: </p> <pre><code>contains(field, :text) &gt; 0 </code></pre> <p>A search for <strong>O'Neil</strong> works, but <strong>Joe's</strong> doesn't.</p> <p>Has anyone using Oracle Text dealt with this issue?</p>
<p>Escape all special characters with backslashes. Curly braces won't work with substring searches as they define complete tokens. Eg %{ello}% won't match the token 'Hello' </p> <p>Escaped space characters will be included in the search token, so the search string '%stay\ near\ me%' will be treated as a literal string "stay near me" and will not invoke the 'near' operator.</p> <p>If you are indexing short strings (like names, etc ) and you want Oracle Text to behave exactly as the like operator, you must write your own lexer that won't create tokens for individual words. (Unfortunately CATSEARCH does not support substring search...)</p> <p>It is probably a good idea to change the searches to use oracle text's semantics, with token matching, but for some applications, the wildcard expansion of multiple (short) tokens and numeric tokens will create too many hits for search strings that the users reasonably would expect to work. </p> <p>Eg, a search for "%I\ AM\ NUMBER\ 9%" will most likely fail if there are a lot of numeric tokens in the indexed data, since all tokens ending with 'I' and starting with '9' must be searched and merged before the result can be returned. </p> <p>'I' and 'AM' is probably also in the default stoplist and will be totally ignored, so for this hypothetical application, a null stoplist may be used if these tokens are important.</p>
<p>Forget about sanitizing. Why? Refer to <a href="http://en.wikipedia.org/wiki/SQL_injection" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/SQL_injection</a> .</p> <p>It depends on the kind of database interface API you are using. Perl DBI, ODBC, JDBC support parameterized queries or prepared statements. If you're using a native DBI and it doesn't support it, then God bless you.</p>
27,019
<p>I have read the GOLD Homepage ( <a href="http://www.devincook.com/goldparser/" rel="nofollow noreferrer">http://www.devincook.com/goldparser/</a> ) docs, FAQ and Wikipedia to find out what practical application there could possibly be for GOLD. I was thinking along the lines of having a programming language (easily) available to my systems such as ABAP on SAP or X++ on Axapta - but it doesn't look feasible to me, at least not easily - even if you use GOLD.</p> <p>The final use of the parsed result produced by GOLD escapes me - what do you do with the result of the parse?</p> <p>EDIT: A practical example (description) would be great.</p>
<p>Parsing really consists of two phases. The first is "lexing", which convert the raw strings of character in to something that the program can more readily understand (commonly called tokens).</p> <p>Simple example, lex would convert:</p> <p>if (a + b > 2) then</p> <p>In to: </p> <pre> IF_TOKEN LEFT_PAREN IDENTIFIER(a) PLUS_SIGN IDENTIFIER(b) GREATER_THAN NUMBER(2) RIGHT_PAREN THEN_TOKEN </pre> <p>The parse takes that stream of tokens, and attempts to make yet more sense out of them. In this case, it would try and match up those tokens to an IF_STATEMENT. To the parse, the IF _STATEMENT may well look like this:</p> <pre> IF ( BOOLEAN_EXPRESSION ) THEN </pre> <p>Where the result of the lexing phase is a token stream, the result of the parsing phase is a Parse Tree.</p> <p>So, a parser could convert the above in to:</p> <pre> if_statement | v boolean_expression.operator = GREATER_THAN | | | v V numeric_constant.string="2" expression.operator = PLUS_SIGN | | | v v identifier.string = "b" identifier.string = "a" </pre> <p>Here you see we have an IF_STATEMENT. An IF_STATEMENT has a single argument, which is a BOOLEAN_EXPRESSION. This was explained in some manner to the parser. When the parser is converting the token stream, it "knows" what a IF looks like, and know what a BOOLEAN_EXPRESSION looks like, so it can make the proper assignments when it sees the code.</p> <p>For example, if you have just:</p> <p>if (a + b) then</p> <p>The parser could know that it's not a boolean expression (because the + is arithmetic, not a boolean operator) and the parse could throw an error at this point.</p> <p>Next, we see that a BOOLEAN_EXPRESSION has 3 components, the operator (GREATER_THAN), and two sides, the left side and the right side.</p> <p>On the left side, it points to yet another expression, the "a + b", while on the right is points to a NUMERIC_CONSTANT, in this case the string "2". Again, the parser "knows" this is a NUMERIC constant because we told it about strings of numbers. If it wasn't numbers, it would be an IDENTIFIER (like "a" and "b" are).</p> <p>Note, that if we had something like:</p> <p>if (a + b > "XYZ") then</p> <p>That "parses" just fine (expression on the left, string constant on the right). We don't know from looking at this whether this is a valid expression or not. We don't know if "a" or "b" reference Strings or Numbers at this point. So, this is something the parser can't decided for us, can't flag as an error, as it simply doesn't know. That will happen when we evaluate (either execute or try to compile in to code) the IF statement.</p> <p>If we did:</p> <p>if [a > b ) then</p> <p>The parser can readily see that syntax error as a problem, and will throw an error. That string of tokens doesn't look like anything it knows about.</p> <p>So, the point being that when you get a complete parse tree, you have some assurance that at first cut the "code looks good". Now during execution, other errors may well come up.</p> <p>To evaluate the parse tree, you just walk the tree. You'll have some code associated with the major nodes of the parse tree during the compile or evaluation part. Let's assuming that we have an interpreter.</p> <pre><code>public void execute_if_statment(ParseTreeNode node) { // We already know we have a IF_STATEMENT node Value value = evaluate_expression(node.getBooleanExpression()); if (value.getBooleanResult() == true) { // we do the "then" part of the code } } public Value evaluate_expression(ParseTreeNode node) { Value result = null; if (node.isConstant()) { result = evaluate_constant(node); return result; } if (node.isIdentifier()) { result = lookupIdentifier(node); return result; } Value leftSide = evaluate_expression(node.getLeftSide()); Value rightSide = evaluate_expression(node.getRightSide()); if (node.getOperator() == '+') { if (!leftSide.isNumber() || !rightSide.isNumber()) { throw new RuntimeError("Must have numbers for adding"); } int l = leftSide.getIntValue(); int r = rightSide.getIntValue(); int sum = l + r; return new Value(sum); } if (node.getOperator() == '&gt;') { if (leftSide.getType() != rightSide.getType()) { throw new RuntimeError("You can only compare values of the same type"); } if (leftSide.isNumber()) { int l = leftSide.getIntValue(); int r = rightSide.getIntValue(); boolean greater = l &gt; r; return new Value(greater); } else { // do string compare instead } } } </code></pre> <p>So, you can see that we have a recursive evaluator here. You see how we're checking the run time types, and performing the basic evaluations.</p> <p>What will happen is the execute_if_statement will evaluate it's main expression. Even tho we wanted only BOOLEAN_EXPRESION in the parse, all expressions are mostly the same for our purposes. So, execute_if_statement calls evaluate_expression.</p> <p>In our system, all expressions have an operator and a left and right side. Each side of an expression is ALSO an expression, so you can see how we immediately try and evaluate those as well to get their real value. The one note is that if the expression consists of a CONSTANT, then we simply return the constants value, if it's an identifier, we look it up as a variable (and that would be a good place to throw a "I can't find the variable 'a'" message), otherwise we're back to the left side/right side thing.</p> <p>I hope you can see how a simple evaluator can work once you have a token stream from a parser. Note how during evaluation, the major elements of the language are in place, otherwise we'd have got a syntax error and never got to this phase. We can simply expect to "know" that when we have a, for example, PLUS operator, we're going to have 2 expressions, the left and right side. Or when we execute an IF statement, that we already have a boolean expression to evaluate. The parse is what does that heavy lifting for us.</p> <p>Getting started with a new language can be a challenge, but you'll find once you get rolling, the rest become pretty straightforward and it's almost "magic" that it all works in the end.</p> <p>Note, pardon the formatting, but underscores are messing things up -- I hope it's still clear.</p>
<p>GOLD can be used for any kind of application where you have to apply context-free grammars to input.</p> <p>elaboration:</p> <p>Essentially, CFGs apply to all programming languages. So if you wanted to develop a scripting language for your company, you'd need to write a parser- or get a parsing program. Alternatively, if you wanted to have a semi-natural language for input for non-programmers in the company, you could use a parser to read that input and spit out more "machine-readable" data. Essentially, a context-free grammar allows you to describe far more inputs than a regular expression. The GOLD system apparently makes the parsing problem somewhat easier than lex/yacc(the UNIX standard programs for parsing).</p>
26,082
<p>I recently read this Question about <a href="https://stackoverflow.com/questions/3630/sqlite-vs-mysql">SQLite vs MySQL</a> and the answer pointed out that SQLite doesn't scale well and the official website <a href="http://www.sqlite.org/whentouse.html" rel="noreferrer">sort-of confirms this</a>, however.</p> <p>How scalable is SQLite and what are its upper most limits?</p>
<p>Yesterday I released a small site<sup>*</sup> to track your rep that used a shared SQLite database for all visitors. Unfortunately, even with the modest load that it put on my host it ran quite slowly. This is because the entire database was locked every time someone viewed the page because it contained updates/inserts. I soon switched to MySQL and while I haven't had much time to test it out, it seems much more scaleable than SQLite. I just remember slow page loads and occasionally getting a database locked error when trying to execute queries from the shell in sqlite. That said, I am running another site from SQLite just fine. The difference is that the site is static (i.e. I'm the only one that can change the database) and so it works just fine for concurrent reads. Moral of the story: only use SQLite for websites where updates to the database happen rarely (less often than every page loaded).</p> <p><strong>edit</strong>: I just realized that I may not have been fair to SQLite - I didn't index any columns in the SQLite database when I was serving it from a web page. This partially caused the slowdown I was experiencing. However, the observation of database-locking stands - if you have particularly onerous updates, SQLite performance won't match MySQL or Postgres.</p> <p><strong>another edit:</strong> Since I posted this almost 3 months ago I've had the opportunity to closely examine the scalability of SQLite, and with a few tricks it can be quite scalable. As I mentioned in my first edit, database indexes dramatically reduce query time, but this is more of a general observation about databases than it is about SQLite. However, there is another trick you can use to speed up SQLite: <a href="http://www.sqlite.org/lang_transaction.html" rel="noreferrer">transactions</a>. Whenever you have to do multiple database writes, put them inside a transaction. Instead of writing to (and locking) the file each and every time a write query is issued, the write will only happen once when the transaction completes.</p> <p>The site that I mention I released in the first paragraph has been switched back to SQLite, and it's running quite smoothly once I tuned my code in a few places.</p> <p><sup>* the site is no longer available</sup></p>
<p>SQLite's website (the part that you referenced) indicates that it can be used for a variety of multi-user situations.</p> <p>I would say that it can handle quite a bit. In my experience it has always been very fast. Of course, you need to index your tables and when coding against it, you need to make sure you use parameritized queries and the like. Basically the same stuff you would do with any database to improve performance.</p>
7,870
<p>What is the best way of creating an alphabetically sorted list in Python?</p>
<p>Basic answer:</p> <pre><code>mylist = ["b", "C", "A"] mylist.sort() </code></pre> <p>This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the <a href="http://docs.python.org/library/functions.html#sorted" rel="noreferrer"><code>sorted()</code></a> function:</p> <pre><code>for x in sorted(mylist): print x </code></pre> <p>However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter <code>key</code> to specify custom sorting order (the alternative, using <code>cmp</code>, is a deprecated solution, as it has to be evaluated multiple times - <code>key</code> is only computed once per element).</p> <p>So, to sort according to the current locale, taking language-specific rules into account (<a href="http://docs.python.org/library/functools.html#functools.cmp_to_key" rel="noreferrer"><code>cmp_to_key</code></a> is a helper function from functools):</p> <pre><code>sorted(mylist, key=cmp_to_key(locale.strcoll)) </code></pre> <p>And finally, if you need, you can specify a <a href="http://docs.python.org/library/locale.html" rel="noreferrer">custom locale</a> for sorting:</p> <pre><code>import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale assert sorted((u'Ab', u'ad', u'aa'), key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad'] </code></pre> <p>Last note: you will see examples of case-insensitive sorting which use the <code>lower()</code> method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:</p> <pre><code># this is incorrect! mylist.sort(key=lambda x: x.lower()) # alternative notation, a bit faster, but still wrong mylist.sort(key=str.lower) </code></pre>
<p>Suppose <code>s = "ZWzaAd"</code> </p> <p>To sort above string the simple solution will be below one.</p> <pre><code>print ''.join(sorted(s)) </code></pre>
5,683
<p>In multi-threaded code, when an instance may be read or written by multiple threads, they need to be locked on to perform these operations safely.</p> <p>To avoid the repetition of creating an object to lock on and writing a bunch of lock statements through code, I've created a generic class to handle the locking. </p> <p>Am I missing anything, conceptually? This should work, right?</p> <pre><code>public class Locked&lt;T&gt; where T : new() { private readonly object locker = new object(); private T value; public Locked() : this(default(T)) { } public Locked(T value) { this.value = value; } public T Get() { lock (this.locker) { return this.value; } } public void Set(T value) { lock (this.locker) { this.value = value; } } } </code></pre> <p>And an example of it being used in a class:</p> <pre><code>private Locked&lt;bool&gt; stopWorkerThread = new Locked&lt;bool&gt;(); public void WorkerThreadEntryPoint() { while (true) { if (this.stopWorkerThread.Get()) { break; } </code></pre> <p>Also, how would I test something like this, in an automated way (e.g. create a unit test)?</p> <p>Lastly, what can I do to implement a ++ and -- operator, to avoid this:</p> <pre><code> this.runningThreads.Set(this.runningThreads.Get() + 1); </code></pre>
<p>That only locks for the duration of the get/set; of course, in many common cases this will be atomic anyway, simply due to to data size.</p> <p>However, in reality most locks need to span more than this, in the same way that collections locking over just the Add etc don't help much - a caller typically needs a single lock to span the "is it there? if so update, else add" sequence.</p> <p>For something as simple as a bool, "volatile" might solve the problem a lot more simply - especially if it is just for a loop exit.</p> <p>You might also want to consider [MethodImpl(MethodImplOptions.Synchronized)] - although personally I prefer a private lock object (like you have used) to prevent issues with external people locking on the object (the above uses "this" as the lock).</p> <p>For unit testing this, you'd need something to prove it broken first - which would be hard since the operations are so small (and already atomic for most data types). One of the other things it avoids (that volatile also fixes) is caching in a register, but again that is an optimisation and hard to force to prove it is broken.</p> <p>If you are interested in a lock-wrapper, you might consider existing code like <a href="http://www.yoda.arachsys.com/csharp/miscutil/usage/locking.html" rel="nofollow noreferrer">this</a>.</p>
<p>Your code above has quite a few potential and real multi-threading issues, and I wouldn't use something like it in a real-world situation. For example:</p> <pre><code>this.runningThreads.Set(this.runningThreads.Get() + 1); </code></pre> <p>There is a pretty obvious race condition here. When the <code>Get()</code> call returns, the object is no longer locked. To do a real post or pre increment, the counter would need to be locked from before the <code>Get</code> to after the <code>Set</code>.</p> <p>Also you don't always need to do a full lock if all you are doing is synchronous reads.</p> <p>A better lock interface would (I think) require you to explicitly lock the instance where you need to do it. My experience is mainly with C++ so I can't recommend a full implementation, but my preferred syntax might look something like this:</p> <pre><code>using (Locked&lt;T&gt; lock = Locked&lt;T&gt;(instance)) { // write value instance++; } // read value print instance; </code></pre>
20,695
<p>What I'm doing is I have a full-screen form, with no title bar, and consequently lacks the minimize/maximize/close buttons found in the upper-right hand corner. I'm wanting to replace that functionality with a keyboard short-cut and a context menu item, but I can't seem to find an event to trigger to minimize the form.</p>
<pre><code>private void Form1_KeyPress(object sender, KeyPressEventArgs e) { if(e.KeyChar == 'm') this.WindowState = FormWindowState.Minimized; } </code></pre>
<pre><code>this.MdiParent.WindowState = FormWindowState.Minimized; </code></pre>
9,475
<p>I'm working on a code base in which we have several configurable types. One of those types is 64 bit integer. When we compile for platforms that have no native 64 bit integer type, we simple represent 64 bit integers using a struct similar to</p> <pre><code>typedef struct { unsigned int hi, lo; } int64; </code></pre> <p>In order to make this type useful, all common operations are defined as functions such as</p> <pre><code>int64 int64_add(int64 x, int64 y); </code></pre> <p>On platforms where a native 64 bit integer type is available, these operations simply look like</p> <pre><code>#define int64_add(x, y) ((x) + (y)) </code></pre> <p>Anyway, on to the question. I am implementing some functionality regarding time and I want to represent my time using the 64 bit integer:</p> <pre><code>typedef int64 mytime; </code></pre> <p>I also want all the common operations available to the int64 type to be available for my time type as well:</p> <pre><code>#define mytime_add(x, y) (mytime) int64_add((int64) (x), (int64) (y)) </code></pre> <p>The problem with this is that the casts between the types mytime and int64 isn't allowed in C (as far as I can tell anyhow). Is there any way to do this without having to reimplement all the add, sub, mul, div, etc functions for the mytime type?</p> <p>One option is of course to never do the mytime typedef and simply use int64 everywhere I need to represent time. The problem with this is that I'm not sure if I always want to represent time as a 64 bit integer. Then there's the issue of readable code as well... :-)</p>
<p>Do you really need the cast? gcc is compiling the following example without any complains:</p> <pre><code> typedef struct int64 int64; struct int64 { unsigned int hi, lo; }; typedef int64 mytime; int64 add_int64(int64 a, int64 b) { int64 c; /* I know that is wrong */ c.hi = a.hi + b.hi; c.lo = a.lo + b.lo; return c; } int main(void) { mytime a = {1, 2}; mytime b = {3, 4}; mytime c; c = add_int64(a, b); return 0; } </code></pre>
<p>Right, so I'm using typedefs and no casting. Works fine. Seems strange though that an explicit cast doesn't compile while an implicit one does. If the implicit cast really isn't a cast at all since the compiler sees the two types as being the same type, one would think the same reasoning would work when doing an explicit cast...</p>
33,615
<p>I don't see what all this fuss is about Microsoft's decision to support JQuery within ASP.NET MVC.</p> <p>There were signs that open-minded people are starting to have some say in the matters of marketing for a while now. And even the way MS does business has started to change. But at it's core it's still acting in response to customers' requests.</p> <p>I for one don't know what to make of it, except that it brings back to Microsoft's sphere of influence a very visible product.</p>
<p>Its the first time MS is shipping an open source component <em>they didn't write</em> with one of their products. This doesn't seem like a big deal, but its almost nuclear in its implications.</p> <p>Think about it... They are saying "we support this." In an OSS product, MS has no control over the code. So, they are putting their livelihood (in some small way) into the hands of people who don't work for MS.</p> <p>I think jQuery's popularity, the fact that it's not mission critical code, and that the codebase is so small all came together to make for favorable circumstances for MS to dip their toe in the water.</p>
<p>Bear in mind that Jquery is released by MS under the MIT license. This means, assuming I understand the terms of the MIT license correctly, that they could in future alter jquery arbitarily and close it off, presumably after its mass acceptance as part of Visual Studio.</p> <p>Edit: OK, I'm being modded down. Can someone please post and explain why they think my supposition here is false. Am I misunderstanding the MIT license?</p>
17,908
<p>Classic ASP had 'server side includes' so that one could easily design a generic layout for the header, footer, left or right side bar.</p> <p>In ASP.NET, I think we must use 'Page Templates'. Although most people say that it is easy to use, I find it rather complicated, as we must copy the whole HTML code inside the 'Render' function. Is there a simpler method? Can I load the code from a HTML file instead pasting the whole code in the 'Render' function?</p> <p>Or is there any better alternative to 'Page Templates'?</p>
<p>I would have thought Master Pages were the standard approach in ASP.NET (2.0 and later). </p> <ol> <li>Design the master page in the designer.</li> <li>Designate the content area or areas within this master page. </li> <li>Then simply design separate "content" pages and indicate the original master page in the Page directive.</li> </ol> <p>Note this is all visually created, no need to manually copy html in Init/Load/Render events, ASP.NET does it for you.</p> <p>A good book I've read is <a href="https://rads.stackoverflow.com/amzn/click/com/0321237706" rel="nofollow noreferrer" rel="nofollow noreferrer">Essential ASP.NET 2.0</a> by Frtiz Onion. It has a good succinct discussion of master pages in Chapter 2.</p>
<p>Master Pages and User Controls combine to give you way more power than ASP includes did.</p>
23,535
<p>I want to print a structure that I can embed in a resin and later dissolve. I know that some fancy 3D printing systems have raft materials etc., that can be printed and later removed easily. </p> <p>Can any one suggest a 3D printing material that can be dissolved in say water or another readily available solvent?</p>
<p>Wash-away filament used for support in PLA printing is typically PVA, which is completely water soluble and may serve your purpose. It is easily 3D printed as the primary filament and attaches well to the build plate.</p> <p>Many 3D printer filament suppliers will carry this type of support material. It is important to keep it in a sealed bag with desiccant as it will absorb moisture from the air, rendering it useless for printing.</p> <p>One such resource is <a href="https://www.matterhackers.com/store/l/175mm-pva-filament-half-kg/sk/M4MJTECR" rel="nofollow noreferrer">MatterHackers</a> which prices a half-kilogram at US$45. The link provides suitably appropriate information:</p> <blockquote> <p>PVA (Polyvinyl Alcohol) is a water-soluble material that is often used as a support material, but can also be used to print independently. PVA supports are useful for complex designs where removing support material manually is difficult or impossible, but leaving the part in a water bath overnight will completely dissolve this material.</p> </blockquote> <p><a href="https://i.stack.imgur.com/2ytSy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2ytSy.png" alt="PVA filament"></a></p>
<p>ABS dissolves in acetone. Indeed actone can be used to clean up 3D prints, see <a href="https://3dprinting.stackexchange.com/questions/4235/whats-smoother-acetone-treated-pla-or-abs/">What&#39;s smoother? Acetone treated PLA or ABS</a>. PLA maybe not somuch as ABS, see the same post.</p> <p>PLA dissolves in any chlorinated or fluorinated solvent, such as THF or Chloroform - both of which are significantly more hazardous than acetone.</p> <p>Hence, as always <strong>take care</strong> when using solvents, see <a href="https://3dprinting.stackexchange.com/questions/81/safety-precautions-when-using-acetone/278#278">Safety precautions when using acetone</a></p> <p>Also, as filaments are often not pure ABS or PLA, due to additives and dyes, etc., then the solvent may not dissolve the 3D printed part <em>completely</em>, and you may be left with a deformed, rubbery residue.</p>
910
<p>I have a unit test where I have statically defined a quite large byte array (over 8000 bytes) as the byte data of a file I don't want to read every time I run my unit test.</p> <pre><code>private static final byte[] FILE_DATA = new byte[] { 12,-2,123,................ } </code></pre> <p>This compiles fine within Eclipse, but when compiling via Ant script I get the following error:</p> <pre><code>[javac] C:\workspace\CCUnitTest\src\UnitTest.java:72: code too large [javac] private static final byte[] FILE_DATA = new byte[] { [javac] ^ </code></pre> <p>Any ideas why and how I can avoid this?</p> <hr> <p><strong>Answer</strong>: Shimi's answer did the trick. I moved the byte array out to a separate class and it compiled fine. Thanks!</p>
<p>Methods in Java are restricted to 64k in the byte code. Static initializations are done in a single method (see <a href="http://www.mail-archive.com/help-bison@gnu.org/msg01990.html" rel="noreferrer">link</a>) <br/> You may try to load the array data from a file.</p>
<p>You can load the byte array from a file in you <code>@BeforeClass</code> static method. This will make sure it's loaded only once for all your unit tests.</p>
30,110
<p>High performance polymers are becoming available for specific applications.</p> <p>One of such materials is PEEK (<a href="https://en.wikipedia.org/wiki/Polyether_ether_ketone" rel="noreferrer">PolyEther Ether Ketone</a>), a thermoplastic polymer in the polyaryletherketone (PAEK) family. PEEK competes with certain Aluminium alloys but is half the weight of Aluminium. For aerospace application this sounds very promising!</p> <p>NASA has <a href="https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/20170000214.pdf" rel="noreferrer">shown</a> that printing these types of polymers is feasible using low-cost, open source hardware.</p> <p><strong>Does anybody know why the prices of PEEK are so high?</strong></p> <p>Depending on the supplier/manufacturer you're looking at about 700 - 900 Euro per kg.</p> <p><a href="https://i.stack.imgur.com/fqNar.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fqNar.png" alt="Natural colored PEEK filament samples"></a></p>
<p>My assumptions about PEEK filament price are:</p> <ul> <li>Raw material is more expensive. Compare price of <a href="https://www.alibaba.com/showroom/abs-pellet.html" rel="noreferrer">ABS</a> with <a href="https://www.alibaba.com/showroom/peek-pellet.html" rel="noreferrer">PEEK</a> pellets.</li> <li>Demand is much lower. There are not many printers able to print peek. If you manufacture PEEK filament you have to store a filament batch for longer time. Manufacturer has to calculate into price storage space, material degradation, ...</li> <li>Filament machine tuning. You have to tune filament extrude machine for PEEK, which takes time because it's a totally different plastic. Maybe there is a cleanup needed after finishing a batch and switching to another material.</li> <li>Working conditions. PEEK is quite smelly and I am not sure if you have to improve work conditions like better ventilation. </li> <li>Research costs. You have to distribute research costs to a filament production where demand is low. </li> </ul>
<p><strong>Patents</strong> still seem to play a role as well.</p> <p>I was curious about this question and did a bit of research: If you filter the <a href="https://patents.google.com/?q=%22Polyether%20ether%20ketone%22&amp;country=US&amp;after=priority:20100101" rel="noreferrer">U.S. patents after 2010 mentioning PEEK</a> and its various applications and improvements, you still get roughly 10,000 patents. Those are not all primarily patents for PEEK, but still.</p> <p>Even <em>Victrex PLC</em>, formerly named <em><a href="https://drakeplastics.com/peek/" rel="noreferrer">Imperial Chemical Industries</a></em>, who filed the <a href="https://register.epo.org/application?number=EP78300314&amp;tab=main" rel="noreferrer">first patent for PEEK back in 1978</a>, had a <a href="https://patents.justia.com/patent/20160208045" rel="noreferrer">patent published in 2016</a> for a new PEEK production procedure:</p> <blockquote> <p>The process can be used to produce high quality, relatively light coloured polymers having a lower Tm than those produced using a standard PEEK process.</p> </blockquote>
979
<p>I have a lot of assignments where I have to continually update a Makefile as I add more subsequently numbered C programs. Is there a way to do this with a loop which iterates over the values 1.1, 1.2, 1.3, etc.?</p> <pre><code>all: 1.1 1.2 1.3 1.4 1.5 1.6 1.7. 1.8 1.9 1.1: 1.1.o gcc -o 1.1 $(FLAGS) 1.1.o 1.1.o: 1.1.c gcc -c $(FLAGS) 1.1.c 1.2: 1.2.o gcc -o 1.2 $(FLAGS) 1.2.o 1.2.o: 1.2.c gcc -c $(FLAGS) 1.2.c 1.3: 1.3.o gcc -o 1.3 $(FLAGS) 1.3.o 1.3.o: 1.3.c gcc -c $(FLAGS) 1.3.c 1.4: 1.4.o gcc -o 1.4 $(FLAGS) 1.4.o 1.4.o: 1.4.c gcc -c $(FLAGS) 1.4.c 1.5: 1.5.o gcc -o 1.5 $(FLAGS) 1.5.o 1.5.o: 1.5.c gcc -c $(FLAGS) 1.5.c 1.6: 1.6.o gcc -o 1.6 $(FLAGS) 1.6.o 1.6.o: 1.6.c gcc -c $(FLAGS) 1.6.c 1.7: 1.7.o gcc -o 1.7 $(FLAGS) 1.7.o 1.7.o: 1.7.c gcc -c $(FLAGS) 1.7.c 1.8: 1.8.o gcc -o 1.8 $(FLAGS) 1.8.o 1.8.o: 1.8.c gcc -c $(FLAGS) 1.8.c 1.9: 1.9.o gcc -o 1.9 $(FLAGS) 1.9.o 1.9.o: 1.9.c gcc -c $(FLAGS) 1.9.c clean: rm -f *.o rm -f 1.1 1.2 1.3 1.4 1.5 1.6 1.7. 1.8 1.9</code></pre>
<p>You want a <a href="http://owen.sj.ca.us/rkowen/howto/slides/make/slides/makesuff.html" rel="nofollow noreferrer">suffix rule</a>, not a loop.</p>
<p>Yes; you can use shell commands in a Makefile, and make itself may offer the looping you need. There are oodles of good examples all over the web; assuming from your use of <code>gcc</code> that you're also using GNU make, try here:</p> <p><a href="http://www.gnu.org/software/make/manual/make.html#Foreach-Function" rel="nofollow noreferrer">http://www.gnu.org/software/make/manual/make.html#Foreach-Function</a></p>
34,921
<p>I was just reading this <a href="https://stackoverflow.com/questions/243082/c-casting-programmatically-can-it-be-done">thread</a> and it occurred to me that there is one seemingly-valid use of that pattern the OP is asking about. I know I've used it before to implement dynamic creation of objects. As far as I know, there is no better solution in C++, but I was wondering if any gurus out there know of a better way. Generally, I run into this situation when I need to create one of several subclasses of an object based one something unknown at compile time (such as based on a config file). I use the object polymorphically once it is created.</p> <p>There's another related situation when you're using a message-passing scheme (usually over TCP/IP) where each message is an object. I like to implement that pattern as letting each message serialize itself into some serialization stream interface, which works well and is fairly clean on the sending end, but on the receiver, I always find myself examining a header on the message to determine the type, then constructing an appropriate message object using the pattern from the linked article, then having it deserialize itself from the stream. Sometimes I implement it so that the construction and deserialization happen at the same time as part of the constructor, which seems more RAII, but that's small consolation for the mess of if/else statements figuring out the type.</p> <p>Any better solutions out there? If you're going to suggest a 3rd party library, it should be free (and ideally open source) and I'd appreciate it if you could explain how the library accomplishes this feat.</p>
<p>I think what you are asking is how to keep the object creation code with the objects themselves.</p> <p>This is usually what I do. It assumes that there is some key that gives you a type (int tag, string, etc). I make a class that has a map of key to factory functions, and a registration function that takes a key and factory function and adds it to the map. There is also a create function that takes a key, looks it up in the map, calls the factory function, and returns the created object. As an example, take a int key, and a stream that contains the rest of the info to build the objects. I haven't tested, or even compiled, this code, but it should give you an idea.</p> <pre><code>class Factory { public: typedef Object*(*Func)(istream&amp; is); static void register(int key, Func f) {m[key] = f;} Object* create(key, istream&amp; is) {return m[key](is);} private: std::map&lt;key, func&gt; m; } </code></pre> <p>Then in each class derived from subobject, the register() method is called with the appropriate key and factory method. </p> <p>To create the object, you just need something like this:</p> <pre><code>while(cin) { int key; is &gt;&gt; key; Object* obj = Factory::Create(key, is); // do something with objects } </code></pre>
<p>Read the classic <a href="https://rads.stackoverflow.com/amzn/click/com/0201633612" rel="nofollow noreferrer" rel="nofollow noreferrer">Gang Of Four aka GOF</a>. Consider [this site[(<a href="http://www.dofactory.com/Patterns/PatternAbstract.aspx" rel="nofollow noreferrer">http://www.dofactory.com/Patterns/PatternAbstract.aspx</a>) for the Factory and other patterns in C#.</p>
30,150
<p>I'm working on a .Net application which uses Asp.net 3.5 and Lucene.Net I am showing search results given by Lucene.Net in an asp.net datagrid. I need to implement Paging (10 records on each page) for this aspx page.</p> <p>How do I get this done using Lucene.Net?</p>
<p>Here is a way to build a simple list matching a specific page with Lucene.Net. This is not ASP.Net specific.</p> <pre><code>int first = 0, last = 9; // TODO: Set first and last to correct values according to page number and size Searcher searcher = new IndexSearcher(YourIndexFolder); Query query = BuildQuery(); // TODO: Implement BuildQuery Hits hits = searcher.Search(query); List&lt;Document&gt; results = new List&lt;Document&gt;(); for (int i = first; i &lt;= last &amp;&amp; i &lt; hits.Length(); i++) results.Add(hits.Doc(i)); // results now contains a page of documents matching the query </code></pre> <p>Basically the Hits collection is very lightweight. The cost of getting this list is minimal. You just instantiate the needed Documents by calling hits.Doc(i) to build your page.</p>
<p>What I do is iterate through the hits and insert them into a temporary table in the db. Then I can run a regular SQL query - joining that temp table with other tables too - and give the grid the DataSet/DataView that it wants.</p> <p>Note that I do the inserts and the query in ONE TRIP to the db, because I'm using just one SQL batch. </p> <pre><code>void Page_Load(Object sender, EventArgs e) { dbutil = new DbUtil(); security = new Security(); security.check_security(dbutil, HttpContext.Current, Security.ANY_USER_OK); Lucene.Net.Search.Query query = null; try { if (string.IsNullOrEmpty(Request["query"])) { throw new Exception("You forgot to enter something to search for..."); } query = MyLucene.parser.Parse(Request["query"]); } catch (Exception e3) { display_exception(e3); } Lucene.Net.Highlight.QueryScorer scorer = new Lucene.Net.Highlight.QueryScorer(query); Lucene.Net.Highlight.Highlighter highlighter = new Lucene.Net.Highlight.Highlighter(MyLucene.formatter, scorer); highlighter.SetTextFragmenter(MyLucene.fragmenter); // new Lucene.Net.Highlight.SimpleFragmenter(400)); StringBuilder sb = new StringBuilder(); string guid = Guid.NewGuid().ToString().Replace("-", ""); Dictionary&lt;string, int&gt; dict_already_seen_ids = new Dictionary&lt;string, int&gt;(); sb.Append(@" create table #$GUID ( temp_bg_id int, temp_bp_id int, temp_score float, temp_text nvarchar(3000) ) "); lock (MyLucene.my_lock) { Lucene.Net.Search.Hits hits = null; try { hits = MyLucene.search(query); } catch (Exception e2) { display_exception(e2); } // insert the search results into a temp table which we will join with what's in the database for (int i = 0; i &lt; hits.Length(); i++) { if (dict_already_seen_ids.Count &lt; 100) { Lucene.Net.Documents.Document doc = hits.Doc(i); string bg_id = doc.Get("bg_id"); if (!dict_already_seen_ids.ContainsKey(bg_id)) { dict_already_seen_ids[bg_id] = 1; sb.Append("insert into #"); sb.Append(guid); sb.Append(" values("); sb.Append(bg_id); sb.Append(","); sb.Append(doc.Get("bp_id")); sb.Append(","); //sb.Append(Convert.ToString((hits.Score(i)))); sb.Append(Convert.ToString((hits.Score(i))).Replace(",", ".")); // Somebody said this fixes a bug. Localization issue? sb.Append(",N'"); string raw_text = Server.HtmlEncode(doc.Get("raw_text")); Lucene.Net.Analysis.TokenStream stream = MyLucene.anal.TokenStream("", new System.IO.StringReader(raw_text)); string highlighted_text = highlighter.GetBestFragments(stream, raw_text, 1, "...").Replace("'", "''"); if (highlighted_text == "") // someties the highlighter fails to emit text... { highlighted_text = raw_text.Replace("'","''"); } if (highlighted_text.Length &gt; 3000) { highlighted_text = highlighted_text.Substring(0,3000); } sb.Append(highlighted_text); sb.Append("'"); sb.Append(")\n"); } } else { break; } } //searcher.Close(); } </code></pre>
41,342
<p>I'm trying to get NAnt 0.86b1 running with VS2008 SP1 and x64 XP.</p> <p>I have a basic build file (below) which gives the error Solution format of file 'Solution.sln' is not supported.</p> <p> </p> <pre><code>&lt;property name="nant.settings.currentframework" value="net-3.5" /&gt; &lt;target name="build" description="Full Rebuild" depends="clean,compile" /&gt; &lt;target name="clean" description="Cleans outputs"&gt; &lt;delete dir="bin" failonerror="false" /&gt; &lt;delete dir="obj" failonerror="false" /&gt; &lt;/target&gt; &lt;target name="compile" description="Compiles solution"&gt; &lt;solution configuration="debug" solutionfile="Solution.sln" /&gt; &lt;/target&gt; </code></pre> <p></p> <p>Has anyone else experienced this problem? I can't find anything useful out there about this.</p>
<p>You'll notice that the docs indicate that NAnt's <a href="http://nant.sourceforge.net/release/0.85/help/tasks/solution.html" rel="noreferrer"><code>&lt;solution</code>></a> task doesn't support solution files newer than VS2003. </p> <p>I recommend using <a href="http://nantcontrib.sourceforge.net/release/0.85/help/tasks/msbuild.html" rel="noreferrer">the <code>&lt;msbuild&gt;</code> task from nantcontrib</a> for all projects newer than VS2003.</p> <p>Also, the .85 version of NAnt only supports framework versions up to 2.0. The purest way to get things working against the 3.5 framework is to use the <a href="http://nant.sourceforge.net" rel="noreferrer">.86-beta1</a> versions of NAnt. You'll then be able to use the <code>&lt;msbuild&gt;</code> task against the 3.5 solution.</p>
<p>See <a href="https://stackoverflow.com/questions/426199/building-the-platform-code-with-nant-and-vs2008/543648#543648">Building the platform code with nant and VS2008</a></p> <p>This is here on Stack overflow. Basically you only have a couple of options, control all the builds yourself with project build files, common build files, and a master build file. Or run the Exec task to exectue the correct version of MSBuild for each solution you want compiled.</p>
42,480
<p>When you take your first look at an Oracle database, one of the first questions is often "where's the alert log?". Grid Control can tell you, but its often not available in the environment.</p> <p>I posted some bash and Perl scripts to find and tail the alert log <a href="http://tardate.blogspot.com/2007/04/find-and-tail-oracle-alert-log.html" rel="nofollow noreferrer">on my blog</a> some time back, and I'm surprised to see that post still getting lots of hits.</p> <p>The technique used is to lookup background_dump_dest from v$parameter. But I only tested this on Oracle Database 10g.</p> <p>Is there a better approach than this? And does anyone know if this still works in 11g?</p>
<p>Am sure it will work in 11g, that parameter has been around for a long time.</p> <p>Seems like the correct way to find it to me.</p> <p>If the background_dump_dest parameter isn't set, the alert.log will be put in $ORACLE_HOME/RDBMS/trace</p>
<p>Once you've got the log open, I would consider using <a href="http://search.cpan.org/perldoc?File::Tail" rel="nofollow noreferrer">File::Tail</a> or <a href="http://search.cpan.org/perldoc?File::Tail::App" rel="nofollow noreferrer">File::Tail::App</a> to display it as it's being written, rather than sleeping and reading. <code>File::Tail::App</code> is particularly clever, because it will detect the file being rotated and switch, and will remember where you were up to between invocations of your program.</p> <p>I'd also consider locking your cache file before using it. The race condition may not bother you, but having multiple people try to start your program at once could result in nasty fights over who gets to write to the cache file.</p> <p>However both of these are nit-picks. My brief glance over your code doesn't reveal any glaring mistakes.</p>
20,721
<p>I've read some of the recent language vs. language questions with interest... <a href="https://stackoverflow.com/questions/150043/python-v-perl#150103">Perl vs. Python</a>, <a href="https://stackoverflow.com/questions/136977/after-c-python-or-java#137343">Python vs. Java</a>, <a href="https://stackoverflow.com/questions/157207/can-one-language-be-better-than-another">Can one language be better than another?</a></p> <p>One thing I've noticed is that a lot of us have <em>very superficial</em> reasons for disliking languages. We notice these things at first glance and they turn us off. We shun what are probably perfectly good languages as a result of features that we'd probably learn to love or ignore in 2 seconds if we bothered.</p> <p>Well, I'm as guilty as the next guy, if not more. Here goes:</p> <ul> <li>Ruby: All the Ruby example code I see uses the <code>puts</code> command, and that's a sort of childish Yiddish anatomical term. So as a result, I can't take Ruby code seriously even though I should.</li> <li>Python: The first time I saw it, I smirked at the whole significant whitespace thing. I avoided it for the next several years. Now I hardly use anything else.</li> <li>Java: I don't like identifiersThatLookLikeThis. I'm not sure why exactly.</li> <li>Lisp: I have trouble with all the parentheses. Things of different importance and purpose (function declarations, variable assignments, etc.) are not syntactically differentiated and I'm too lazy to learn what's what.</li> <li>Fortran: uppercase everything hurts my eyes. I know modern code doesn't have to be written like that, but most example code is...</li> <li>Visual Basic: it bugs me that <code>Dim</code> is used to declare variables, since I remember the good ol' days of GW-BASIC when it was <em>only</em> used to dimension arrays.</li> </ul> <p>What languages <em>did</em> look right to me at first glance? Perl, C, QBasic, JavaScript, assembly language, BASH shell, FORTH.</p> <p>Okay, now that I've aired my dirty laundry... I want to hear yours. <strong>What are your language hangups? What superficial features bother you? How have you gotten over them?</strong></p>
<p>I hate Hate HATE "End Function" and "End IF" and "If... Then" parts of VB. I would much rather see a curly bracket instead.</p>
<p>I have a practical one from years of code revewing and debugging other people's code. I would remove (from all languages) the ability to group logical operations in a conditional statement. This comes from a specific gripe about the AND operator e.g...</p> <pre><code>if (a and b) { do something } </code></pre> <p>There are four cases, three of which have not been handled. The programmer may well have considered all 4 cases and deliberately chosen to write the code this way, but we have no indication that is the case unless they commented the code - and normally they don't.</p> <p>It may be a bit more verbose, but the following is unambiguous...</p> <pre><code>if (a) { if (b) { do something } else { what about this case? } } else { if (b) { what about this case? } else { do something else } } </code></pre> <p>As the poor person following up a year later at least I will know exactly what is supposed to be going on.</p>
19,455
<p><strong>Good day.</strong></p> <p>I have a program thats launches an external application. That external app has a right click sub menu on it which I need to disable. Is it possible (without modifying the external app) to disable the right click? Maybe permission or group policies and etc.</p> <p>Thanks.</p>
<p>I wasn't sure I wanted to post as I don't have a huge amount of scope on the matter, but it's definatley possible. If you have a handle to the application (if not you can get one) you can use that to disable right click within the application.</p> <p><a href="http://www.codeguru.com/forum/showthread.php?t=190440" rel="nofollow noreferrer">http://www.codeguru.com/forum/showthread.php?t=190440</a></p> <p><a href="http://support.microsoft.com/kb/318804" rel="nofollow noreferrer">http://support.microsoft.com/kb/318804</a></p> <p>seems like the most helpful links, it just goes on about how you should hook and then disregard <code>WM_RBUTTONDOWN</code> and <code>WM_RBUTTONUP</code>.</p> <p>I'll try and write up a better thing later with an example.</p> <p>More links/edits</p> <p>This link could be useful as it explains that you're going to need to use unmanaged c/c++ to hook using setWindowsHookEx.</p> <p><a href="http://social.msdn.microsoft.com/Forums/en-US/clr/thread/8dd657b5-647b-443b-822d-ebe03ca4033c/" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/clr/thread/8dd657b5-647b-443b-822d-ebe03ca4033c/</a></p> <p>Hope this helps</p> <p>[EDIT]</p> <p>I think this can actually be done in a C# application completely. I will post a solution tonight</p> <p>[/EDIT]</p>
<p>It's a win32 api FAQ.</p> <p>see news://194.177.96.26/comp.os.ms-windows.programmer.win32 where it has often been discussed</p>
20,925
<p>There has been a flurry of updates released to Microsoft's Silverlight over the past couple of months (Silverlight 2 beta 2 runtime + dev tools, RC0 + dev tools which broke beta 2 apps), and recently Microsoft has released the RTM.</p> <p>I have been trying (unsuccessfully) to integrate Sharepoint 2007 and Silverlight. Many of the sharepoint/silverlight blogs i have read are outdated, meaning that they target SL Beta 2.</p> <p>So, my question is...</p> <p><b>What steps are necessary in order to host a Silverlight 2.0 (RTM) application, in a web part, on Sharepoint Server 2007 ?</b></p>
<p>I haven't tried this out but it seems like a good start:</p> <p><a href="http://www.codeplex.com/SL4SP" rel="nofollow noreferrer">Silverlight Blueprint for SharePoint</a></p>
<p>If you are going to be using User Controls [i.e. Web Parts], then I'd highly recommend looking at SmartPart. You'll still need to do the things in the blogs above to get the assemblies recognized, trusted, etc, but this may help you get your user controls deployed faster.</p>
32,373
<p>Is it good practice to let abstract classes define instance variables?</p> <pre><code>public abstract class ExternalScript extends Script { String source; public abstract void setSource(String file); public abstract String getSource(); } </code></pre> <p>The sub class, ExternalJavaScript.class, would then automatically get the source variable but I feel it's easier to read the code if all the sub classes themselves define the source, instead of from inheritance. </p> <p>What is your advice?</p> <p>/Adam</p>
<p>I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.</p> <pre><code>public abstract class ExternalScript extends Script { private String source; public void setSource(String file) { source = file; } public String getSource() { return source; } } </code></pre> <p>Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too:</p> <ul> <li>If source was protected (so accessible by subclasses) then code gets messy: who's changing the variables? When it's an object it then becomes hard when you need to refactor, whereas a method tends to make this step easier.</li> <li>If your getter/setter methods aren't getting and setting, then describe them as something else.</li> </ul> <p>Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.</p>
<p>Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.</p>
29,232
<p>I am using YUI reset/base, after the reset it sets the <code>ul</code> and <code>li</code> tags to list-style: disc outside;</p> <p>My markup looks like this:</p> <pre><code>&lt;div id="nav"&gt; &lt;ul class="links"&gt; &lt;li&gt;&lt;a href=""&gt;Testing&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>My CSS is:</p> <pre><code>#nav {} #nav ul li { list-style: none; } </code></pre> <p>Now that makes the small disc beside each li disappear.</p> <p>Why doesn't this work though?</p> <pre><code> #nav {} #nav ul.links { list-style: none; } </code></pre> <p>It works if I remove the link to the base.css file, why?.</p> <p>Updated: <code>sidenav</code> -> <code>nav</code></p>
<p>I think that Dan was close with his answer, but this isn't an issue of specificity. <strong>You can set the list-style on the list (the UL) but you can also override that list-style for individual list items (the LIs).</strong></p> <p>You are telling the browser to not use bullets on the list, but YUI tells the browser to use them on individual list items (YUI wins):</p> <pre><code>ul li{ list-style: disc outside; } /* in YUI base.css */ #nav ul.links { list-style: none; /* doesn't override styles for LIs, just the UL */ } </code></pre> <p>What you want is to tell the browser not to use them on the list items:</p> <pre><code>ul li{ list-style: disc outside; } /* in YUI base.css */ #nav ul.links li { list-style: none; } </code></pre>
<p>Maybe the style is the base.css overrides your styles with "!important"? Did you try to add a class to this specific li and make an own style for it?</p>
13,332
<p>If I have two dates (ex. <code>'8/18/2008'</code> and <code>'9/26/2008'</code>), what is the best way to get the number of days between these two dates?</p>
<p>If you have two date objects, you can just subtract them, which computes a <a href="https://docs.python.org/3/library/datetime.html#datetime.timedelta" rel="noreferrer"><code>timedelta</code></a> object.</p> <pre><code>from datetime import date d0 = date(2008, 8, 18) d1 = date(2008, 9, 26) delta = d1 - d0 print(delta.days) </code></pre> <p>The relevant section of the docs: <a href="https://docs.python.org/library/datetime.html" rel="noreferrer">https://docs.python.org/library/datetime.html</a>.</p> <p>See <a href="https://stackoverflow.com/a/8258465">this answer</a> for another example.</p>
<p>Without using datetime object in python.</p> <pre><code># A date has day 'd', month 'm' and year 'y' class Date: def __init__(self, d, m, y): self.d = d self.m = m self.y = y # To store number of days in all months from # January to Dec. monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] # This function counts number of leap years # before the given date def countLeapYears(d): years = d.y # Check if the current year needs to be considered # for the count of leap years or not if (d.m &lt;= 2) : years-= 1 # An year is a leap year if it is a multiple of 4, # multiple of 400 and not a multiple of 100. return int(years / 4 - years / 100 + years / 400 ) # This function returns number of days between two # given dates def getDifference(dt1, dt2) : # COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1' # initialize count using years and day n1 = dt1.y * 365 + dt1.d # Add days for months in given date for i in range(0, dt1.m - 1) : n1 += monthDays[i] # Since every leap year is of 366 days, # Add a day for every leap year n1 += countLeapYears(dt1) # SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2' n2 = dt2.y * 365 + dt2.d for i in range(0, dt2.m - 1) : n2 += monthDays[i] n2 += countLeapYears(dt2) # return difference between two counts return (n2 - n1) # Driver program dt1 = Date(31, 12, 2018 ) dt2 = Date(1, 1, 2019 ) print(getDifference(dt1, dt2), &quot;days&quot;) </code></pre>
18,225
<p>I have several "ASP:TextBox" controls on a form (about 20).<br> When the form loads, the text boxes are populated from a database.<br> The user can change the populated values, and when they submit the form, I take the values posted to the server and conditionally save them (determined by some business logic).<br> All but 1 of the text boxes work as intended.</p> <p>The odd box out, upon postback, does not contain the updated value that the user typed into the box.<br> When debugging the application, it is clear that <code>myTextBox.Text</code> reflects the old, pre-populated value, not the new, user-supplied value.<br> Every other box properly shows their respective user-supplied values.</p> <p>I did find a workaround.<br> My solution was to basically extract the text box's value out of the <code>Request.Form</code> object: <code>Request.Form[myTextBox.UniqueID]</code>, which does contain the user-supplied value.</p> <p>What could be going on, here?<br> As I mentioned, the other text boxes receive the user-supplied values just fine, and this particular problematic text box doesn't have any logic associated to it -- it just takes the value and saves it.<br> The main difference between this text box and the others is that this is a multi-line box (for inputting notes), which I believe is rendered as an HTML "textarea" tag instead of an "input" tag in ASP.NET.</p>
<p>Are you initially loading the data only when !Page.IsPostBack? Also, is view state enabled for the text box?</p>
<p>Remember the order of the page lifecycle, and where you are databinding your form.</p> <ul> <li>PreInit</li> <li>Init</li> <li>Load</li> <li>Your Control Event Handler</li> </ul> <p>If you are reading the value in the Control Event handler, yet databinding in Init or Load, you'll have the old value.</p> <p>The trick is to always databind in the correct event, or check for postback and don't databind then.</p>
4,299
<p>I found <a href="http://forums.mysql.com/read.php?100,22967,22967" rel="noreferrer">a posting on the MySQL forums from 2005</a>, but nothing more recent than that. Based on that, it's not possible. But a lot can change in 3-4 years.</p> <p>What I'm looking for is a way to have an index over a view but have the table that is viewed remain unindexed. Indexing hurts the writing process and this table is written to quite frequently (to the point where indexing slows everything to a crawl). However, this lack of an index makes my queries painfully slow.</p>
<p>I don't think MySQL supports materialized views which is what you would need, but it wouldn't help you in this situation anyway. Whether the index is on the view or on the underlying table, it would need to be written and updated at some point during an update of the underlying table, so it would still cause the write speed issues.</p> <p>Your best bet would probably be to create summary tables that get updated periodically.</p>
<p>Do you only want one indexed view? It's unlikely that writing to a table with only one index would be that disruptive. Is there no primary key?</p> <p>If each record is large, you might improve performance by figuring out how to shorten it. Or shorten the length of the index you need.</p> <p>If this is a write-only table (i.e. you don't need to do updates), it can be deadly in MySQL to start archiving it, or otherwise deleting records (and index keys), requiring the index to start filling (reusing) slots from deleted keys, rather than just appending new index values. Counterintuitive, but you're better off with a larger table in this case.</p>
30,278
<p>I'm trying to deserialize an xml structure that looks like this:</p> <pre><code>&lt;somecontainer&gt; &lt;key1&gt;Value1&lt;/key1&gt; &lt;key1&gt;Value2&lt;/key1&gt; &lt;key2&gt;Value3&lt;/key2&gt; &lt;key2&gt;Value4&lt;/key2&gt; &lt;/somecontainer&gt; </code></pre> <p>I can basically choose what kind if element to deserialize to, maybe something like a List of Pair or something. The essence here is that the element names are the keys.</p> <p>And no, I cannot change the xml structure. Anyone know how to do this with xstream ?</p>
<p>Edit (Aug. 2012):</p> <p>It turns out that currently the best solution are probably Guava 13.0's <code>Cache</code> classes, explained on <a href="https://github.com/google/guava/wiki/CachesExplained" rel="nofollow noreferrer">Guava's Wiki</a> - that's what I'm going to use. It even supports building a <code>SoftHashMap</code> (see <code>CacheBuilder.newBuilder().softKeys()</code>), but it is probably not what you want, as Java expert Jeremy Manson explains (below you'll find the link).</p> <hr /> <p>Not that <a href="http://www.javalobby.org/java/forums/t16581.html" rel="nofollow noreferrer">I know of</a> (Nov. 2008), but you kind find some implementation of <code>SoftHashMap</code> on the net.</p> <p>Like this one: <a href="http://www.koders.com/java/fidF6A9D06D716A6B562853A8DA95C43169F4044FC0.aspx?s=idef%3Aconfiguration" rel="nofollow noreferrer"><code>SoftHashMap</code></a> or <a href="http://www.krugle.org/examples/p-5RTxkghvRYJ5a4Wv/SoftHashMap.java" rel="nofollow noreferrer">this one</a>.</p> <hr /> <p>Edit (Nov. 2009)<br /> As <a href="https://stackoverflow.com/users/127013/matthias">Matthias</a> mentions in the comments, the <a href="https://github.com/google/guava" rel="nofollow noreferrer">Google Guava</a> <a href="https://github.com/google/guava/wiki/MapMakerMigration" rel="nofollow noreferrer"><strong>MapMaker</strong></a> does use SoftReferences:</p> <blockquote> <p>A <code>ConcurrentMap</code> builder, providing any combination of these features:</p> </blockquote> <blockquote> <ul> <li>soft or weak keys,</li> </ul> </blockquote> <ul> <li>soft or weak values,</li> <li>timed expiration, and</li> <li>on-demand computation of values.</li> </ul> <p>As mentioned in <a href="http://www.mail-archive.com/general@lists.ops4j.org/msg08349.html" rel="nofollow noreferrer">this thread</a>, another JSR166y candidate:</p> <p><a href="http://anonsvn.jboss.org/repos/jbosscache/experimental/jsr166/src/jsr166y/ConcurrentReferenceHashMap.java" rel="nofollow noreferrer">jsr166y.ConcurrentReferenceHashMap</a></p> <blockquote> <p>It provides an alternative concurrent reference map to the Google implementation (which relies on a background thread to evict entries)</p> </blockquote> <hr /> <p>Edit (August 2012)</p> <p>The Google implementation uses a background thread only when timed expiration of entries is requested. In particular, it simply uses <code>java.util.Timer</code>, which is not so intrusive as having a separate background thread.</p> <p>Jeremy Manson recommends, for any cache, using this feature to avoid the dangers of SoftReference: <a href="http://jeremymanson.blogspot.de/2009/07/how-hotspot-decides-to-clear_07.html" rel="nofollow noreferrer">http://jeremymanson.blogspot.de/2009/07/how-hotspot-decides-to-clear_07.html</a></p> <p>There's another implementation from <a href="http://commons.apache.org/collections/" rel="nofollow noreferrer">Apache Commons</a>, namely <a href="https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/org/apache/commons/collections/map/ReferenceMap.html" rel="nofollow noreferrer">org.apache.commons.collections.map.ReferenceMap</a>; it does not support timed removal, but it does support choosing whether keys should be compared by identity or by equality. Moreover, this implementation is not concurrent - it can be made synchronized, but that works less well under accesses from multiple threads.</p>
<p>If you want to implement a cache softreferences are definetly a better idea than weak references, but it puts your entire cache removal policy in the hands of the garbage collector. which is probably not what you want.</p> <p>If cache removal policy is important your are going to need to do it on your own most likely using regular references. However you are going to have to decide when to eject items and which to eject. If you only want to lose things when you are running out of heap space you can query available heap space via:</p> <pre><code>Runtime.getRuntime().getFreeMemory(); </code></pre> <p>Then once free memory drops below a certain amount you can start either dropping items. Or you could just implement a max size for the cache and use that to decide when to drop things.</p> <p>here's an <a href="https://stackoverflow.com/questions/221525/how-would-you-implement-an-lru-cache-in-java-6#224256">LRU cache</a> i designed with O(1) insertion, deletion and lookup time, that has a configurable max number of elements. If you want a cache this is going to be a better solution imho than a SoftHashMap.</p> <p>The softreferences are a great way to create a growable cache. So the ideal solution would be to use a SoftHashMap along with a regular fixed size cache. have all inserts into the cache go into both the fixed cache and the soft hash map then to reference something just see if its in the soft hashmap (and update the reference time in the cache). this way all your most important items (according to your chosen policy LRU, MFU,...) will never be removed because they are hard referenced in the cache but you will also hold on to more things (with no policy control) as long as there is sufficient memory.</p>
33,147
<p>Need to show a credits screen where I want to acknowledge the many contributors to my application. </p> <p>Want it to be an automatically scrolling box, much like the credits roll at the end of the film.</p>
<p>A easy-to-use snippet would be to make a multiline textbox. With a timer you may insert line after line and scroll to the end after that:</p> <pre><code>textbox1.SelectionStart = textbox1.Text.Length; textbox1.ScrollToCaret(); textbox1.Refresh(); </code></pre> <p>Not the best method but it's simple and working. There are also some free controls available for exactly this auto-scrolling.</p>
<p>A quick and dirty method would be to use a Panel with a long list of Label controls on it that list out the various people and contributions. Then you need to set the Panel to be AutoScroll so that it has a vertical scrollbar because the list of labels goes past the bottom of the displayed Panel. Then add a time that updates the AutoScrollOffset by 1 vertical pixel each timer tick. When you get to the bottom you reset the offset to 0 and carry on. The only downside is the vertical scrollbar showing.</p>
8,847
<p>Here's what I need to do, any ideas would be helpful.</p> <p>I need to be able to change the Local IP address of a computer programmatically as a limited user in XP. Without giving Admin information to the users. I've played with runas, sanur, and autoit, but all either require giving up the Administrator password or is not extremely reliable.</p> <p>Again, any ideas would be great.</p>
<p>You should probably create a service that has administrative rights and allow limited users to request an IP change from that service.</p>
<p>I'd imagine you could simply call <a href="http://msdn.microsoft.com/en-us/library/aa378184(VS.85).aspx" rel="nofollow noreferrer">LogonUser</a> with admin credentials, and change it from there. That'd require embedding the password in the EXE, of course.</p>
23,394
<pre><code>include("conn.php"); $result = mysql_query("SELECT * FROM sggame"); while($row = mysql_fetch_assoc($result)); { $id = $row['id']; echo $id; echo 'working?'; } </code></pre> <p>The above code simply doesn't return anything out of the db. The row name is correct and the loop runs, showing that there is something in the database. However the row is just not echoed out at all. This is code i have used a thousand time before and am rather perplexed as to why it has stopped now! Any help, as always, is much appreciated</p>
<p>replace</p> <pre><code>while($row = mysql_fetch_assoc($result)); </code></pre> <p>with </p> <pre><code>while($row = mysql_fetch_assoc($result)) </code></pre>
<p>did this code give off a notice or warning when you where running it ? I am just curious being that the problem was the semicolon.</p>
46,806
<p>Why is it not advisable to use JavaScript in JSP? One rationale that I can think of is turning off the feature in browser would stop the code from executing. Is there any other reason behind this?</p>
<p>Afaik, there is no problem in using javascript in jsp, and many sites do use it. Especially if your site is a web app, you <i>will</i> have to use both side by side. They are completely independent. You just have to make sure that what you are using each for is appropriate.</p> <p><p>As for the part about turning off javascript in a browser making the site unusable, it is true whenever you use javascript, with or without jsp.</p>
<p>JSP is a server side technology. That is - Server parses/compiles all the information and then sends it to the client (i.e. your browser). And then..</p> <p>If received data contains ANY javascript then browser interprets it in its own javascript VM and server is long forgotten by then since HTTP is stateless protocol.</p> <p>Considering "not recommending JS in web" I wouldn't bother about it. Most of the sites use JS extensively thus turning it off on the client side would render them mostly useless.</p>
42,413
<p>I've always handled optional parameters in JavaScript like this:</p> <pre><code>function myFunc(requiredArg, optionalArg){ optionalArg = optionalArg || 'defaultValue'; // Do stuff } </code></pre> <p>Is there a better way to do it?</p> <p>Are there any cases where using <code>||</code> like that is going to fail?</p>
<p>Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative</p> <pre><code>if (typeof optionalArg === 'undefined') { optionalArg = 'default'; } </code></pre> <p>Or an alternative idiom:</p> <pre><code>optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg; </code></pre> <p>Use whichever idiom communicates the intent best to you!</p>
<p>I suggest you to use <a href="https://github.com/zvictor/ArgueJs" rel="nofollow">ArgueJS</a> this way:</p> <pre><code>function myFunc(){ arguments = __({requiredArg: undefined, optionalArg: [undefined: 'defaultValue'}) //do stuff, using arguments.requiredArg and arguments.optionalArg // to access your arguments } </code></pre> <p>You can also replace <code>undefined</code> by the type of the argument you expect to receive, like this:</p> <pre><code>function myFunc(){ arguments = __({requiredArg: Number, optionalArg: [String: 'defaultValue'}) //do stuff, using arguments.requiredArg and arguments.optionalArg // to access your arguments } </code></pre>
17,942
<p>I'm making a C program where I need to get the directory that the program is started from. This program is written for UNIX computers. I've been looking at <code>opendir()</code> and <code>telldir()</code>, but <code>telldir()</code> returns a <code>off_t (long int)</code>, so it really doesn't help me. </p> <p>How can I get the current path in a string (char array)?</p>
<p>Have you had a look at <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html" rel="noreferrer"><code>getcwd()</code></a>?</p> <pre><code>#include &lt;unistd.h&gt; char *getcwd(char *buf, size_t size); </code></pre> <p>Simple example:</p> <pre><code>#include &lt;unistd.h&gt; #include &lt;stdio.h&gt; #include &lt;limits.h&gt; int main() { char cwd[PATH_MAX]; if (getcwd(cwd, sizeof(cwd)) != NULL) { printf(&quot;Current working dir: %s\n&quot;, cwd); } else { perror(&quot;getcwd() error&quot;); return 1; } return 0; } </code></pre>
<p>Use <b>getcwd</b></p> <pre><code>#include &lt;stdio.h&gt; /* defines FILENAME_MAX */ //#define WINDOWS /* uncomment this line to use it for windows.*/ #ifdef WINDOWS #include &lt;direct.h&gt; #define GetCurrentDir _getcwd #else #include &lt;unistd.h&gt; #define GetCurrentDir getcwd #endif int main(){ char buff[FILENAME_MAX]; GetCurrentDir( buff, FILENAME_MAX ); printf(&quot;Current working dir: %s\n&quot;, buff); return 1; } </code></pre> <p>OR</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;unistd.h&gt; #include&lt;stdlib.h&gt; main() { char *buf; buf=(char *)malloc(100*sizeof(char)); getcwd(buf,100); printf(&quot;\n %s \n&quot;,buf); } </code></pre>
38,214
<p>How do you feel about VS making you hunt for a tab that you used just minutes ago when you have a bazillion open tabs? What about constantly dragging tabs around to keep the ones you use close together?</p> <p>Oh, so you think <em>AARGH</em>, too? Then read on.</p> <p>I work on a piece of software with dozens of projects and hundreds of files. It's really easy to get the tab bar to fill up - like when debugging, which can open a lot of files, most of which are just boilerplate, or not really interesting for the task at hand.<br> This makes the few files that are <em>relevant</em> to 'fall off' the tab bar, or a pain to find by skimming the visible tabs. </p> <p>There are some solutions, some more widely known than others. Here's my top 3:</p> <p><strong>III.</strong> This works if you can <strong>exactly</strong> remember the file name (or at least the first letters): use the 'find box':</p> <pre><code>type: Ctrl-D &gt;of yourFileName </code></pre> <p>As you type the file name, you get autocomplete on the file names in the solution. More details <a href="http://www.alteridem.net/2007/09/11/quickly-findopen-a-file-in-visual-studio/" rel="noreferrer">here</a>.</p> <p><strong>II.</strong> The most obvious one: using the 'active files' drop-down on the right of the tab bar which is alphabetically ordered. <br> Lesser known fact: use <strong><code>Ctrl-Alt-DownArrow</code></strong> to open that drop-down, then start typing the file name. You get the added benefit of visualizing the available choices. [info shamelessly stolen from <a href="http://www.chinhdo.com/20070920/top-11-visual-studio-2005-ide-tips-and-tricks-to-make-you-a-more-productive-developer/" rel="noreferrer">here</a>]</p> <p><strong>I.</strong> <code>&lt;drum roll/&gt;</code> This one is my personal favourite, and it's based on an undocumented feature of VS 2005/2008. When activated, it does one simple thing: clicking a tab moves it to the left-most side of the window. This basic action usually lets me find the tab I'm looking for in the first 3 to 5 tabs. It goes like this:</p> <p><em>removed dead ImageShack link - sample animation</em></p> <p>In order to enable this functionality, you have to get your hands dirty with the Windows registry.<br> Compulsory edit-registry-at-your-own-risk warning: <br><em>Editing the registry may make your network card drop packets on the floor. You have been warned.</em> </p> <p>Add this key to the registry for VS 2005:</p> <pre><code>[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0] "UseMRUDocOrdering"=dword:00000001 </code></pre> <p>or this for VS 2008:</p> <pre><code>[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0] "UseMRUDocOrdering"=dword:00000001 </code></pre> <p>You don't even have to restart VS to see it work! [plagiarized from <a href="http://blogs.msdn.com/msbuild/archive/2007/04/13/window-tab-management-in-visual-studio.aspx" rel="noreferrer">here</a>]<br> Now go on, give it a try! </p> <p><strong>Update:</strong> This trick no longer works in VS2010 Pro :(</p> <hr> <p>This wraps up my part. Now it's your turn to share how you deal with tab hunting!</p>
<p>ReSharper and its Recent Files feature works a lot better for me.</p>
<p>Control-Tab and the ">of" trick are both useful. Neither of them quite work for me, though, especially when I've got a lot of open files or I want quicker access.</p> <p>I like the free <a href="http://www.usysware.com/dpack/" rel="nofollow noreferrer">DPack</a> collection of tools. There's a lot of neat stuff in there, some of which is built in to more recent versions of VS. I haven't seent anything like the file browser, though. It sits as a tool window (or dialog, if you prefer), and gives you an incrementally-filtered list of files in your solution. You can limit the list to open files if you use it as a modal dialog, apparently, though I haven't tried that.</p> <p><a href="https://i.stack.imgur.com/INaVo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/INaVo.png" alt="USWare File Browser"></a><br> <sub>(source: <a href="http://www.usysware.com/dpack/images/FileBrowser2.png" rel="nofollow noreferrer">usysware.com</a>)</sub> </p>
38,359
<p>I am using VMware Server 1.0.7 on Windows XP SP3 at the moment to test software in virtual machines.</p> <p>I have also tried Microsoft Virtual PC (do not remeber the version, could be 2004 or 2007) and VMware was way faster at the time.</p> <p>I have heard of Parallels and VirtualBox but I did not have the time to try them out. Anybody has some benchmarks how fast is each of them (or some other)?</p> <p>I searched for benchmarks on the web, but found nothing useful.</p> <p>I am looking primarily for free software, but if it is really better than free ones I would pay for it.</p> <p>Also, if you are using (or know of) a good virtualization software but have no benchmarks for it, please let me know.</p>
<p>Use <code>/dev/random</code> (requires user input, eg mouse movements) or <code>/dev/urandom</code>. The latter has an entropy pool and doesn't require any user input unless the pool is empty.</p> <p>You can read from the pool like this:</p> <pre><code>char buf[100]; FILE *fp; if (fp = fopen("/dev/urandom", "r")) { fread(&amp;buf, sizeof(char), 100, fp); fclose(fp); } </code></pre> <p>Or something like that.</p>
<p>The <code>/dev/random</code> device is intended to be a source of cryptographically secure bits.</p>
14,622
<p>I've had a little search and I was wondering if there is back compatibility for the .NET framework.</p> <p>The real question is, if there's a program that uses .NET Framework 1.1, can I install 3.5 and be done, or do I have to install 1.1 and then if something uses 3.5 I have to install 3.5 as well?</p>
<p>Unfortunately you will have to install both versions. Older version of the framework are not automatically bundled with newer versions.</p>
<p>If you install something that requires 3.5, then you will have to install it. The way that .Net works though, you can have 1.1, 2.x and 3.5 all installed at the same time. Programs specify the version of the framework they need, and that version is loaded for them.</p>
9,744
<p>The last cross platform desktop development I did was Java/Swing. What about flex?</p>
<p>Don't do it. If you need to go cross-platform, write the main guts of your application in a business logic layer that doesn't depend on any GUI framework and then use the native platform API to finish each app.</p> <p>Your users will thank you.</p>
<p>C# with Framework .Net can be good not only for Windows but for <a href="http://www.mono-project.com/Main_Page" rel="nofollow noreferrer">Linux with Mono</a>.</p> <p>Microsoft have a <a href="http://www.microsoft.com/downloads/details.aspx?familyid=3a1c93fa-7462-47d0-8e56-8dd34c6292f0&amp;displaylang=en" rel="nofollow noreferrer">CLI that work on MAC OSX10.2</a>.</p>
22,936
<p>It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.</p> <pre><code>List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = sl; </code></pre> <p>results in Cannot implicitly convert type <code>System.Collections.Generic.List&lt;string&gt;</code> to <code>System.Collections.Generic.List&lt;object&gt;</code></p> <p>And then...</p> <pre><code>List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = (List&lt;object&gt;)sl; </code></pre> <p>results in Cannot convert type <code>System.Collections.Generic.List&lt;string&gt;</code> to <code>System.Collections.Generic.List&lt;object&gt;</code></p> <p>Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.</p>
<p>Think of it this way, if you were to do such a cast, and then add an object of type Foo to the list, the list of strings is no longer consistent. If you were to iterate the first reference, you would get a class cast exception because once you hit the Foo instance, the Foo could not be converted to string!</p> <p>As a side note, I think it would be more significant whether or not you can do the reverse cast:</p> <pre><code>List&lt;object&gt; ol = new List&lt;object&gt;(); List&lt;string&gt; sl; sl = (List&lt;string&gt;)ol; </code></pre> <p>I haven't used C# in a while, so I don't know if that is legal, but that sort of cast is actually (potentially) useful. In this case, you are going from a more general class (object) to a more specific class (string) that extends from the general one. In this way, if you add to the list of strings, you are not violating the list of objects.</p> <p>Does anybody know or can test if such a cast is legal in C#?</p>
<p>Here is another pre-.NET 3.5 solution for any IList whose contents can be cast implicitly.</p> <pre><code>public IList&lt;B&gt; ConvertIList&lt;D, B&gt;(IList&lt;D&gt; list) where D : B { List&lt;B&gt; newList = new List&lt;B&gt;(); foreach (D item in list) { newList.Add(item); } return newList; } </code></pre> <p>(Based on Zooba's example)</p>
2,827
<p>All,</p> <p>I have built a nifty demo application that displays data about our internal systems as a full-screen "billboard" style display. You could think of this as something like an application displaying the national deficit - rapidly increasing numbers, animating very quickly, all day.</p> <p>The problem is that the demo works really well and the client would like me to build an industrial strength version! </p> <p>I'd like to do this in C++ but it could be Java or <em>maybe</em> C# (though I'd prefer not to use C#, as I'm not so strong in that env). </p> <p>I'm toying with SDL or Allegro, but I have no experience in either, so I'm open to the best (and ideally easiest) toolkit out there.</p> <p>When I say "iPhone"-style, I mean simple but elegant transitions between panels. The iPhone makes exellent use of slides, fades and blends. My app doesn't need to do any 3D style animations. In terms of graphics, I really only need simple things: 90% text, some images, and simple primitives like lines, rectangles and gradient fills.</p> <p>Of course, I could implement this in "plain old" DirectDraw or OpenGL, but I really don't want to think about writing timer classes and choosing timing methods for animation - some toolkit out there should be just right for this.</p> <p>Thanks for any help!</p> <p>RF</p>
<p>I think you are looking for the Clutter Toolkit. It's free, cool, and multi-platform. Works on top of OpenGL by implementing all those timers and stuff you can't be arsed to implement yourself, and wrapping them on a very convenient and awesome API.</p> <p><a href="http://clutter-project.org/" rel="nofollow noreferrer">http://clutter-project.org/</a></p>
<p>SDL is an excellent toolkit to work with. If you already understand the principles of "plain old DirectDraw or OpenGL," you should have no trouble with SDL. I haven't seen every graphics framework out there, but of the ones I have seen, I'd definitely recommend SDL. It's designed by experienced game programmers who know what they're doing because they've been there and done that, and it's interface is very intuitive. And unlike WPF, it's designed from the ground up for cross-platform compatibility.</p>
20,837
<p>I inherited an application which uses a java properties file to define configuration parameters such as database name. </p> <p>There is a class called MyAppProps that looks like this:</p> <pre><code>public class MyAppProps { protected static final String PROP_FILENAME = "myapp.properties"; protected static Properties myAppProps = null; public static final String DATABASE_NAME = "database_name"; public static final String DATABASE_USER = "database_user"; // etc... protected static void init() throws MyAppException { try { Classloader loader = MyAppException.class.getClassLoader(); InputStream is = loader.getResourceAsStream(PROP_FILENAME); myAppProps = new Properties(); myAppProps.load(is); } catch (Exception e) { threw new MyAppException(e.getMessage()); } } protected static String getProperty(String name) throws MyAppException { if (props==null) { throw new MyAppException("Properties was not initialized properly."); } return props.getProperty(name); } } </code></pre> <p>Other classes which need to get property values contain code such as:</p> <pre><code>String dbname = MyAppProps.getProperty(MyAppProps.DATABASE_NAME); </code></pre> <p>Of course, before the first call to MyAppProps.getProperty, MyAppProps needs to be initialized like this:</p> <pre><code>MyAppProps.init(); </code></pre> <p>I don't like the fact that <code>init()</code> needs to be called. Shouldn't the initialization take place in a static initialization block or in a private constructor?</p> <p>Besides for that, something else seems wrong with the code, and I can't quite put my finger on it. Are properties instances typically wrapped in a customized class? Is there anything else here that is wrong?</p>
<p>If I make my own wrapper class like this; I always prefer to make strongly typed getters for the values, instead of exposing all the inner workings through the static final variables.</p> <pre><code>private static final String DATABASE_NAME = "database_name" private static final String DATABASE_USER = "database_user" public String getDatabaseName(){ return getProperty(MyAppProps.DATABASE_NAME); } public String getDatabaseUser(){ return getProperty(MyAppProps.DATABASE_USER); } </code></pre> <p>A static initializer looks like this;</p> <pre><code>static { init(); } </code></pre> <p>This being said, I will readily say that I am no big fan of static initializers. </p> <p>You may consider looking into dependency injection (DI) frameworks like spring or guice, these will let you inject the appropriate value directly into the places you need to use them, instead of going through the indirection of the additional class. A lot of people find that using these frameworks reduces focus on this kind of plumbing code - but only after you've finished the learning curve of the framework. (DI frameworks are quick to learn but take quite some time to master, so this may be a bigger hammer than you really want)</p>
<p>You can use either, a static block or a constructor. The only advice I have is to use ResourceBundle, instead. That might better suit your requirement. For more please follow the link below.</p> <p><strong>Edit:</strong> <a href="http://www.russellbeattie.com/notebook/1007850.html" rel="nofollow noreferrer">ResourceBundles vs Properties</a></p>
49,332
<p>It's great to find all those little snippets of code on the Web for your current needs, but is there anything better than getting whole application source code at once and reading it like a book? There's no better way to learn positive and negative aspects of various architecture solutions.</p> <p>That's why I was trying to find some known/big websites with its source code published, but haven't found anything more than I knew already ( <a href="http://code.reddit.com/browser" rel="nofollow noreferrer">http://code.reddit.com/browser</a> )</p> <p>Do you know anything more? </p> <p>PS. Just being curious - have you heard about any unofficial big web site source code leak?</p>
<p>Wikipedia's source code (MediaWiki) can be found at <a href="http://www.mediawiki.org/" rel="nofollow noreferrer">http://www.mediawiki.org/</a></p> <p>The most relevant parts are</p> <ul> <li><a href="http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/" rel="nofollow noreferrer">"phase3"</a> (the core code; this strange name is because it was rewritten a couple of times)</li> <li><a href="http://svn.wikimedia.org/viewvc/mediawiki/trunk/extensions/" rel="nofollow noreferrer">extensions</a> (Wikipedia uses several of them; which ones can be seen at <a href="http://en.wikipedia.org/wiki/Special:Version" rel="nofollow noreferrer">Special:Version</a>)</li> </ul> <p>Additionally, here is a very detailed explanation of Wikipedia's whole architecture: <a href="http://dammit.lt/uc/workbook2007.pdf" rel="nofollow noreferrer">Wikipedia: Site internals, configuration, code examples and management issues</a>.</p>
<p>Check out Rob Conery's screencast series, <a href="http://blog.wekeroad.com/mvc-storefront/" rel="nofollow noreferrer">MVC Storefront</a>, where he builds a small commerce website using ASP.NET MVC.</p>
29,666
<p>We're currently using WinCVS but it's slow and has no merge dialog. I'm looking for something like Eclipse's Team Synchronize (so people can see what they'll get before they update).</p> <p>What do you suggest? <a href="http://www.tortoisecvs.org/" rel="noreferrer">TortoiseCVS</a> with <a href="http://winmerge.org/" rel="noreferrer">WinMerge</a>?</p> <p>Note: OSS preferred :)</p>
<p>On windows, definitely using Tortoise CVS and WinMerge will meet your needs. I also think it would be a good idea to learn how to do some operations with the command line too. </p>
<p>I was also searching for this currently. I got my eye on WinCVS and I liked it. but for my java projects I prefer eclipse which fulfills all my needs.. </p> <p>edit.. my bad.. didnt see the date :(</p>
38,248
<p>Some examples I found that apparently worked with older versions of mvc suggest that there was a length parameter of sorts:</p> <pre><code>&lt;%=Html.TextBox("test", 50)%&gt; </code></pre> <p>But that may have been mistakenly setting the value.</p> <p>How do this work in the current release? Passing in the style doesn't appear to have any effect.</p>
<p>The original answer is no longer working as written:</p> <pre><code>&lt;%=Html.TextBox("test", new { style="width:50px" })%&gt; </code></pre> <p>will get you a text box with "{ style="width:50px" }" as its text content.</p> <p>To adjust this for the current release of MVC 1.0, use the following script (note the addition of the second parameter - I have mine starting as blank, adjust accordingly based on your needs):</p> <pre><code>&lt;%=Html.TextBox("test", "", new { style="width:50px" })%&gt; </code></pre>
<p>new { style="width:50px", maxsize = 50 };</p> <p>should be</p> <p>new { style="width:50px", maxlength = 50 };</p>
42,041
<p>I need to be able to allow a user to enter Vietnamese text into a text box.</p> <p>I have been instructed to use VNI-Times and provided a sample word document with Vietnamese text.</p> <p>When I paste the text from the sample document into the textbox it is encoded incorrectly. I have tried installing the font (VNI-Times) on both my machine and the server, and changing the encoding of my browser, all to no avail. This problem is not localized to just the browser but also to notepad.</p> <p>I have found one solution so far, put a WYSIWYG editor on the page, but I am hoping to use the asp:TextBox control.</p> <p>Once the text is submitted by the user it is displayed back as an image that is generated by the server, these images are also not being generated correctly.</p>
<p>The Asian Language Pack needed to be installed on the server (Windows Server 2003).</p> <p>Once the server was migrated to Windows Server 2008 installing the VNI-Times font was sufficient to solve this problem.</p> <p>This has also allowed the images to be generated properly.</p>
<p>The problem is related to copying text with the clipboard. When you copy text from a text file in non-Unicode to a textbox that assumes Unicode, there is no encoding translation and the byte string is viewed incorrectly. Would you have used a keyboard to enter the Vietnamese text directly in the input controls (asp:TextBox) all is fine.</p> <p>The trick is to translate your text document to Unicode before you start copy and paste. Make sure the sample Word document is converted first and input controls will show the text correctly.</p> <p><a href="http://vietunicode.sourceforge.net/howto/unicodeconversion.html" rel="nofollow noreferrer">http://vietunicode.sourceforge.net/howto/unicodeconversion.html</a></p>
44,270
<p>I know this is a long shot - but is there any way at all to get code folding into Delphi 7?</p> <p>I'm working on some .. "suboptimal" .. code. Sometimes I really need to fold bits away to grok a stupid-long procedure. Currently I'm pasting code into Notepad++, which works, but it would be nice to have it in the IDE.</p>
<p>Look for "method folding" on this <a href="http://www.gexperts.org/faq.html" rel="noreferrer">FAQ</a> (for GExperts) and you'll see that even this team, which has added many enhancements to Delphi, doesn't think this is in the cards for Delphi 7. I've looked for solutions and haven't seen them.</p>
<p>As already mentioned, you could use the include file. But personally I don't like the idea of removing parts of code to another file, especially parts of a procedure (if I interpret your question the right way). I would prefer using bookmarks to rapidly navigate through the procedure, skipping the irrelevant parts, and the Ctrl+Shift+Up/Down key combinations to alternate between implementation and definition of methods.</p>
23,041
<p>I use int.MaxValue as a penalty and sometimes I am computing the penalties together. Is there a function or how would you create one with the most grace and efficiency that does that. </p> <p>ie. </p> <p>50 + 100 = 150</p> <p>int.Max + 50 = int.Max and not int.Min + 50 </p>
<pre><code>int penaltySum(int a, int b) { return (int.MaxValue - a &lt; b) ? int.MaxValue : a + b; } </code></pre> <p>Update: If your penalties can be negative, this would be more appropriate:</p> <pre><code>int penaltySum(int a, int b) { if (a &gt; 0 &amp;&amp; b &gt; 0) { return (int.MaxValue - a &lt; b) ? int.MaxValue : a + b; } if (a &lt; 0 &amp;&amp; b &lt; 0) { return (int.MinValue - a &gt; b) ? int.MinValue : a + b; } return a + b; } </code></pre>
<p>Does it overflow a lot, or is that an error condition? How about using try/catch (overflow exception)?</p>
15,861
<p>I read somewhere that NTP is based on UDP and there's no security built with NTP communication so it is easy to spoof NTP responses. Is it true? Wouldn't that be a major security issue since most of the servers out there depend on NTP to sync their clock?</p>
<p>here is an <a href="http://securityvulns.com/advisories/timesync.asp" rel="nofollow noreferrer">interesting article</a> that talks about some of the security concerns, it might be a bit dated, but a good read.</p>
<p>Yes, it is relatively easy and there are multiple exploits currently available. Most important to realize it that larger enterprises Sync NTP Timing through GPS, typically located within secure facilities. This minimizes the effectiveness of remote attacks. Therefore, the exploits and "hacking" causes more damage to organizations with 100 or less systems as most of those organizations do not have local timing and often rely on remote servers.</p>
30,992
<p>I am considering to apply Entity Framework in a new project because I liked its OR/M-API as well as the storage/conceptual model mapping-capabilities (plus Linq of course and Entity SQL).</p> <p>But how can loose coupling be achieved betwen the UI layer and the business layer if EF entities are used as dataholders in both. If I leave the entities attached to their ObjectContext while they reside in the UI, the UI might bypass the business layer and connect straight to the database. If I detach the entities from their ObjectContext before passing them to the UI, there will be no changetracking, so I have to "replay" all changes in the business layer for them to be persisted to the database (difficult to achieve, esp. with parent-child relations). While I don't want the business layer to degrade to a "object-tree-persistence-engine", there are scenarios where having this ability would be helpful.</p> <p>This certainly applies to other OR-mappers as well, but several alternative products seem to have somewhat better detaching/attaching mechanisms.</p>
<p>"Replaying" the changes is easier than you might think. Here's the general outline of what you need to do:</p> <ol> <li>Store the "original" version of the entity instance before you detach it and hand it to the UI.</li> <li>Let the UI do its thing.</li> <li>When you want to persist changes made by the UI to the database, take the original version that you stored, and attach it to the EntityContext. Apply the changes from the modified version returned by the UI to this instance. Now SaveChanges. The Entity Framework will handle the three-way merge.</li> </ol>
<p>Google "Entity framework" and "vote of no confidence" and see what you get.</p>
10,886
<p>I am starting a WPF project, which will be fairly complicated in complexity and will make use of a lot of modern UIs, like outlook bar, grids, tabs, etc... I've looked around in the marketplace and there aren't too many control suites. Some of the available ones are either Beta or CTP. Others don't look too polished. Yet others are pretty nice looking. </p> <p>At this point, today, should I buy or, bite the bullet and build my own? What are the experiences people are having with 1st generation control suites?</p>
<p>The thing to remember is that WPF is very different from WinForms, you can do amazing things buy just re-skining existing controls, when you are starting your first WPF big project you don't yet understand WPF and you don't know the possibilities and pitfalls of the system.</p> <p>I suggest you start developing the project without those controls and add them later, that way when you get around to adding those controls you will have a better feel of what controls you need and what controls are a trivial customization of an existing control.</p> <p>If you need anything that isn't trivial it's better to buy - but only if the component you buy is good, so evaluate carefully.</p> <p>and read Joel's "In Defense of Not-Invented-Here Syndrome" at <a href="http://www.joelonsoftware.com/articles/fog0000000007.html" rel="nofollow noreferrer">http://www.joelonsoftware.com/articles/fog0000000007.html</a></p>
<p>I would say to take a look on what it is already in there. In my point of view I am pretty much covered with the available ones, and especially in .NET 4, where the DataGridView, Calendar, and DateTimePicker are included (finally).</p> <p>But if you want also take a look in the components from a company named Infragistics. They are very powerful, but the documentation of them really sucks!</p>
45,714
<p>I'm using WinRAR SFX module to create an installation, and use its presetup option to run some preliminary tests.</p> <p>Since wscript can only accept vbs file, and not the script itself, I first run "cmd /c echo {...script code...} > setup.vbs", and then I run "wscript setup.vbs". The run of the first cmd command opens a brief command window, and I would really like to avoid this. I thought of using RunDll32 to write this data, but couldn't find any suitable API to use.</p> <p>Can anyone think of a way to bypass it and create a small file with a small VBScript text without opening a Command Prompt window?</p> <p>Thanks a lot,</p> <p>splintor</p>
<p>Is the script code already in a file? If so,</p> <p>You can use the TYPE command to send the script to a file:</p> <pre><code>TYPE [script_file] &gt; setup.vbs </code></pre> <p>or COPY the script file:</p> <pre><code>COPY [script_file] setup.vbs </code></pre> <p>If the script code is in the body of your <code>cmd</code>, you can use the <code>START</code> command to run the <code>cmd</code> without a window (<code>/b</code> flag):</p> <pre><code>START /B cmd /c echo {...script code...} &gt; setup.vbs </code></pre>
<p>Rather than use <code>cmd /c echo {...script code...} &gt; setup.vbs</code> as a presetup step, perhaps you could package a VBscript with your install that does your preliminary tests and creates <code>setup.vbs</code>, and then calls <code>setup.vbs</code> for you. You'd have to put this in the setup portion of the WinRAR script.</p> <p>You can call another VBScript from VBScript like this:</p> <pre><code>Set WSHShell = CreateObject("WScript.Shell") WSHShell.Run "wscript d:\setup.vbs, ,True </code></pre> <p>See <a href="http://msdn.microsoft.com/en-us/library/d5fk67ky(VS.85).aspx" rel="nofollow noreferrer">this MSDN link</a> for the syntax of the Run command.</p>
48,502
<p>All I know about the constraint is it's name (<code>SYS_C003415</code>), but I want to see it's definition.</p>
<p>Looks like I should be querying <code>ALL_CONSTRAINTS</code>.</p> <pre><code>select OWNER, CONSTRAINT_NAME, CONSTRAINT_TYPE, TABLE_NAME, SEARCH_CONDITION from ALL_CONSTRAINTS where CONSTRAINT_NAME = 'SYS_C003415'; </code></pre>
<p>Or to see all constaints use SYS.DBA_CONSTRAINTS (If you have the privileges)</p>
10,938
<p>We've got a webserver running IIS. We'd like to run maybe a shared blog or something to keep track of information. Because of security issues, we'd like for that part to be only viewable from localhost so people have to remote in to use it.</p> <p>So, to repeat my question, can part of a website be made viewable from localhost only?</p>
<p>For some one doing it in <code>IIS 8</code> / <code>Windows 2012</code></p> <p>1) In <code>Server Manager</code>, go to <code>Manage, Add Roles and Features</code>, Next, Next (get to <code>Server Roles</code>), scroll down to <code>Web Server (IIS)</code>, expand that row, then expand <code>Web Server</code>, and finally expand <code>Security</code>. Make sure that <strong>IP and Domain Restrictions</strong> are installed.</p> <p>2) In <code>IIS Manager</code>, drill down to the folder that you want to protect and left click select it. In the <code>Features View</code> of that folder select <strong>IP and Domain Restrictions</strong> In <code>Actions</code> choose <code>Edit Feature Settings</code>. Change <code>'Access for unspecified clients:'</code> to <code>'Deny'</code> then OK.</p> <p>3) Finally go to <code>'Add Allow Entry'</code> In the <code>Action</code>s menu. Type in the Specific IP address of your server.</p> <p>Now only requests coming from your server will be allowed access. Or any server that shares that IP address. So in a small network, the office could share the IP address between all of the PCs in that offices, so all of those PCs could access that folder.</p> <p>Last but not least is to remember that if your network has a dynamic IP address, then if that IP changes, you will expose your blog admin folder to whoever is using that IP now. Also, everyone on that new IP address will lose access to your that folder...</p>
<p>You could simply add this .NET to the top of the page.</p> <pre><code>string MyWebServerName = currentContext.Request.ServerVariables["SERVER_NAME"]; if ( MyWebServerName == "127.0.0.1" || MyWebServerName == "localhost" ) { // the user is local } else { // the user is NOT local } </code></pre>
33,962
<p>I have a java object with several members. I want to create a small, quick and dirty editor that allows me to set the value of the members in an easy way. I've created a Panel that contains a TextField for every member. I have a setValues() method that will take the value of the TextFields and set them into the object. This method is automatically invoked when I call getDataObject() from the panel. Some of the members contain Strings, some others are doubles and some are integers. Nothing fancy.</p> <p>The question is, however, what would be the easier way to improve this Panel? How can I add some validation without having to manually check every value? How can I do this without having to write a huge amount of code? At the moment my quick and very dirty implementation just propagates the RuntimeException, but of course this is only temporary.</p> <p>Before I set myself to write all this code, I wondered what would be the best pattern, or if there is some library available to perform such operations, as this seems to be a relatively commmon use case. In other words, if there is a lazy way out.</p>
<p>To answer your question directly, there is no such thing as a Intellij IDEA GUI WYSIWYG editor for GWT for the moment. </p> <p>The most popular/feature complete WYSIWYG editor for GWT is <a href="http://www.instantiations.com/windowbuilder/" rel="noreferrer">Instantiations GWT Designer</a>. It is available only for Eclipse though.</p> <p>The GWT team also provide a <a href="http://code.google.com/intl/nn/webtoolkit/tools.html" rel="noreferrer">list of tools and libraries.</a>. It seem rather incomplete though as it does not list Ext-GWT and GWT-Ext libraries (the most popular widget libraries).</p> <p>Be warned however that most WYSIWYG editor only support the basic widgets of GWT. If you have custom widget, you may not be able to use them in the editor.</p> <hr> <p>[Edit] As of August 2010, Instanciation has been acquired Google</p>
<p>Unfortunately, there really isn't one yet. We're going to have to wait until 2016 when Google takes over the world; everything will be so much easier then! ;)</p>
46,669
<p>In the <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml" rel="noreferrer">Google C++ Style Guide</a>, the <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Operator_Overloading" rel="noreferrer">section on Operator Overloading</a> recommends against overloading <em>any</em> operators ("except in rare, special circumstances"). Specifically, it recommends:</p> <blockquote> <p>In particular, do not overload <code>operator==</code> or <code>operator&lt;</code> just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container.</p> </blockquote> <p>I'm a little fuzzy on what such a functor would look like, but my main question is, <em>why</em> would you want to write your own functors for this? Wouldn't defining <code>operator&lt;</code>, and using the standard <code>std::less&lt;T&gt;</code> function, be simpler? Is there any advantage to using one over the other?</p>
<p>Except for the more fundamental types, the less-than operation isn't always trivial, and even equality may vary from situation to situation.</p> <p>Imagine the situation of an airline that wants to assign all passengers a boarding number. This number reflects the boarding order (of course). Now, what determines who comes before who? You might just take the order in which the customers registered – in that case, the less-than operation would compare the check-in times. You might also consider the price customers paid for their tickets – less-than would now compare ticket prices.</p> <p>… and so on. All in all, it's just not meaningful to define an <code>operator &lt;</code> on the <code>Passenger</code> class although it may be required to have passengers in a sorted container. I think that's what Google warns against.</p>
<p>Ironically, a functor also requires overriding an operator (the function call operator - <code>operator ()</code>), so I'm not sure what their point is.</p>
22,204
<p>I will explain problem with an example:</p> <p>There is two table in my database, named entry, tags</p> <p>There is a column named ID_ENTRY in both table. When I add a record to table, entry, I have to take the ID_ENTRY of last added record and add it to table, tags. How can I do it?</p>
<p>The only way to do this is with multiple statements. Using dynamic sql you can do this by separating each statement in your query string with a semi-colon:</p> <pre><code>"DECLARE @ID int;INSERT INTO [Entry] (...) VALUES ...; SELECT @ID = scope_identity();INSERT INTO [TAGS] (ID_ENTRY) VALUES (@ID);" </code></pre> <p>Make sure you put this in a transaction to protect against concurrency problems and keep it all atomic. You could also break that up into two separate queries to return the new ID value in the middle if you want; just make sure both queries are in the same transaction.</p> <p>Also: you are using parameterized queries with your dynamic sql, right? If you're not, I'll personally come over there and smack you 10,000 times with a wet noodle until you repent of your insecure ways.</p>
<p>I would probably do this with an INSERT trigger on the named entry table, if you have all of the data you need to push to the tags table available. If not, then you might want to consider using a stored procedure that creates both inside a transaction.</p> <p>If you want to do it in code, you'll need to be more specific about how you are managing your data. Are you using DataAdapter, DataTables, LINQ, NHibernate, ...? Essentially, you need to wrap both inserts inside a transaction of some sort so that either inserts get executed or neither do, but the means to doing that depend on what technology you are using to interact with the database.</p>
40,664
<p>Let's say I have a source file with many preprocessor directives. Is it possible to see how it looks after the preprocessor is done with it?</p>
<p><code>cl.exe</code>, the command line interface to Microsoft Visual C++, has three different options for outputting the preprocessed file (hence the inconsistency in the previous responses about Visual C++):</p> <ul> <li><code>/E</code>: <a href="http://msdn.microsoft.com/en-us/library/3xkfswhy.aspx" rel="noreferrer">preprocess to stdout</a> (similar to GCC's -E option)</li> <li><code>/P</code>: <a href="http://msdn.microsoft.com/en-us/library/8z9z0bx6.aspx" rel="noreferrer">preprocess to file</a></li> <li><code>/EP</code>: <a href="http://msdn.microsoft.com/en-us/library/becb7sys.aspx" rel="noreferrer">preprocess to stdout without #line directives</a></li> </ul> <p>If you want to preprocess to a file without #line directives, combine the <code>/P</code> and <code>/EP</code> options.</p>
<p><a href="http://cpip.sourceforge.net/" rel="nofollow noreferrer">CPIP</a> is a new C/C++ preprocessor written in Python. If you want a detailed visual representation of a preprocessed file, give it a shot.</p> <blockquote> <p>CPIP is a C/C++ pre-processor implemented in Python. Most pre-processors regard pre-processing as a dirty job that just has to be done as soon as possible. This can make it very hard to track down subtle defects at the pre-processing stage as pre-processors throw away a lot of useful information in favor of getting the result as cheaply as possible.</p> <p>Few developers really understand pre-processing, to many it is an obscure bit of black magic. CPIP aims to improve that and by recording every detail of preprocessing so CPIP can can produce some wonderfully visual information about file dependencies, macro usage and so on.</p> <p>CPIP is not designed to be a replacement for cpp (or any other established pre-processor), instead CPIP regards clarity and understanding as more important than speed of processing.</p> </blockquote>
34,986
<p>I picked up some no-name &quot;silk&quot; PLA in a multi color pack as part of a project where I needed some additional distinct colors and structural properties didn't matter, but now I'm playing with the excess I'm not using for that, and its behavior is really weird. On overhangs with detail on the downward-facing surface it's like everything flowed/melted together rather than retaining the extruded shape. And on vertical surfaces where one would expect to see layer lines, the lines are present and can be felt and slightly seen, but don't seem to contibute to the sheen/reflective properties like how they would in normal PLA or other materials. Together these observations make me suspect there's an additive that melts to a state where it flows much more than the base PLA at PLA printing temperatures, coalescing into more of a uniform smooth surface.</p> <p>What are the likely additives in &quot;silk PLA&quot; filaments, and what printing/mechanical properties should we expect from them?</p> <p>Some further observations: pushing it out of the hotend by hand, it has <em>a lot</em> of die swell, almost up to the original 1.75 mm diameter, and if tension is released it tries to retreat back into the nozzle. This suggests to me there might be some sort of foaming type additive involved, and also explains the behavior on overhangs.</p>
<p>It has additives to the PLA to change its characteristics.</p> <blockquote> <p>Typically, “silk” filaments are enhanced PLA filaments, owing their glossy result to various additives. As such, they tend to show most of the same pros and cons of PLA filament. In the case where silk filaments have a different base, these would be expected to have similar properties to the base material. For this article, we’ll focus mostly on PLA-based silk filaments.</p> </blockquote> <p>-- <a href="https://all3dp.com/2/silk-3d-printing-filament-brands-compared/" rel="nofollow noreferrer">Silk PLA Filament: Best Brands</a></p> <p>The article goes on to say that this does modify how the material prints and thus may need different parameters on your printer from normal PLA. You can get silk PLA in different brands. There doesn't seem to be a standard composition, so each brand may behave differently.</p>
<p>It has additives to the PLA to change its characteristics.</p> <blockquote> <p>Typically, “silk” filaments are enhanced PLA filaments, owing their glossy result to various additives. As such, they tend to show most of the same pros and cons of PLA filament. In the case where silk filaments have a different base, these would be expected to have similar properties to the base material. For this article, we’ll focus mostly on PLA-based silk filaments.</p> </blockquote> <p>-- <a href="https://all3dp.com/2/silk-3d-printing-filament-brands-compared/" rel="nofollow noreferrer">Silk PLA Filament: Best Brands</a></p> <p>The article goes on to say that this does modify how the material prints and thus may need different parameters on your printer from normal PLA. You can get silk PLA in different brands. There doesn't seem to be a standard composition, so each brand may behave differently.</p>
1,942
<p>I use eclipse to work on an application which was originally created independently of eclipse. As such, the application's directory structure is decidedly not eclipse-friendly.</p> <p>I want to programmatically generate a project for the application. The <code>.project</code> and <code>.classpath</code> files are easy enough to figure out, and I've learned that projects are stored in the workspace under <code>&lt;workspace&gt;/.metadata/.plugins/org.eclipse.core.resources/.projects</code></p> <p>Unfortunately, some of the files under here (particularly <code>.location</code>) seem to be encoded in some kind of binary format. On a hunch I tried to deserialize it using <code>ObjectInputStream</code> - no dice. So it doesn't appear to be a serialized java object.</p> <p>My question is: is there a way to generate these files automatically?</p> <p>For the curious, the error I get trying to deserialize the <code>.location</code> file is the following:</p> <p><code>java.io.StreamCorruptedException: java.io.StreamCorruptedException: invalid stream header: 40B18B81</code></p> <p><strong>Update:</strong> My goal here is to be able to replace the New Java Project wizard with a command-line script or program. The reason is the application in question is actually a very large J2EE/weblogic application, which I like to break down into a largish (nearly 20) collection of subprojects. Complicating matters, we use clearcase for SCM and create a new branch for every release. This means I need to recreate these projects for every development view (branch) I create. This happens often enough to automate.</p>
<p>You should be able to accomplish this by writing a small Eclipse plugin. You could even extend it out to being a "headless" RCP app, and pass in the command line arguments you need.</p> <p>The barebones code to create a project is:</p> <pre><code>IProgressMonitor progressMonitor = new NullProgressMonitor(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject("DesiredProjectName"); project.create(progressMonitor); project.open(progressMonitor); </code></pre> <p>Just take a look at the eclipse code for the Import Project wizard to give you a better idea of where to go with it.</p>
<p>To create java project you can use JavaCore from <code>org.eclipse.jdt.core.JavaCore</code>. As a <code>sourceProject</code> you can use generic project item, which has been suggested by @James Van Huis</p> <pre class="lang-java prettyprint-override"><code>IJavaProject javaSourceProject = JavaCore.create(sourceProject); </code></pre>
31,372
<p>I would like to throw an exception when my C++ methods encounter something weird and can't recover. Is it OK to throw a <code>std::string</code> pointer?</p> <p>Here's what I was looking forward to doing:</p> <pre><code>void Foo::Bar() { if(!QueryPerformanceTimer(&amp;m_baz)) { throw new std::string("it's the end of the world!"); } } void Foo::Caller() { try { this-&gt;Bar(); // should throw } catch(std::string *caught) { // not quite sure the syntax is OK here... std::cout &lt;&lt; "Got " &lt;&lt; caught &lt;&lt; std::endl; } } </code></pre>
<p>Yes. <a href="http://en.cppreference.com/w/cpp/error/exception" rel="noreferrer"><code>std::exception</code></a> is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?</p> <p>boost has an excellent <a href="http://www.boost.org/community/error_handling.html" rel="noreferrer">document</a> on good style for exceptions and error handling. It's worth a read.</p>
<p><strong>Simplest way to throw an Exception in C++:</strong></p> <pre><code>#include &lt;iostream&gt; using namespace std; void purturb(){ throw "Cannot purturb at this time."; } int main() { try{ purturb(); } catch(const char* msg){ cout &lt;&lt; "We caught a message: " &lt;&lt; msg &lt;&lt; endl; } cout &lt;&lt; "done"; return 0; } </code></pre> <p>This prints:</p> <pre><code>We caught a message: Cannot purturb at this time. done </code></pre> <p>If you catch the thrown exception, the exception is contained and the program will ontinue. If you do not catch the exception, then the program exists and prints: </p> <p><code>This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.</code></p>
16,289
<p>I know there is a similar problem on this forum, but the solutions did not really work for me. I am populating form controls with fields from a few different data sources, and the data shows up great.</p> <p>I have an <code>ImageButton</code> control, which has an <code>OnClick</code> Event set to grab all of the data from the form. Unfortunately, when I click the button, it seems as though the page is reloading first, and THEN is executes the <code>OnClick</code> call. The data that was hand-entered, or hard-coded seems to be pulled fine from the controls it was entered in, but anything that was pulled from a datasource is not able to be read. Any ideas. this is the last hurdle in a project that I have been working on for 6 months.</p>
<p>In EF, if you use this code, you have all the entities that are already loaded in the context (including newly added ones) :</p> <pre><code>context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Unchanged).Select(o =&gt; o.Entity).OfType&lt;YourObjectType&gt;() </code></pre>
<p>"The same question also applies to LinqToSql."</p> <p>For LINQ-to-SQL, look at <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.getchangeset.aspx" rel="nofollow noreferrer"><code>DataContext.GetChangeSet()</code></a>; this has <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.changeset_properties.aspx" rel="nofollow noreferrer">3 separate collections</a> for the pending <code>.Inserts</code>, <code>.Updates</code> and <code>.Deletes</code></p> <p>Note that the <code>ChangeSet</code> is a snapshot of when the <code>GetChangeSet()</code> method is called; you need to re-query to see any additional changes.</p>
42,259
<p>Lets say you have a:</p> <pre><code>List&lt;string&gt; los = new List&lt;string&gt;(); </code></pre> <p>In this crazy functional world we live in these days which one of these would be best for creating one string by concatenating these:</p> <pre><code>String.Join(String.Empty, los.ToArray()); StringBuilder builder = new StringBuilder(); los.ForEach(s =&gt; builder.Append(s)); string disp = los.Aggregate&lt;string&gt;((a, b) =&gt; a + b); </code></pre> <p>or Plain old StringBuilder foreach</p> <p>OR is there a better way?</p>
<p>I would go with option A:</p> <pre><code>String.Join(String.Empty, los.ToArray()); </code></pre> <p>My reasoning is because the Join method was written for that purpose. In fact if you look at Reflector, you'll see that unsafe code was used to really optimize it. The other two also WORK, but I think the Join function was written for this purpose, and I would guess, the most efficient. I could be wrong though...</p> <p>As per @Nuri YILMAZ without <code>.ToArray()</code>, but this is .NET 4+:</p> <pre><code>String.Join(String.Empty, los); </code></pre>
<p>My vote is string.Join</p> <p>No need for lambda evaluations and temporary functions to be created, fewer function calls, less stack pushing and popping.</p>
41,203
<p>I have been experimenting with <a href="http://www.woopra.com/" rel="nofollow noreferrer">woopra.com</a> A web analytics tool. Which requires a piece of javascript code to be added to each page to function. This is easy enough with more dynamic sites with universal headers or footers but not for totally static html pages.</p> <p>I attempted to work round it by using a combination of Apache rewrites and SSI's to &quot;Wrap&quot; the static html with the required code. For example...</p> <p>I made the following changes to my apache config</p> <pre><code> RewriteEngine On RewriteCond %{REQUEST_URI} !=test.shtml RewriteCond %{IS_SUBREQ} false RewriteRule (.*)\.html test.shtml?$1.html </code></pre> <p>The test.shtml file contains...</p> <pre><code> &lt;script type=&quot;text/javascript&quot;&gt; var XXXXid = 'xxxxxxx'; &lt;/script&gt; &lt;script src=&quot;http://xxxx.woopra.com/xx/xxx.js&quot;&gt;&lt;/script&gt; &lt;!--#set var=&quot;page&quot; value=&quot;$QUERY_STRING&quot; --&gt; &lt;!--#include virtual= $page --&gt; </code></pre> <p>The idea was that a request coming in for</p> <pre><code> /abc.html </code></pre> <p>would be redirected to</p> <pre><code> /test.shtml?abc.html </code></pre> <p>the shtml would then include the original file into the response page.</p> <p>Unfortunately it doesn't quite work as planed :) can anyone see what I am doing wrong or perhaps suggest an alternative approach. Is there any apache modules that could do the same thing. Preferably that can be configured on a per site basis.</p> <p>Thanks</p> <p>Peter</p>
<p>I think that <a href="http://httpd.apache.org/docs/2.2/mod/mod_ext_filter.html" rel="nofollow noreferrer">mod_filter_ext</a> is the module you are looking for. You can write a short Perl script for example to insert the JS code in the pages and register it to process HTML pages:</p> <pre><code>while (&lt;&gt;) { s/&lt;html&gt;/\Q&lt;script&gt;....\E/; print $_; } </code></pre> <p>You could even use something like <code>sed</code> to perform the substitution.</p>
<p>ok the method above's biggest problem is it would break your html validity by placing a script tag outside the <code>&lt;html&gt;</code> tags</p> <p>i'd agree with the others on a pre-process run over your html files such as a sed/awk script</p> <p>heres a quick example {assuming the script part can be added before the <code>&lt;/head&gt;</code> and that the <code>&lt;/head&gt;</code> is at the start of a newline</p> <pre><code>#!/bin/bash cd /var/webserver/whatever/ grep -r '&lt;\/head&gt;' */*|grep "^.*\.html*:" &gt;/var/tmp/tempfile.txt ((lines = $(wc -l /var/tmp/dom-tempfile.txt | awk '{print $1}'))) if [ $lines -gt 0 ] then while read line; do sed 's/&lt;script type="text\/javascript"&gt; var XXXXid = "xxxxxxx"; &lt;\/script&gt;&lt;script src="http:\/\/xxxx\.woopra\.com\/xx\/xxx\.js"&gt;&lt;\/script&gt;&lt;\/head&gt;/^&lt;\/head&gt;/g' $line&gt;/var/tmp/tempfile.htm mv /var/tmp/tempfile.htm $line done &lt; &lt;(sed 's/\(^.*\.html*\):.*$/\1/' /var/tmp/tempfile.txt) fi exit 0 </code></pre>
6,136
<p>For example, how much memory is required to store a list of one million (32-bit) integers?</p> <pre><code>alist = range(1000000) # or list(range(1000000)) in Python 3.0 </code></pre>
<p>"It depends." Python allocates space for lists in such a way as to achieve <a href="http://effbot.org/zone/python-list.htm" rel="noreferrer">amortized constant time</a> for appending elements to the list.</p> <p>In practice, what this means with the current implementation is... the list always has space allocated for a power-of-two number of elements. So range(1000000) will actually allocate a list big enough to hold 2^20 elements (~ 1.045 million).</p> <p>This is only the space required to store the list structure itself (which is an array of pointers to the Python objects for each element). A 32-bit system will require 4 bytes per element, a 64-bit system will use 8 bytes per element.</p> <p>Furthermore, you need space to store the actual elements. This varies widely. For small integers (-5 to 256 currently), no additional space is needed, but for larger numbers Python allocates a new object for each integer, which takes 10-100 bytes and tends to fragment memory.</p> <p>Bottom line: <b>it's complicated</b> and Python lists are <b>not</b> a good way to store large homogeneous data structures. For that, use the <code>array</code> module or, if you need to do vectorized math, use NumPy.</p> <p>PS- Tuples, unlike lists, are <i>not designed</i> to have elements progressively appended to them. I don't know how the allocator works, but don't even think about using it for large data structures :-)</p>
<p>This is implementation specific, I'm pretty sure. Certainly it depends on the internal representation of integers - you can't assume they'll be stored as 32-bit since Python gives you arbitrarily large integers so perhaps small ints are stored more compactly. </p> <p>On my Python (2.5.1 on Fedora 9 on core 2 duo) the VmSize before allocation is 6896kB, after is 22684kB. After one more million element assignment, VmSize goes to 38340kB. This very grossly indicates around 16000kB for 1000000 integers, which is around 16 bytes per integer. That suggests a <em>lot</em> of overhead for the list. I'd take these numbers with a large pinch of salt.</p>
16,427
<p>Heres a screenshot to make it clear. I'm trying to figure out a robust way of making the bullet images vertically aligned to my li content. As you can see my content is currently too high.</p> <p>Many thanks 'over-flowers'...</p> <p><a href="http://dl.getdropbox.com/u/240752/list-example.gif" rel="nofollow noreferrer">http://dl.getdropbox.com/u/240752/list-example.gif</a></p>
<p>Well, some css code to see how you currently set your bullet images would be useful ;-)</p> <p>Instead of actually setting the 'list-style-image' property, I've had far more consistent results with setting a background-image property for the li element. You can then control the positioning with pixel accuracy. Remember to set a suitable left-padding value to push your list item contents clear of the bullet image.</p>
<p>You can use something like this in your css...</p> <pre><code>#content li{ list-style-image: url(../images/bullet.gif); } </code></pre>
26,778
<p>I had created the xml document with xml version="1.0".</p> <p>In that document I need to use the greater than symbol <code>&gt;</code> and less than symbol <code>&lt;</code>.</p> <p>How should I include those symbols? It's not working.</p> <p><code>&amp;gt;</code> and <code>&amp;lt;</code> are not working for me.</p> <p>Is there any special encoder for this?</p>
<p>You need the <a href="http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references" rel="noreferrer">Character Entity References</a></p> <p><code>&lt; = &amp;lt;</code></p> <p><code>&gt; = &amp;gt;</code></p>
<p>Use <code>&amp;gt;</code> and <code>&amp;lt;</code> for 'greater-than' and 'less-than' respectively</p>
42,844
<p>I suppose this is a strange question to the huge majority of programmers that work daily with Java. I don't. I know Java-the-language, because I worked on Java projects, but not Java-the-world. I never made a web app from scratch in Java. If I have to do it with Python, Ruby, I know where to go (Django or Rails), but if I want to make a web application in Clojure, not because I'm forced to live in a Java world, but because I like the language and I want to give it a try, what libraries and frameworks should I use?</p>
<p>By far the best Clojure web framework I have yet encountered is Compojure: <a href="http://github.com/weavejester/compojure/tree/master" rel="noreferrer">http://github.com/weavejester/compojure/tree/master</a></p> <p>It's small but powerful, and has beautifully elegant syntax. (It uses Jetty under the hood, but it hides the Servlet API from you unless you want it, which won't be often). Go look at the README at that URL, then download a snapshot and start playing.</p>
<p><a href="http://arachne-framework.org/" rel="nofollow noreferrer">Arachne</a> is a newcomer web framework. Quoting the site's description:</p> <blockquote> <p>Arachne is a full, highly modular web development framework for Clojure. It emphasizes ease, simplicity, and a solid, scalable design.</p> </blockquote> <p>It has a <a href="https://www.kickstarter.com/projects/1346708779/arachne-rapid-web-development-for-clojure" rel="nofollow noreferrer">kickstarter campaign</a> claiming to offer a "getting started" experience similar to Rails. It is developed by a Cognitect.</p> <p><a href="https://www.reddit.com/r/Clojure/comments/4f2j1w/introducing_arachne_a_full_rapiddevelopment_web/" rel="nofollow noreferrer">Here</a> is a good discussion about it with the author of Luminus (yogthos).</p>
20,201
<p>I just re-ran all basic calibration steps from the Original Prusa i3 MK2 Manual.</p> <p>Now, when doing the first layer calibration, lines that are running in positive X direction are ok, while those running in negative X direction are severely squished.</p> <p><a href="https://i.stack.imgur.com/5zzEl.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/5zzEl.jpg" alt="Print of the default V2Calibration.gcode file on my Prusa i3 MK2"></a> <em>(The "waviness" of my print bed is an artifact of the camera lens distortion of my smartphone)</em></p> <p>I already did Bed level correction, so each line is exactly the same width over its entire distance and tried to raise the live-adjust Z, but that leads to the thin lines not adhering at all. My printer is 100% stock, I modified nothing about it. </p> <p>What can I do to troubleshoot this further?</p>
<h2>No FDM print at all.</h2> <p>The problem of your design will not be the materials, but a basic property of FDM printing: FDM Printers do create a structure by placing a long string of filament next to itself and ontop of itself, creating tons of boudaries.</p> <p>These boundaries between the layers are the weak points for this application: Even if the material like ABS could withstand the blow handled with such a club, the print will break at its weakest point - which in this case is any layer boundary. This is amplyfied by the basic design we have here: The elongated shape will serve as a lever on each of the weak boundries, until one gives way and results in catastrophic failure and a flying clubhead.</p> <h1>Non-FDM for the rescue.</h1> <p>To counteract this, you need to use a different method than FDM printing to get a more homogenous material than the bound deposited filament. Such methods could be for example SLA (Stereolithography) or SLS (Selective Laser Sintering). Both could easily offer even tiny details.</p> <p>SLS uses Nylon or metal powders, sometimes even ceramics - Tungstencarbide for example.</p> <h3>SLA/Resin</h3> <p>Using a Resin printer using the SLA methods results in an object almost as homogenous as an injecion molded object. Proper aftercare and curing is required to get the best results. Also, Resin prints usually age under UV light, which can negatively impact lifetime. SLA printers are expensive (for home printers), print shops that offer them relatively rare and costly (in comparison to FDM) but usually offer superb resolution and almost perfect smoothness. A lot of the exact material properties is resin and aftercare dependant.</p> <p>A way around the aging could be that the results of an SLA print could be used to create green-sand molds countless times, which can be used for casting metal or even some thermoplastics. Remember though, that cooling metal shrinks.</p> <h3>SLS Nylon</h3> <p>Nylon would be a medium rigid, light solution, but it ages and has a quite rough surface. It does offer some flex, almost perfect for this application. While most SLS machines for nylon are commercial to industrial, print technology of this kind is widespread enough to make them somewhat affordable (for an industrial printer) and printshops for these relatively common, prints are not cheap but well priced.</p> <h3>DMLS / SLM</h3> <p>Direct Metal Laser Sintering and Selective Laser Melting - an evolution of SLS - allows to create structures from various metals by sintering/melting powders of metal at the right spot to gain shape. The benefit would be, that you get a part that could withstand much more destructive testing than your bottle used as a clubhead - you get a workpiece of solid metal (Steel, aluminium, Titanium and a lot others are available) after all that has the same properties as a cast item. The big downside is, that only few companies currently delve into DMLS, among them the former patent holder of many of the FDM printing patents, <a href="https://www.stratasysdirect.com/technologies/direct-metal-laser-sintering" rel="nofollow noreferrer">Stratasys</a>. This means, that a machine for this is industrial rated and priced, and that print suppliers charge accordingly.</p>
<h2>No FDM print at all.</h2> <p>The problem of your design will not be the materials, but a basic property of FDM printing: FDM Printers do create a structure by placing a long string of filament next to itself and ontop of itself, creating tons of boudaries.</p> <p>These boundaries between the layers are the weak points for this application: Even if the material like ABS could withstand the blow handled with such a club, the print will break at its weakest point - which in this case is any layer boundary. This is amplyfied by the basic design we have here: The elongated shape will serve as a lever on each of the weak boundries, until one gives way and results in catastrophic failure and a flying clubhead.</p> <h1>Non-FDM for the rescue.</h1> <p>To counteract this, you need to use a different method than FDM printing to get a more homogenous material than the bound deposited filament. Such methods could be for example SLA (Stereolithography) or SLS (Selective Laser Sintering). Both could easily offer even tiny details.</p> <p>SLS uses Nylon or metal powders, sometimes even ceramics - Tungstencarbide for example.</p> <h3>SLA/Resin</h3> <p>Using a Resin printer using the SLA methods results in an object almost as homogenous as an injecion molded object. Proper aftercare and curing is required to get the best results. Also, Resin prints usually age under UV light, which can negatively impact lifetime. SLA printers are expensive (for home printers), print shops that offer them relatively rare and costly (in comparison to FDM) but usually offer superb resolution and almost perfect smoothness. A lot of the exact material properties is resin and aftercare dependant.</p> <p>A way around the aging could be that the results of an SLA print could be used to create green-sand molds countless times, which can be used for casting metal or even some thermoplastics. Remember though, that cooling metal shrinks.</p> <h3>SLS Nylon</h3> <p>Nylon would be a medium rigid, light solution, but it ages and has a quite rough surface. It does offer some flex, almost perfect for this application. While most SLS machines for nylon are commercial to industrial, print technology of this kind is widespread enough to make them somewhat affordable (for an industrial printer) and printshops for these relatively common, prints are not cheap but well priced.</p> <h3>DMLS / SLM</h3> <p>Direct Metal Laser Sintering and Selective Laser Melting - an evolution of SLS - allows to create structures from various metals by sintering/melting powders of metal at the right spot to gain shape. The benefit would be, that you get a part that could withstand much more destructive testing than your bottle used as a clubhead - you get a workpiece of solid metal (Steel, aluminium, Titanium and a lot others are available) after all that has the same properties as a cast item. The big downside is, that only few companies currently delve into DMLS, among them the former patent holder of many of the FDM printing patents, <a href="https://www.stratasysdirect.com/technologies/direct-metal-laser-sintering" rel="nofollow noreferrer">Stratasys</a>. This means, that a machine for this is industrial rated and priced, and that print suppliers charge accordingly.</p>
942
<p>We use Sharepoint as CMS for our webpages at work. I know how to create controls that can be only visible if you have logged in in SharePoint with:</p> <p>&lt;Sharepoint:SPSecurityTrimmedControl ID=&quot;SPSecurityTrimmedControl1&quot; runat=&quot;server&quot; PermissionsString=&quot;AddAndCustomizePages&quot;&gt;&lt;br /&gt;<br /> &lt;Sharepoint:CssLink ID=&quot;CssLink1&quot; runat=&quot;server&quot;/&gt;&lt;br /&gt;<br /> &lt;/Sharepoint:SPSecurityTrimmedControl&gt;</p> <p>But I want to know how to make controls visible (or whatever) programmatically depending on permissions. </p> <p>I cannot use the methods for .NET windows form authentication like:</p> <pre><code> if (!(HttpContext.Current.User == null) &amp;&amp; HttpContext.Current.User.Identity.IsAuthenticated){} </code></pre> <p>because we use this for anonymous users who has another type of log in.</p> <p>Could you provide some code? I know that it must be something like verifying the SPContext.Current.FormContext.</p>
<p>How are the users authenticated? With forms authentication or Windows/active directory?</p> <p>If active directory, then I think in that case you might need to get a reference to the current SPWeb, and then do web.CurrentUser.ID. This might come out null when you are anonymous. If not, try web.SiteUsers.GetByID(web.CurrentUser.ID) and see what you get.</p>
<p>Although I haven't tested it, I imagine the LoginName property of the SPUser object will be blank, or throw an exception.</p> <p>... of course, its never safe to presume anything when dealing w/the SharePoint OM :(</p>
49,903
<p>First, I am Linq to Sql newbie, so please be gentle :).</p> <p>I have existing ASP.Net application developed over last 3.5 years. It has pretty big data model underneath, around 350 tables. I am trying to do some new things with Linq to SQL. </p> <p>First impression is that linq designer and SqlMetal are built for databases not bigger than NorthWind example. Here are some problems I have:</p> <ol> <li>I have table <code>Products</code> that is needed in lots of places (inventory, invoicing, production, ...). If I put table <code>Products</code> in each dbml file, linq designer is going to create <code>Product</code> class in each of them. I don't want that. I want to only one <code>Product</code> class.</li> <li>I have DataContext about shipping. It needs around 40 tables. This makes dbml file very hard to manage. Is there a way to create smaller dbml files and then include them (as reference) into some "major" dbml?</li> </ol> <p>For now, I really like Linq, but I think it is still seriously lacking design tool for anything bigger than 10 tables.</p> <p>My solution now is building smaller models with Linq designer and then manually merging them (adding properties and references), so lots of code will be generated, but there will also be lots of manual work. </p> <p>Did I miss something big or is this current state of affair with Linq to Sql?</p>
<p>well, my solution was to use SQLMetal's <code>/code</code> option to create plain classes in a .cs file instead of a DBML file, and use partial classes in a separate file to extend the generated ORM classes. </p> <p>I know that doesn't solve your issue of splitting parts of your database into different ORM assemblies - I just found that without the headache of the DBML / Designer, managing a large number of classes in a .cs file wasn't too bad.</p>
<p>If I were you I would be using <a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" rel="nofollow noreferrer">Entity Framework</a> as this is the MS recommended ORM going forward <a href="http://ayende.com/Blog/archive/2008/10/31/microsoft-kills-linq-to-sql.aspx" rel="nofollow noreferrer">Microsoft kills Linq to SQL</a> </p>
34,651
<p>There are several application systems that pass messages to each other as part of their work process. Due to technical constraints revolving transactional integrity, the application data and message delivery are all committed into a single mainframe DB2 database. The messages are not directly passed to BizTalk server (2006 R2); it is up to BTS to pull the message out from the DB2 database later.</p> <p>The message-queue table in the DB2 database has several fields. The key field is the MESSAGE_DATA column - the actual message; it is XML content itself. When one uses the DB2 adapter to query out records from the table the incoming schema would be like</p> <p>CORRECTION UPDATE: the DB2Message schema is attribute based; I mistook it previously to be element based.</p> <pre><code>&lt;DB2Message MESSAGE_DATA="&amp;lt;InternalXML&amp;gt; ........ &amp;lt;/InternalXML&amp;gt;" MESSAGE_DATE="2008-1-1 00:00:00" MESSAGE_ID="GUID" TXN_ID="GUID" .... other attrib /&gt; </code></pre> <p>The orchestration consumes the schema</p> <pre><code>&lt;EAIMessage&gt; &lt;Header&gt; &lt;ServiceID&gt; &lt;MessageID&gt; .... &lt;Mode&gt; &lt;/Header&gt; &lt;Body&gt; &lt;RawXML&gt; &lt;/Body&gt; &lt;/EAIMessage&gt; </code></pre> <p>The orchestration will use several promoted fields in the Header to make routing and processing decisions. The thing is, those header fields are actually coming from the inner-XML content stored into DB2Message's MESSAGE_DATA.</p> <p>At this single level, the Mapper has no knowledge of this underyling XML schema inside MESSAGE_DATA when pitting the two schemas together. There should probably be some XPath functoid that can further drill down the MESSAGET_DATA element to conduct the proper mapping of values, but having not dealt with extensive XML and XSLT applications before, I am unable to see the features available that can help me perform this task.</p> <p>Has anybody done such data extraction and mapping before?</p> <p>UPDATE. As requested, in the MESSAGE_DATA inner XML may look like</p> <pre><code>&lt;Message&gt; &lt;Id&gt;e86970f4-0455-4535-8e65-a06eb7aaef8a&lt;/Id&gt; &lt;SenderApp&gt;999&lt;/SenderApp&gt; &lt;ReceiverApp&gt;2000&lt;/ReceiverApp&gt; &lt;ServiceId&gt;8798973454&lt;/ServiceId&gt; &lt;Mode&gt;P&lt;/Mode&gt; &lt;MuxId&gt;&lt;/MuxId&gt; &lt;ExceptionCode&gt;&lt;/ExceptionCode&gt; &lt;ExceptionMessage&gt;&lt;/ExceptionMessage&gt; &lt;Body&gt; &lt;WorkItem xmlns="http://tempuri.org/WorkItem.xsd"&gt; &lt;ServiceHeader xmlns="http://tempuri.org/Service.xsd"&gt; &lt;ID_UPDATED_BY&gt;username&lt;/ID_UPDATED_BY&gt; &lt;ID_HISTORY_REF&gt;xxxxxxx&lt;/ID_HISTORY_REF&gt; &lt;SESSION_ID&gt;sessionID&lt;/SESSION_ID&gt; &lt;DT_LAST_UPDATE&gt;timestamp&lt;/DT_LAST_UPDATE&gt; &lt;TM_LAST_UPDATE&gt;time&lt;/TM_LAST_UPDATE&gt; &lt;/ServiceHeader&gt; &lt;/WorkItem&gt; &lt;/Body&gt; &lt;/Message&gt; </code></pre>
<p>Chris is correct - it seems it's only the inner part of the message you actually care about, the outer part is just an envelope.</p> <p>As such I would suggest you create a disassembler which, in the receive pipeline, will strip out the envelope (you can keep it in it's entirety as a context property and/or extract some bits from it as individual properties, if you need to act on them), and extract the inner part which would become the message published into the Message Box. </p> <p>Now the real message is the one get's processed, but the rest of the send port and any subscriber, and whatever information you require from the envelope flows with it through its context.</p> <p>Now you have full access to the message and it's properties; if applicable you can deploy a schema for this message, which could have distinguished properties which would give you quick access to some (simple type) nodes. alternatively you can use xlang/s xpath to extract the information.</p> <p>If your embedded message was inside an element in the envelope you could certainly use the built in XmlDisassembler to do all of this (you would just need to deploy your schemas correctly and configure the component accordingly; I'm not sure how well this works with a message contained within an attribute, but it's probably worth a try. </p> <p>Worst case you are looking at writing a custom disassembler that would strip the envelope and then call the built-in disassembler to process the internal message, but that should not be too much effort as well.</p>
<p>I would suggest looking into envelope schemas to 'unwrap' the interior message from the outer message. I believe the envelope can promote properties from the envelope into the inner message's context as it moves through the receive pipeline. The inner message will then have to map to a schema of its own type. You will then be able to route or make decisions based on the schema type and use XPath to pick out whatever you need. Have not tried all of these things, but I am certain the functionality exists to do do this. </p>
31,894
<p>The canonical way to return multiple values in languages that support it is often <a href="https://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>.</p> <h3>Option: Using a tuple</h3> <p>Consider this trivial example:</p> <pre><code>def f(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0, y1, y2) </code></pre> <p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p> <h3>Option: Using a dictionary</h3> <p>The next logical step seems to be to introduce some sort of 'record notation'. In Python, the obvious way to do this is by means of a <code>dict</code>.</p> <p>Consider the following:</p> <pre><code>def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return {'y0': y0, 'y1': y1 ,'y2': y2} </code></pre> <p>(Just to be clear, y0, y1, and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers.)</p> <p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example,</p> <pre><code>result['y0'] </code></pre> <h3>Option: Using a class</h3> <p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p> <pre><code>class ReturnValue: def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2) </code></pre> <p>In Python the previous two are perhaps very similar in terms of plumbing - after all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p> <p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p> <pre><code>class ReturnValue(object): __slots__ = [&quot;y0&quot;, &quot;y1&quot;, &quot;y2&quot;] def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 </code></pre> <p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html" rel="noreferrer">Python Reference Manual</a>:</p> <blockquote> <p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p> </blockquote> <h3>Option: Using a <a href="https://docs.python.org/3/library/dataclasses.html" rel="noreferrer">dataclass</a> (Python 3.7+)</h3> <p>Using Python 3.7's new dataclasses, return a class with automatically added special methods, typing and other useful tools:</p> <pre><code>@dataclass class Returnvalue: y0: int y1: float y3: int def total_cost(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2) </code></pre> <h3>Option: Using a list</h3> <p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p> <pre><code>def h(x): result = [x + 1] result.append(x * 3) result.append(y0 ** y3) return result </code></pre> <p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be.</p> <p>A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable" rel="noreferrer">mutable</a>, whereas tuples are not.</p> <p>I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p> <h1>Question</h1> <p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p>
<p><a href="http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields" rel="noreferrer">Named tuples</a> were added in 2.6 for this purpose. Also see <a href="http://docs.python.org/library/os.html#os.stat" rel="noreferrer">os.stat</a> for a similar builtin example.</p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; Point = collections.namedtuple('Point', ['x', 'y']) &gt;&gt;&gt; p = Point(1, y=2) &gt;&gt;&gt; p.x, p.y 1 2 &gt;&gt;&gt; p[0], p[1] 1 2 </code></pre> <p>In recent versions of Python 3 (3.6+, I think), the new <code>typing</code> library got the <a href="https://docs.python.org/3/library/typing.html#typing.NamedTuple" rel="noreferrer"><code>NamedTuple</code></a> class to make named tuples easier to create and more powerful. Inheriting from <code>typing.NamedTuple</code> lets you use docstrings, default values, and type annotations.</p> <p>Example (From the docs):</p> <pre><code>class Employee(NamedTuple): # inherit from typing.NamedTuple name: str id: int = 3 # default value employee = Employee('Guido') assert employee.id == 3 </code></pre>
<p>In languages like Python, I would usually use a dictionary as it involves less overhead than creating a new class.</p> <p>However, if I find myself constantly returning the same set of variables, then that probably involves a new class that I'll factor out.</p>
46,242
<p>I've used <a href="http://members.fortunecity.com/neshkov/dj.html" rel="noreferrer">DJ Java Decompiler</a>, which has a handy GUI, but it seems as if the latest version is only a trial and forces you to purchase the software after some period of days (I recall using an earlier free version about a year ago at a previous job).</p> <p>I'm aware of Jad and Jadclipse, but what I loved about DJ Java Decompiler was that it integrated with Windows Explorer - so I could simply open up a JAR in something like WinRAR, navigate thru the packages, and double-click on a .class file to view it's decompiled source.</p> <p>Can anyone suggest other good, free, .class viewers? The criteria I have in mind for these would be: </p> <ul> <li>GUI-based</li> <li>Integrates to Windows Explorer (so I don't have to run some command-line options like with JAD)</li> <li>optional - can also show raw JVM bytecode commands </li> </ul> <p>In other words - I'd like to find the closest thing to <a href="http://www.red-gate.com/products/reflector/index.htm" rel="noreferrer">.NET Reflector</a> for Java as possible.</p>
<p>JAD is one of the best Java Decompiler today. This is one brilliant piece of software. Nevertheless, the last JDK supported by JAD 1.5.8 (Apr 14, 2001) is JDK 1.3.</p> <p>DJ Java Decompiler, JadClipse, Cavaj and JarInspector are powered by Jad. The last version of Decafe Pro has been released on 2002-01-03.</p> <p>These viewers can not display Java 5 sources.</p> <p>So, I use <a href="http://jd.benow.ca/" rel="noreferrer">JD-GUI</a> : logic, I'm the author :)</p>
<p>Many of these decompilers are based on Jad:</p> <ul> <li><a href="http://www.kpdus.com/jad.html" rel="nofollow noreferrer">http://www.kpdus.com/jad.html</a></li> </ul> <p>I like the JadClipse Eclipse plugin:</p> <ul> <li><a href="http://sourceforge.net/projects/jadclipse" rel="nofollow noreferrer">http://sourceforge.net/projects/jadclipse</a></li> </ul>
24,774
<p>What update rate should I run my fixed-rate game logic at?</p> <p>I've used 60 updates per second in the past, but that's hard because it's not an even number of updates per second (16.666666). My current games uses 100, but that seems like overkill for most things.</p>
<p>None of the above. For the smoothest gameplay possible, your game should be time-based, not frame-locked. Frame-locking works for simple games where you can tweak the logic and lock down the framerate. It doesn't do so well with modern 3D titles where the framerate jumps all over the board and the screen may not be VSynced. </p> <p>All you need to do is figure out how fast an object should be going (i.e. virtual units per second), compute the amount of time since the last frame, scale the number of virtual units to match the amount of time that has passed, then add those values to your object's position. Voila! Time-based movement.</p>
<p>Bear in mind that unless your code is measured down to the cycle, not each game loop will take the same number of milliseconds to complete - so 16.6666 being irrational is not an issue really as you will need to time and compensate anyway. Besides it's not 16.6666 updates per second, but the average number of milliseconds your game loop should be targeting.</p>
11,372
<p>Alright so I'm essentialyl trying to code something that will combine two files together in VB and output a single file that when run, runs both of them. I've grabbed this source from several places online and am just trying to get it to work. We have the main program that combines them with a GUI</p> <pre><code>Const FileSplit = "@&lt;&gt;#&lt;&gt;#&lt;&gt;@" Private Sub cmdAdd_Click() With Dlg .Filter = "All Files(*.*) | *.*" .DialogTitle = "Please Select a File..." .ShowOpen End With lsFiles.AddItem (Dlg.FileName) End Sub Private Sub cmdBuild_Click() Dim sStub As String, sFiles As String, i As Integer Open App.Path &amp; "\stub.exe" For Binary As #1 sStub = Space(LOF(1)) Get #1, , sStub Close #1 Open App.Path &amp; "\boundfile.exe" For Binary As #1 Put #1, , sStub &amp; FileSplit For i = 0 To lsFiles.ListCount - 1 Open lsFiles.List(i) For Binary As #2 sFiles = Space(LOF(2)) Get #2, , sFiles Close #2 Put #1, , sFiles &amp; FileSplit Next i Close #1 MsgBox "Files Successfully Combined" End Sub </code></pre> <p>And then we have a second App that acts as a stub</p> <pre><code>Const FileSplit = "@&lt;&gt;#&lt;&gt;#&lt;&gt;@" Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long Private Sub Form_Load() Dim sStub As String, sFiles() As String, i As Integer Open App.Path &amp; "\" &amp; App.EXEName &amp; ".exe" For Binary As #1 sStub = Input(LOF(1), 1) Get #1, , stub Close #1 sFiles = Split(sStub, FileSplit) For i = 1 To UBound(sFiles()) Open Environ("tmp") &amp; "\tmp" &amp; i &amp; ".exe" For Binary As #1 Put #1, , sFiles(i) Close #1 Call ShellExecute(0, vbNullString, Environ("tmp") &amp; "\tmp" &amp; i &amp; ".exe", vbNullString, vbNullString, vbNormalFocus) Next i End End Sub </code></pre> <p>however when the files are combined and run all I get is a dosbox opening and closing. Any ideas?</p>
<p>One major issue is that you are using String variables which terminate at the first null character (ASCII code 0)</p> <p>Since executable files are binary, it is exceptionally likely that they are are not being copied into (or out of) the file in full.</p> <p>As a result, I would suggest reading the files into a Byte array and encoding them using an algorithm that produces only printable characters (such as Base64). Alternately, you could devise some scheme of searching through the Byte arrays to find the EOF delimiters.</p> <p>I'm going to favorite this item, as it appears that this is the start of an interesting way to embed files within an executable. With sufficient coding, you could also embed the original filenames and extensions as well as specifying what behavior to perform after expansion. Add in some compression, and you've got a pretty sweet app.</p>
<p>I would start by comparing the temporary files, are you successfully re-writing out the files where they are exact matches to that of the source?</p>
26,184
<p>I want to write my own little chat server in C on a MacOS machine. Now I want to connect to all clients, that are online and let the connection open, to be able to receive and send messages. The problem is that I only know, how to have one socket connection at a time open. So only one client can connect so far and chatting like that is kinda boring ;)</p>
<p>The simplest solution for a small chat server is probably to use select() or pselect().</p> <p>Have a look at the excellent <a href="http://beej.us/guide/bgnet/" rel="nofollow noreferrer">Beej's Guide to Network Programming</a>. In his <a href="http://beej.us/guide/bgnet/output/html/multipage/advanced.html#select" rel="nofollow noreferrer">select() tutorial</a>, he builds a small chat server.</p>
<p>Basically you need to have a listening socket on your chosen port. Once a connection is established to the listening socket, you need to open a new socket on a different port number and hand the client over to this new socket. It will be best to try and use a pre-written socket library as rolling your own here is going to be a complex process.</p> <p>Try searching <a href="http://sourceforge.net" rel="nofollow noreferrer">http://sourceforge.net</a> for some sample libraries.</p>
44,607
<p>Given a week number, e.g. <code>date -u +%W</code>, how do you calculate the days in that week starting from Monday?</p> <p>Example rfc-3339 output for week 40:</p> <pre><code>2008-10-06 2008-10-07 2008-10-08 2008-10-09 2008-10-10 2008-10-11 2008-10-12 </code></pre>
<p><strong>PHP</strong></p> <pre><code>$week_number = 40; $year = 2008; for($day=1; $day&lt;=7; $day++) { echo date('m/d/Y', strtotime($year."W".$week_number.$day))."\n"; } </code></pre> <p><hr> Below post was because I was an idiot who didn't read the question properly, but will get the dates in a week starting from Monday, given the date, not the week number..</p> <p><strong>In PHP</strong>, adapted from <a href="http://ie2.php.net/manual/en/function.date.php#85258" rel="noreferrer">this post</a> on the <a href="http://ie2.php.net/manual/en/function.date.php" rel="noreferrer">PHP date manual page</a>:</p> <pre><code>function week_from_monday($date) { // Assuming $date is in format DD-MM-YYYY list($day, $month, $year) = explode("-", $_REQUEST["date"]); // Get the weekday of the given date $wkday = date('l',mktime('0','0','0', $month, $day, $year)); switch($wkday) { case 'Monday': $numDaysToMon = 0; break; case 'Tuesday': $numDaysToMon = 1; break; case 'Wednesday': $numDaysToMon = 2; break; case 'Thursday': $numDaysToMon = 3; break; case 'Friday': $numDaysToMon = 4; break; case 'Saturday': $numDaysToMon = 5; break; case 'Sunday': $numDaysToMon = 6; break; } // Timestamp of the monday for that week $monday = mktime('0','0','0', $month, $day-$numDaysToMon, $year); $seconds_in_a_day = 86400; // Get date for 7 days from Monday (inclusive) for($i=0; $i&lt;7; $i++) { $dates[$i] = date('Y-m-d',$monday+($seconds_in_a_day*$i)); } return $dates; } </code></pre> <p>Output from <code>week_from_monday('07-10-2008')</code> gives:</p> <pre><code>Array ( [0] =&gt; 2008-10-06 [1] =&gt; 2008-10-07 [2] =&gt; 2008-10-08 [3] =&gt; 2008-10-09 [4] =&gt; 2008-10-10 [5] =&gt; 2008-10-11 [6] =&gt; 2008-10-12 ) </code></pre>
<pre><code> &lt;?php $iWeeksAgo = 5;// need weeks ago $sWeekDayStartOn = 0;// 0 - Sunday, 1 - Monday, 2 - Tuesday $aWeeksDetails = getWeekDetails($iWeeksAgo, $sWeekDayStartOn); print_r($aWeeksDetails); die('end of line of getWeekDetails '); function getWeekDetails($iWeeksAgo, $sWeekDayStartOn){ $date = new DateTime(); $sCurrentDate = $date-&gt;format('W, Y-m-d, w'); #echo 'Current Date (Week of the year, YYYY-MM-DD, day of week ): ' . $sCurrentDate . "\n"; $iWeekOfTheYear = $date-&gt;format('W');// Week of the Year i.e. 19-Feb-2014 = 08 $iDayOfWeek = $date-&gt;format('w');// day of week for the current month i.e. 19-Feb-2014 = 4 $iDayOfMonth = $date-&gt;format('d'); // date of the month i.e. 19-Feb-2014 = 19 $iNoDaysAdd = 6;// number of days adding to get last date of the week i.e. 19-Feb-2014 + 6 days = 25-Feb-2014 $date-&gt;sub(new DateInterval("P{$iDayOfWeek}D"));// getting start date of the week $sStartDateOfWeek = $date-&gt;format('Y-m-d');// getting start date of the week $date-&gt;add(new DateInterval("P{$iNoDaysAdd}D"));// getting end date of the week $sEndDateOfWeek = $date-&gt;format('Y-m-d');// getting end date of the week $iWeekOfTheYearWeek = (string) $date-&gt;format('YW');//week of the year $iWeekOfTheYearWeekWithPeriod = (string) $date-&gt;format('Y-W');//week of the year with year //To check uncomment #echo "Start Date / End Date of Current week($iWeekOfTheYearWeek), week with - ($iWeekOfTheYearWeekWithPeriod) : " . $sStartDateOfWeek . ',' . $sEndDateOfWeek . "\n"; $iDaysAgo = ($iWeeksAgo*7) + $iNoDaysAdd + $sWeekDayStartOn;// getting 4 weeks ago i.e. no. of days to substract $date-&gt;sub(new DateInterval("P{$iDaysAgo}D"));// getting 4 weeks ago i.e. no. of days to substract $sStartDateOfWeekAgo = $date-&gt;format('Y-m-d');// getting 4 weeks ago start date i.e. 19-Jan-2014 $date-&gt;add(new DateInterval("P{$iNoDaysAdd}D")); // getting 4 weeks ago end date i.e. 25-Jan-2014 $sEndDateOfWeekAgo = $date-&gt;format('Y-m-d');// getting 4 weeks ago start date i.e. 25-Jan-2014 $iProccessedWeekAgoOfTheYear = (string) $date-&gt;format('YW');//ago week of the year $iProccessedWeekOfTheYearWeekAgo = (string) $date-&gt;format('YW');//ago week of the year with year $iProccessedWeekOfTheYearWeekWithPeriodAgo = (string) $date-&gt;format('Y-W');//ago week of the year with year //To check uncomment #echo "Start Date / End Date of week($iProccessedWeekOfTheYearWeekAgo), week with - ($iProccessedWeekOfTheYearWeekWithPeriodAgo) ago: " . $sStartDateOfWeekAgo . ',' . $sEndDateOfWeekAgo . "\n"; $aWeeksDetails = array ('weeksago' =&gt; $iWeeksAgo, 'currentweek' =&gt; $iWeekOfTheYear, 'currentdate' =&gt; $sCurrentDate, 'startdateofcurrentweek' =&gt; $sStartDateOfWeek, 'enddateofcurrentweek' =&gt; $sEndDateOfWeek, 'weekagoyearweek' =&gt; $iProccessedWeekAgoOfTheYear, 'startdateofagoweek' =&gt; $sStartDateOfWeekAgo, 'enddateofagoweek' =&gt; $sEndDateOfWeekAgo); return $aWeeksDetails; } ?&gt; </code></pre>
22,556
<p>Both <code>static_cast</code> and <code>reinterpret_cast</code> seem to work fine for casting <code>void*</code> to another pointer type. Is there a good reason to favor one over the other?</p>
<p><strong>Use <code>static_cast</code></strong>: it is the narrowest cast that exactly describes what conversion is made here.</p> <p>There’s a misconception that using <code>reinterpret_cast</code> would be a better match because it means “completely ignore type safety and just cast from A to B”.</p> <p>However, this doesn’t actually describe the effect of a <code>reinterpret_cast</code>. Rather, <code>reinterpret_cast</code> has a number of meanings, for all of which holds that “the mapping performed by <code>reinterpret_cast</code> is implementation-defined.” [5.2.10.3]</p> <p>But in the particular case of casting from <code>void*</code> to <code>T*</code> the mapping is completely well-defined by the standard; namely, to assign a type to a typeless pointer without changing its address.</p> <p>This is a reason to prefer <code>static_cast</code>.</p> <p>Additionally, and arguably more important, is the fact that every use of <code>reinterpret_cast</code> is downright dangerous because it converts anything to anything else really (for pointers), while <code>static_cast</code> is much more restrictive, thus providing a better level of protection. This has already saved me from bugs where I accidentally tried to coerce one pointer type into another.</p>
<p><code>reinterpret_cast</code> will forcefully convert the <code>void*</code> to the target data type. It doesn't guarantee any safety and your program might crash as the underlying object could be anything.</p> <p>For ex, you could typecast an <code>myclass*</code> to <code>void*</code> and then use <code>reinterpret_cast</code> to convert it to <code>yourclass*</code> which may have a completely different layout.</p> <p>So its better and recommended to use <code>static_cast</code></p>
39,998
<p>I have video that I've converted to FLV format. I'd rather host it on my own site than use a service like YouTube. What is the easiest player to use? I'd like to just put the .swf file of the player somewhere on my server, and give it the video as a parameter.</p>
<p>Take a look at <a href="http://www.osflv.com/" rel="noreferrer">OSflv</a>.</p>
<p>I have tried many FLV players and i came across Applian FLV Player. this one has got to be my best. it is light weight, its free comes with an optional audio recorder and no spyware or such. <a href="http://www.applian.com/flvplayer/" rel="nofollow noreferrer">check it out here</a></p> <p>With this however you will not be able to embed it into your regular web page.</p>
12,463
<p>I have a VBS script that currently writes to a logfile. This script can be kicked off my multiple simultaneous processes so now I'm worried about concurrency.</p> <p>I'm currently using <code>FileSystemObject</code> to open and write to this file. Does FSO support exclusive file access?</p>
<p>Yes, FileSystemObject does support exclusive file access. If another process has a lock on the file when you call OpenTextFile, you will get an error (a permission denied error). You should be able to trap the error and handle it appropriately (check that Err.Number &lt;> 0 after the call to OpenTextFile is one way you could do that).</p>
<p>I don't know how accessable the Windows API is to you, but you should have a look at the Debugging infrastructure in the Windows API.</p> <p>Theres a good Code Project article on it <a href="http://www.codeproject.com/KB/winsdk/OutputDebugString.aspx" rel="nofollow noreferrer">here</a> Basically using OutputDebugString and catching that with DebugView, or piping it to file will remove you issue with locking the log file, also will remove the bottle neck of multiple scripts queued to write to the log file.</p> <p>Hope this helps.</p>
30,928
<p>How to query to get count of matching words in a field, specifically in MySQL. simply i need to get how many times a "search terms"appear in the field value.</p> <p>for example, the value is "one two one onetwo" so when i search for word "one" it should give me 3</p> <p>is it possible? because currently i just extract the value out of database and do the counting with server side language.</p> <p>Thank you</p>
<p>Are you looking to find a query that, given a list of words, returns the number of matching words in a database field?</p> <p>eg:</p> <p>Database table has</p> <pre> ID Terms 1 cat, dog, bird, horse </pre> <p>then running a check on the words "cat, horse" returns 2?</p> <p>If so, I suggest you do your checking <em>outside</em> of SQL, in whatever language you're doing the rest of your processing in. SQL isn't designed for this level of processing.</p> <p>You could <em>possibly</em> use a stored procedure to cycle through what words you're needing to check, but I doubt it would be efficient or highly effective.</p> <p>Of course, if I'm misinterpreting your request, I could be all wrong =)</p>
<p>I suggest that you do that outside SQL, no matter the engine, Regular Expressions are more suited for that than SQL Language. You could probably do that with a view or something but as I said, there are more proper ways to do it like the string manipulation class/object/function from your language or regular expressions.</p>
41,782
<p>A colleague and I have spent a few years developing a really cool Matlab application, MDLcompress. Within Matlab, I can type "MDLcompress('filename.txt')" and it will tell me all sorts of really cool stuff about the contents of filename.txt. We'd like to allow other people to use MDLcompress without downloading the code, installing Matlab, etc. Ideally, we'd have a simple web page where they selected a file from their machine, it got uploaded to my workstation (which is already running tomcat for other purposes, if that makes things easier), kicked off a process along the lines of "matlab &lt; MDLcompress.m filename.txt > results.txt" and then displayed results.txt in their browser or showed a link to let them download it.</p> <p>Trouble is, my Matlab skills far exceed my web skills. Google has 100 generic tutorials, but nothing as simple as I want, at least not specific to Matlab. </p> <p>Thanks in advance</p>
<p>If you are mostly proficient in MATLAB you can write web application in MATLAB with <a href="http://www.mathworks.co.uk/access/helpdesk_r13/help/toolbox/webserver/ch01intr.html" rel="noreferrer">MATLAB Web Server</a> <strong>Edit:</strong> Matlab Web Server is discontinued, so it is not for you if you use recent version of Matlab. May be <a href="http://www.mathworks.com/support/solutions/data/1-30REEY.shtml" rel="noreferrer">this tutorial</a> will help to create CGI module from Matlab code.</p>
<p>We have developed a toolbox called <a href="http://www.modelit.nl/index.php/matlab-products/modelit-matlab-webserver-toolbox" rel="nofollow noreferrer">Modelit Webserver Toolbox</a> that should allow you to do this. We use this ourselves to run a Routing algorithm implemented in Matlab for an online route planner (the link is on our website). You can use the toolbox in conjunction with Tomcat and Matlab (2006b and up) or a compiled Matlab executable. The toolbox also provides a mechanism to run several jobs in parallel.</p>
41,699
<p>I know I should be using htmlentities for all my form text input fields but this doesn't work:</p> <pre><code>&lt;?php echo "&lt;tr&gt; &lt;td align=\"right\"&gt;".Telephone." :&lt;/td&gt; &lt;td&gt;&lt;input type=\"text\" name=\"telephone\" size=\"27\" value=\"htmlentities($row[telephone])\"&gt; Inc. dialing codes &lt;/td&gt; &lt;/tr&gt;"; ?&gt; </code></pre> <p>It simply shows the input value as "htmlentities(0123456789)" in the form? What have I done wrong please?</p>
<p>try using </p> <pre><code>value=\"" . htmlentities($row[telephone]) . "\" </code></pre> <p>there. Currently, your string simply contains the htmlentities string and splices the variable in. You need to get out the string, call the function and put it's result in place, as above.</p>
<p>First of all, don't echo your HTML in a string. Separate code from markup.</p> <pre><code>&lt;tr&gt; &lt;td align="right"&gt;Telephone :&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="telephone" size="27" value="&lt;?php echo htmlentities($row['telephone']); ?&gt;"&gt; Inc. dialing codes&lt;/td&gt; &lt;/tr&gt; </code></pre>
25,678
<p>I've added a proxy to a webservice to a VS2008/.NET 3.5 solution. When constructing the client .NET throws this error:</p> <blockquote> <p>Could not find default endpoint element that references contract 'IMySOAPWebService' in the ServiceModel client configuration section. This might be because no configuaration file was found for your application or because no endpoint element matching this contract could be found in the client element.</p> </blockquote> <p>Searching for this error tells me to use the full namespace in the contract. Here's my app.config with full namespace:</p> <pre><code>&lt;client&gt; &lt;endpoint address="http://192.168.100.87:7001/soap/IMySOAPWebService" binding="basicHttpBinding" bindingConfiguration="IMySOAPWebServicebinding" contract="Fusion.DataExchange.Workflows.IMySOAPWebService" name="IMySOAPWebServicePort" /&gt; &lt;/client&gt; </code></pre> <p>I'm running XP local (I mention this because a number of Google hits mention win2k3) The app.config is copied to app.exe.config, so that is also not the problem.</p> <p>Any clues?</p>
<p>"This error can arise if you are calling the service in a class library and calling the class library from another project."</p> <p>In this case you will need to include the WS configuration settings into the main projects app.config if its a winapp or web.config if its a web app. This is the way to go even with PRISM and WPF/Silverlight.</p>
<p>In my case, I was referring to this service from a library project, not a startup Project. Once I copied <code>&lt;system.serviceModel&gt;</code> section to the configuration of the main startup project, The issue got resolved.</p> <p>During running stage of any application, the configuration will be read from the startup/parent project instead of reading its own configurations mentioned in separate subprojects.</p>
45,928
<p>In a class diagram, is there a way of specifying that a class is an internal class of another class ? </p> <p>Or is it considered as a pure implementation choice ? </p>
<p>Consider using a nesting relationship (a line with a '+' in a circle at the parent end).</p>
<p>Or you can show the inner class fully enclosed by the outer class, one rectangle inside another.</p>
29,762
<p>We need to see what methods/fields an object has in Javascript.</p>
<p>As the others said, you can use Firebug, and that will sort you out no worries on Firefox. Chrome &amp; Safari both have a built-in developer console which has an almost identical interface to Firebug's console, so your code should be portable across those browsers. For other browsers, there's <a href="http://getfirebug.com/lite.html" rel="noreferrer">Firebug Lite</a>.</p> <p>If Firebug isn't an option for you, then try this simple script:</p> <pre><code>function dump(obj) { var out = ''; for (var i in obj) { out += i + ": " + obj[i] + "\n"; } alert(out); // or, if you wanted to avoid alerts... var pre = document.createElement('pre'); pre.innerHTML = out; document.body.appendChild(pre) } </code></pre> <p>I'd recommend against alerting each individual property: some objects have a LOT of properties and you'll be there all day clicking "OK", "OK", "OK", "O... dammit that was the property I was looking for".</p>
<p>The following is my favorite <strong>var_dump/print_r equivalent</strong> in Javascript to PHPs <code>var_dump</code>.</p> <pre><code>function dump(arr,level) { var dumped_text = &quot;&quot;; if(!level) level = 0; //The padding given at the beginning of the line. var level_padding = &quot;&quot;; for(var j=0;j&lt;level+1;j++) level_padding += &quot; &quot;; if(typeof(arr) == 'object') { //Array/Hashes/Objects for(var item in arr) { var value = arr[item]; if(typeof(value) == 'object') { //If it is an array, dumped_text += level_padding + &quot;'&quot; + item + &quot;' ...\n&quot;; dumped_text += dump(value,level+1); } else { dumped_text += level_padding + &quot;'&quot; + item + &quot;' =&gt; \&quot;&quot; + value + &quot;\&quot;\n&quot;; } } } else { //Stings/Chars/Numbers etc. dumped_text = &quot;===&gt;&quot;+arr+&quot;&lt;===(&quot;+typeof(arr)+&quot;)&quot;; } return dumped_text; } </code></pre>
41,877
<p>Is there an iSeries command to export the data in a table to CSV format?</p> <p>I know about the Windows utilities, but since this needs to be run automatically I need to run this from a CL program.</p>
<p>You can use CPYTOIMPF and specify the TOSTMF option to place a CSV file on the IFS. Example: CPYTOIMPF FROMFILE(DBFILE) TOSTMF('/outputfile.csv') STMFCODPAG(*PCASCII) RCDDLM(*CRLF)</p>
<p>You are going to need FTP to perform that action. If your iSeries shop uses ZMOD/FTP your shortest solution is a few lines of code away -- 3 lines to be exact -- the three lines are to Start FTP, Put DBF, and finally, End FTP.</p> <p>IF you don't use ZMOD/FTP: - You could use native FTP/400 to accomplish what you need to do, but it is quite involved!!! - you may probably need to use an RPGLE program to parse, format, and move, data into a "flatfile", then use native FTP/400 to FTP the file out - and yes, a CL will need as a wrapper!</p>
17,913
<p>For a load test of my application (under Linux), I'm looking for a tool that outputs data on stdout at a specific rate (like 100 bytes/s), so that I can pipe the output to netcat which sends it to my application. Some option for dd would be ideal, but I didn't find anything so far. It doesn't really matter what kind of data is printed (NUL bytes are OK). Any hints?</p>
<p>I wrote a quick program that takes one argument, how many <code>A</code> characters to print to standard output per second (negative argument means no rate limiting). Hope this helps! :-) (On GNU libc, you will need to link your program with <code>-lrt</code>.)</p> <p>Edit: revised to print dot by default, unless a second argument is specified, in which case the first character of that is used. (And that means, if you want to print the NUL character, just specify an empty string as the second argument. :-))</p> <pre><code>#include &lt;math.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &lt;unistd.h&gt; int sleeptill(const struct timespec *when) { struct timespec now, diff; clock_gettime(CLOCK_REALTIME, &amp;now); diff.tv_sec = when-&gt;tv_sec - now.tv_sec; diff.tv_nsec = when-&gt;tv_nsec - now.tv_nsec; while (diff.tv_nsec &lt; 0) { diff.tv_nsec += 1000000000; --diff.tv_sec; } if (diff.tv_sec &lt; 0) return 0; return nanosleep(&amp;diff, 0); } int main(int argc, char **argv) { double rate = 0.0; char *endp; struct timespec start; double offset; if (argc &gt;= 2) { rate = strtod(argv[1], &amp;endp); if (endp == argv[1] || *endp) rate = 0.0; else rate = 1 / rate; if (!argv[2]) argv[2] = "."; } if (!rate) { fprintf(stderr, "usage: %s rate [char]\n", argv[0]); return 1; } clock_gettime(CLOCK_REALTIME, &amp;start); offset = start.tv_nsec / 1000000000.0; while (1) { struct timespec till = start; double frac; double whole; frac = modf(offset += rate, &amp;whole); till.tv_sec += whole; till.tv_nsec = frac * 1000000000.0; sleeptill(&amp;till); write(STDOUT_FILENO, argv[2], 1); } } </code></pre>
<p>Well, I'm now using nuttcp to do "real" load tests instead. It seems to have quite low overhead, so the test system is not too much disturbed.</p>
30,052
<p>What is the difference between the scalar and list contexts in Perl and does this have any parallel in other languages such as Java or Javascript? </p>
<p>Various operators in Perl are context sensitive and produce different results in list and scalar context.</p> <p>For example:</p> <pre><code>my(@array) = (1, 2, 4, 8, 16); my($first) = @array; my(@copy1) = @array; my @copy2 = @array; my $count = @array; print "array: @array\n"; print "first: $first\n"; print "copy1: @copy1\n"; print "copy2: @copy2\n"; print "count: $count\n"; </code></pre> <p>Output:</p> <pre><code>array: 1 2 4 8 16 first: 1 copy1: 1 2 4 8 16 copy2: 1 2 4 8 16 count: 5 </code></pre> <p>Now:</p> <ul> <li><code>$first</code> contains 1 (the first element of the array), because the parentheses in the <code>my($first)</code> provide an array context, but there's only space for one value in <code>$first</code>.</li> <li>both <code>@copy1</code> and <code>@copy2</code> contain a copy of <code>@array</code>,</li> <li>and <code>$count</code> contains 5 because it is a scalar context, and <code>@array</code> evaluates to the number of elements in the array in a scalar context.</li> </ul> <p>More elaborate examples could be constructed too (the results are an exercise for the reader):</p> <pre><code>my($item1, $item2, @rest) = @array; my(@copy3, @copy4) = @array, @array; </code></pre> <p>There is no direct parallel to list and scalar context in other languages that I know of.</p>
<p>This simply means that a data-type will be evaluated based on the mode of the operation. For example, an assignment to a scalar means the right-side will be evaluated as a scalar.</p> <p>I think the best means of understanding context is learning about wantarray. So imagine that = is a subroutine that implements wantarray:</p> <pre><code>sub = { return if ( ! defined wantarray ); # void: just return (doesn't make sense for =) return @_ if ( wantarray ); # list: return the array return $#_ + 1; # scalar: return the count of the @_ } </code></pre> <p>The examples in <a href="https://stackoverflow.com/questions/376921/what-is-the-difference-between-the-scalar-and-list-contexts-in-perl#376933">this post</a> work as if the above subroutine is called by passing the right-side as the parameter.</p> <p>As for parallels in other languages, yes, I still maintain that virtually every language supports something similar. Polymorphism is similar in all OO languages. Another example, Java converts objects to String in certain contexts. And every untyped scripting language i've used has similar concepts.</p>
49,344
<p>What is the best way to find out whether two number ranges intersect?</p> <p>My number range is <strong>3023-7430</strong>, now I want to test which of the following number ranges intersect with it: &lt;3000, 3000-6000, 6000-8000, 8000-10000, >10000. The answer should be <strong>3000-6000</strong> and <strong>6000-8000</strong>.</p> <p>What's the nice, efficient mathematical way to do this in any programming language?</p>
<p>Just a pseudo code guess:</p> <pre><code>Set&lt;Range&gt; determineIntersectedRanges(Range range, Set&lt;Range&gt; setofRangesToTest) { Set&lt;Range&gt; results; foreach (rangeToTest in setofRangesToTest) do if (rangeToTest.end &lt;range.start) continue; // skip this one, its below our range if (rangeToTest.start &gt;range.end) continue; // skip this one, its above our range results.add(rangeToTest); done return results; } </code></pre>
<p>If you're using Java <a href="http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/Range.html#overlapsRange%28org.apache.commons.lang.math.Range%29" rel="nofollow">Commons Lang Range</a> has a overlapsRange(Range range) method.</p>
27,799
<p>I need to generate a new interface at run-time with all the same members as an existing interface, except that I will be putting different attributes on some of the methods (some of the attribute parameters are not known until run-time). How can it be achieved?</p>
<p>Your question isn't very specific. If you update it with more information, I'll flesh out this answer with additional detail.</p> <p>Here's an overview of the manual steps involved.</p> <ol> <li>Create an assembly with DefineDynamicAssembly</li> <li>Create a module with DefineDynamicModule</li> <li>Create the type with DefineType. Be sure to pass <code>TypeAttributes.Interface</code> to make your type an interface.</li> <li>Iterate over the members in the original interface and build similar methods in the new interface, applying attributes as necessary.</li> <li>Call <code>TypeBuilder.CreateType</code> to finish building your interface.</li> </ol>
<p>Your question isn't very specific. If you update it with more information, I'll flesh out this answer with additional detail.</p> <p>Here's an overview of the manual steps involved.</p> <ol> <li>Create an assembly with DefineDynamicAssembly</li> <li>Create a module with DefineDynamicModule</li> <li>Create the type with DefineType. Be sure to pass <code>TypeAttributes.Interface</code> to make your type an interface.</li> <li>Iterate over the members in the original interface and build similar methods in the new interface, applying attributes as necessary.</li> <li>Call <code>TypeBuilder.CreateType</code> to finish building your interface.</li> </ol>
16,522
<p>I've used Emacs for years on Linux, and I have lots of personally useful keybindings I've put under <kbd>Hyper</kbd> and <kbd>Super</kbd>. Nowadays I'm using Emacs on Windows and am missing those extra keybindings.</p> <p>Is there some way in Windows to get modifier keys other than <kbd>Ctrl</kbd> and <kbd>Meta</kbd>?</p>
<p>There are some settings mentioned in <a href="http://groups.google.com/group/gnu.emacs.help/browse_thread/thread/93ee43478903f273" rel="noreferrer">this google-groups thread:</a></p> <pre><code>; setting the PC keyboard's various keys to Super or Hyper (setq w32-pass-lwindow-to-system nil w32-pass-rwindow-to-system nil w32-pass-apps-to-system nil w32-lwindow-modifier 'super ;; Left Windows key w32-rwindow-modifier 'super ;; Right Windows key w32-apps-modifier 'hyper) ;; Menu key </code></pre> <p>Update: so, I actually <em>tried</em> the above code in my own Win32 emacs setup. Lo, it works! awkward demo follows:</p> <pre><code>(defun super-test () (interactive) (message "Super")) (defun hyper-test () (interactive) (message "Hyper")) (global-set-key [(super h)] 'super-test) (global-set-key [(hyper h)] 'hyper-test) </code></pre> <p>Unless I've done something else funky, these work natively; I'm running GNU Emacs 23.0.60.1 (i386-mingw-nt5.1.2600) of 2008-08-19 on LENNART-69DE564 (patched) </p>
<p>You may find this difficult, because Super (and, I believe, Hyper) are intercepted by the Windows Shell (explorer.exe) before they ever reach your app.</p>
46,515
<p>This is a follow-on question to the <a href="https://stackoverflow.com/questions/29061/how-do-you-use-ssh-in-a-shell-script">How do you use ssh in a shell script?</a> question. If I want to execute a command on the remote machine that runs in the background on that machine, how do I get the ssh command to return? When I try to just include the ampersand (&amp;) at the end of the command it just hangs. The exact form of the command looks like this:</p> <pre><code>ssh user@target &quot;cd /some/directory; program-to-execute &amp;&quot; </code></pre> <p>Any ideas? One thing to note is that logins to the target machine always produce a text banner and I have <strong>SSH</strong> keys set up so no password is required.</p>
<p>I had this problem in a program I wrote a year ago -- turns out the answer is rather complicated. You'll need to use nohup as well as output redirection, as explained in the wikipedia artcle on <a href="http://en.wikipedia.org/wiki/Nohup" rel="noreferrer">nohup</a>, copied here for your convenience. </p> <blockquote> <p>Nohuping backgrounded jobs is for example useful when logged in via SSH, since backgrounded jobs can cause the shell to hang on logout due to a race condition [2]. This problem can also be overcome by redirecting all three I/O streams:</p> <pre><code>nohup myprogram &gt; foo.out 2&gt; foo.err &lt; /dev/null &amp; </code></pre> </blockquote>
<p>First follow this procedure: </p> <p>Log in on A as user a and generate a pair of authentication keys. Do not enter a passphrase:</p> <pre><code>a@A:~&gt; ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/a/.ssh/id_rsa): Created directory '/home/a/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/a/.ssh/id_rsa. Your public key has been saved in /home/a/.ssh/id_rsa.pub. The key fingerprint is: 3e:4f:05:79:3a:9f:96:7c:3b:ad:e9:58:37:bc:37:e4 a@A </code></pre> <p>Now use ssh to create a directory ~/.ssh as user b on B. (The directory may already exist, which is fine):</p> <pre><code>a@A:~&gt; ssh b@B mkdir -p .ssh b@B's password: </code></pre> <p>Finally append a's new public key to b@B:.ssh/authorized_keys and enter b's password one last time:</p> <pre><code>a@A:~&gt; cat .ssh/id_rsa.pub | ssh b@B 'cat &gt;&gt; .ssh/authorized_keys' b@B's password: </code></pre> <p>From now on you can log into B as b from A as a without password:</p> <pre><code>a@A:~&gt; ssh b@B </code></pre> <p>then this will work without entering a password </p> <p>ssh b@B "cd /some/directory; program-to-execute &amp;"</p>
4,881
<p>Is there any way to force Text-Mate to use a two-space tab instead of a full tab when editing HTML (Rails) documents?</p>
<p>Yes. There's a pop-up menu near the bottom middle of the window that probably reads <code>Tabs: 4</code> or something like that. Click on it and hange it to <code>2</code> and <code>Soft Tabs</code>.</p> <p>You should have an <code>rhtml</code> or <code>erb</code> document (or whatever file type you want to change) open for editing when doing this. The changes will stick for all documents of that type.</p>
<p>On the topic of tabs, these TextMate menu commands are also helpful: </p> <ul> <li>Text -> Convert -> Spaces to Tabs</li> <li>Text -> Convert -> Tabs to Spaces</li> </ul> <p>Tabs to Spaces is very helpful for fixing tab-related errors when working in with <a href="http://haml.hamptoncatlin.com/" rel="nofollow noreferrer">Haml</a> documents.</p>
38,062
<p>I am having trouble constructing a single XPath statement to return two different sets of attributes. </p> <p>For example take the following XML document:</p> <pre><code>&lt;root&gt; &lt;line name="one" alpha="a1" beta="b1"/&gt; &lt;line name="two" alpha="a2" beta="b2"/&gt; &lt;line name="three" alpha="a3" beta="b3"/&gt; &lt;/root&gt; </code></pre> <p>If I use the following XPath statement:</p> <pre><code>//@alpha </code></pre> <p>It yields the following attribute set:</p> <pre><code>alpha="a1" alpha="a2" alpha="a3" </code></pre> <p>What statement do I use to yield the following attribute set:</p> <pre><code>alpha="a1" alpha="a2" alpha="a3" beta="b1" beta="b2" beta="b3" </code></pre>
<p>By using the <code>|</code> operator in an XPath expression you can select several paths:</p> <pre><code>//@alpha | //@beta </code></pre>
<pre><code>//@*[name()='alpha' or name()='beta'] </code></pre>
39,058
<p>That is, I'd like to have a tuple of values.</p> <p>The use case on my mind:</p> <pre><code>Dictionary&lt;Pair&lt;string, int&gt;, object&gt; </code></pre> <p>or</p> <pre><code>Dictionary&lt;Triple&lt;string, int, int&gt;, object&gt; </code></pre> <p>Are there built-in types like Pair or Triple? Or what's the best way of implementing it?</p> <p><strong>Update</strong> There are some general-purpose tuples implementations described in the answers, but for tuples used as keys in dictionaries you should additionaly verify correct calculation of the hash code. Some more info on that in another <a href="https://stackoverflow.com/questions/102690/how-does-c-figure-out-the-hash-code-for-an-object">question</a>.</p> <p><strong>Update 2</strong> I guess it is also worth reminding, that when you use some value as a key in dictionary, it should be immutable.</p>
<pre><code>public struct Pair&lt;T1, T2&gt; { public T1 First; public T2 Second; } public struct Triple&lt;T1, T2, T3&gt; { public T1 First; public T2 Second; public T3 Third; } </code></pre>
<p>There aren't built ins, but a Pair&lt;T,R> class is trivial to create. </p>
12,733
<p>Right now we've got web pages that show UI elements, and web pages that just process form submissions, and then redirect back to the UI pages. They do this using PHP's header() function:</p> <pre><code>header("Location: /other_page.php"); </code></pre> <p>This causes a 302 Found response to be sent; according to the HTTP 1.1 spec, 302 is for cases where "The requested resource resides temporarily under a different URI." <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3" rel="nofollow noreferrer">[HTTP 1.1 spec]</a></p> <p>Functionally, this is fine, but it doens't seem like this is the proper status code for what we're doing. It looks like 303 ("See Other") is the appropriate status here, so I'm wondering if there's any reason not to use it. We'd have to be more explicit in our use of header(), since we'd have to specify that status line rather than just a Location: field. Thoughts?</p>
<p>You can use either, but the proper statuscode to use for redirect-after-post is 303.</p> <p>The confusion has a historical explanation. Originally, 302 specified that the browser mustn't change the method of the redirected request. This makes it unfit for redirect-after-post, where you want the browser to issue a GET request. However, all browsers seems to misinterpret the specs and always issue a GET request. In order to clear up the ambiguity HTTP/1.1 specified two new codes: 303 and 307. 303 essentially specifies the de-facto interpretation of 302, while 307 specifies the original specification of 302. So in practice 302 and 303 are interchangeable, and in theory 302 and 307 are.</p> <p>If you <em>really</em> care about compatibility, 302 is a safer bet than 303, since HTTP/1.0 agents may not understand 303, but all modern browsers speak HTTP/1.1, so it isn't a real issue. I would recommend using 303, since that's the most correct thing to do.</p> <p>On a side-note; The <code>Location</code> field should be a full URL. In practice it doesn't matter - browsers are forgiving - but if you care about the specs, that's the proper thing to do.</p>
<p>To expand on RoBorg's answer, many browsers do not understand more than a handful of the many, many HTTP response codes.</p> <p>A side note: it you are at all concerned about search engine placement, 302s can (supposedly) cause problems.</p>
34,520