instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'm trying to determine if there's a way in Visual Basic 2008 (Express edition if that matters) to do inline collection initialization, a la JavaScript or Python:</p> <pre><code>Dim oMapping As Dictionary(Of Integer, String) = {{1,"First"}, {2, "Second"}} </code></pre> <p>I know Visual Basic 2008 supports array initialization like this, but I can't seem to get it to work for collections... Do I have the syntax wrong, or is it just not implemented?</p>
<p><a href="http://en.wikipedia.org/wiki/Visual_Basic_.NET#Visual_Basic_2008_.28VB_9.0.29" rel="nofollow noreferrer">Visual Basic 9.0</a> doesn't support this yet. However, <a href="http://en.wikipedia.org/wiki/Visual_Basic_.NET#Visual_Basic_2010_.28VB_10.0.29" rel="nofollow noreferrer">Visual Basic 10.0</a> <a href="http://msdn.microsoft.com/en-us/library/dd293617.aspx" rel="nofollow noreferrer">will</a>.</p>
<p>Here are <a href="https://msdn.microsoft.com/en-us/library/dd293617.aspx" rel="noreferrer">VB collection initializers</a> using the <strong>From</strong> keyword. (Starting with Visual Studio 2010)</p> <p><strong>List:</strong></p> <pre><code>Dim list As New List(Of String) From {"First", "Second"} </code></pre> <p><strong>Dictionary:</strong></p> <pre><code>Dim oMapping As New Dictionary(Of Integer, String) From {{1, "First"}, {2, "Second"}} </code></pre>
11,137
<p>On Windows I have a problem I never encountered on Unix. That is how to get a thread to sleep for less than one millisecond. On Unix you typically have a number of choices (sleep, usleep and nanosleep) to fit your needs. On Windows, however, there is only <em>Sleep</em> with millisecond granularity. </p> <p>On Unix, I can use the use the <code>select</code> system call to create a microsecond sleep which is pretty straightforward:</p> <pre><code>int usleep(long usec) { struct timeval tv; tv.tv_sec = usec/1000000L; tv.tv_usec = usec%1000000L; return select(0, 0, 0, 0, &amp;tv); } </code></pre> <p>How can I achieve the same on Windows?</p>
<p>This indicates a mis-understanding of sleep functions. The parameter you pass is a <em>minimum</em> time for sleeping. There's no guarantee that the thread will wake up after exactly the time specified. In fact, threads don't "wake up" at all, but are rather chosen for execution by the OS scheduler. The scheduler might choose to wait much longer than the requested sleep duration to activate a thread, especially if another thread is still active at that moment.</p>
<p>On Windows the use of <code>select</code> forces you to include the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms740673(v=vs.85).aspx" rel="nofollow noreferrer">Winsock</a> library which has to be initialized like this in your application:</p> <pre><code>WORD wVersionRequested = MAKEWORD(1,0); WSADATA wsaData; WSAStartup(wVersionRequested, &amp;wsaData); </code></pre> <p>And then the select won't allow you to be called without any socket so you have to do a little more to create a microsleep method:</p> <pre><code>int usleep(long usec) { struct timeval tv; fd_set dummy; SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); FD_ZERO(&amp;dummy); FD_SET(s, &amp;dummy); tv.tv_sec = usec/1000000L; tv.tv_usec = usec%1000000L; return select(0, 0, 0, &amp;dummy, &amp;tv); } </code></pre> <p>All these created usleep methods return zero when successful and non-zero for errors.</p>
11,067
<p>I'd like to know how to grab the Window title of the current active window (i.e. the one that has focus) using C#. </p>
<p>See example on how you can do this with full source code here:</p> <p><a href="http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/" rel="noreferrer">http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/</a></p> <pre><code>[DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count); private string GetActiveWindowTitle() { const int nChars = 256; StringBuilder Buff = new StringBuilder(nChars); IntPtr handle = GetForegroundWindow(); if (GetWindowText(handle, Buff, nChars) &gt; 0) { return Buff.ToString(); } return null; } </code></pre> <hr> <p><strong>Edited</strong> with @Doug McClean comments for better correctness.</p>
<p>you can use process class it's very easy. use this namespace </p> <pre><code>using System.Diagnostics; </code></pre> <p>if you want to make a button to get active window.</p> <pre><code>private void button1_Click(object sender, EventArgs e) { Process currentp = Process.GetCurrentProcess(); TextBox1.Text = currentp.MainWindowTitle; //this textbox will be filled with active window. } </code></pre>
14,126
<p>ASP.Net 3.5 running under IIS 7 doesn't seem to allow this out of the box.</p> <pre><code> if (!EventLog.SourceExists("MyAppLog")) EventLog.CreateEventSource("MyAppLog", "Application"); EventLog myLog = new EventLog(); myLog.Source = "MyAppLog"; myLog.WriteEntry("Message"); </code></pre>
<p>This is part of windows security since windows 2003.</p> <p>You need to create an entry in the registry under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application Make sure that network service or the account you impersonate has permission to this registry key.</p> <p>@CheGueVerra's link: <a href="http://support.microsoft.com/?id=329291" rel="noreferrer">Requested Registry Access Is Not Allowed</a></p>
<p>Right click the application and choose "Run as Administrator"</p>
36,338
<p>How can I transform a time value into YYYY-MM-DD format in Java?</p> <pre><code>long lastmodified = file.lastModified(); String lasmod = /*TODO: Transform it to this format YYYY-MM-DD*/ </code></pre>
<p>Something like:</p> <pre><code>Date lm = new Date(lastmodified); String lasmod = new SimpleDateFormat("yyyy-MM-dd").format(lm); </code></pre> <p>See the javadoc for <a href="http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">SimpleDateFormat</a>.</p>
<pre><code>Date d = new Date(lastmodified); DateFormat form = new SimpleDateFormat("yyyy-MM-dd"); String lasmod = form.format(d); </code></pre>
28,028
<p>How do you use enums in Oracle using SQL only? (No PSQL)</p> <p>In MySQL you can do:</p> <pre><code>CREATE TABLE sizes ( name ENUM('small', 'medium', 'large') ); </code></pre> <p>What would be a similar way to do this in Oracle?</p>
<p>Reading a bit about the <a href="http://dev.mysql.com/doc/refman/5.0/en/enum.html" rel="noreferrer">MySQL enum</a>, I'm guessing the closest equivalent would be a simple check constraint</p> <pre><code>CREATE TABLE sizes ( name VARCHAR2(10) CHECK( name IN ('small','medium','large') ) ); </code></pre> <p>but that doesn't allow you to reference the value by the index. A more complicated foreign key relationship would also be possible</p> <pre><code>CREATE TABLE valid_names ( name_id NUMBER PRIMARY KEY, name_str VARCHAR2(10) ); INSERT INTO valid_sizes VALUES( 1, 'small' ); INSERT INTO valid_sizes VALUES( 2, 'medium' ); INSERT INTO valid_sizes VALUES( 3, 'large' ); CREATE TABLE sizes ( name_id NUMBER REFERENCES valid_names( name_id ) ); CREATE VIEW vw_sizes AS SELECT a.name_id name, &lt;&lt;other columns from the sizes table&gt;&gt; FROM valid_sizes a, sizes b WHERE a.name_id = b.name_id </code></pre> <p>As long as you operate through the view, it would seem that your could replicate the functionality reasonably well.</p> <p>Now, if you admit PL/SQL solutions, you can create custom object types that could include logic to limit the set of values they can hold and to have methods to get the IDs and to get the values, etc.</p>
<p>At this link you can find an alternative solution/workaround for Oracle, inspired by C language enums: <a href="http://www.petefinnigan.com/weblog/archives/00001246.htm" rel="nofollow">http://www.petefinnigan.com/weblog/archives/00001246.htm</a></p> <p>Shortly put, Pete suggests to define some integer constants and to use a SUBTYPE to constrait them:</p> <pre class="lang-sql prettyprint-override"><code>RED constant number(1):=1; GREEN constant number(1):=2; BLUE constant number(1):=3; YELLOW constant number(1):=4; subtype COLORS is binary_integer range 1..4; </code></pre> <p>After that you can declare variables, pass parameters and return values from functions and so on, with type COLORS.</p>
24,895
<p>Our website uses Perl to provide a simple mechanism for our HR people to post vacancies to our website. It was developed by a third party, but they have been long since kicked into touch, and sadly we do not have any Perl skills in-house. This is what happens when Marketing people circumvent their in-house IT team!</p> <p>I need to make a simple change to this application. Currently, the vacancies page says 'We currently have the following vacancies:', regardless of whether there are any vacancies! So we want to change it so that this line is only displayed at the appropriate times.</p> <p>I could, obviously, start to learn a bit of Perl, but we are already planning a replacement site, and it certainly won't be using Perl. So since the solution will be trivial for those with these skills, I thought I'd ask for some focused help.</p> <p>Below is the start of the procedure that lists the vacancies. </p> <pre><code>sub list { require HTTP::Date; import HTTP::Date; my $date = [split /\s+/, HTTP::Date::time2iso(time())]-&gt;[0]; my $dbh = DBI-&gt;connect($dsn, $user, $password) || die "cannot connect to $database: $!\n"; my $sql = &lt;&lt;EOSQL; SELECT * FROM $table where expiry &gt;= '$date' order by expiry EOSQL my $sth = $dbh-&gt;prepare($sql); $sth-&gt;execute(); while (my $ref = $sth-&gt;fetchrow_hashref()) { my $temp = $template; $temp =~ s#__TITLE__#$ref-&gt;{'title'}#; my $job_spec = $ref-&gt;{'job_spec'}; ...etc... </code></pre> <p>The key line is <code>while (my $ref = $sth-&gt;fetchrow_hashref()) {</code>. I'm figuring that this is saying 'while I can pull off another vacancy from the returned recordset...'. If I place my print statement before this line, it will always be shown; after this line and it was be repeated for every vacancy.</p> <p>How do I determine that there are some vacancies to be displayed, without prematurely moving through the returned recordset?</p> <p>I could always copy the code within the while loop, and place it within an if() statement (preceding the while loop) which will also include my print statement. But I'd prefer to just have the simpler approach of <code>If any records then print "We currently have.." line</code>. Unfortunately, I haven't a clue to code even this simple line.</p> <p>See, I told you it was a trivial problem, even considering my fumbled explanation!</p> <p>TIA</p> <p>Chris</p>
<p>A really simple way would be:</p> <pre><code>$sth-&gt;execute(); my $first = 1; while (my $ref = $sth-&gt;fetchrow_hashref()) { if( $first ) { print "We currently have the following vacancies:\n"; $first = 0; } my $temp = $template; ... } if( $first ) { print "No vacancies found\n"; } </code></pre>
<p>Says perldoc DBI:</p> <pre><code> For a non-"SELECT" statement, "execute" returns the number of rows affected, if known. If no rows were affected, then "execute" returns "0E0", which Perl will treat as 0 but will regard as true. </code></pre> <p>So the answer is to check the return value of $sth->execute():</p> <pre><code> my $returnval = $sth-&gt;execute; if (defined $returnval &amp;&amp; $returnval == 0) { carp "Query executed successfully but returned nothing"; return; } </code></pre>
36,974
<p>I've got nutch and lucene setup to crawl and index some sites and I'd like to use a .net website instead of the JSP site that comes with nutch.</p> <p>Can anyone recommend some solutions?</p> <p>I've seen solutions where there was an app running on the index server which the .Net site used remoting to connect to.</p> <p>Speed is a consideration obviously so can this still perform well?</p> <p><strong>Edit:</strong> could NHibernate.Search work for this?</p> <p><strong>Edit:</strong> We ended up going with Solr index servers being used by our ASP.net site with the <a href="http://code.google.com/p/solrnet/" rel="nofollow noreferrer">solrnet</a> library.</p>
<p>Instead of using Lucene, you could use <a href="http://lucene.apache.org/solr/" rel="nofollow noreferrer">Solr</a> to index with nutch (see <a href="http://blog.foofactory.fi/2007/02/online-indexing-integrating-nutch-with.html" rel="nofollow noreferrer">here</a>), then you can connect very easily to Solr using one of the two libraries available: <a href="http://www.codeplex.com/solrsharp" rel="nofollow noreferrer">SolrSharp</a> and <a href="http://code.google.com/p/solrnet/" rel="nofollow noreferrer">SolrNet</a>.</p>
<p>Instead of using Solr, I wrote a java based indexer that runs in a cron job, and a java based web service for querying. I actually didn't index pages so much as different types of data that the .net site uses to build the pages. So there's actually 4 different indexes each with a different document structure that can all be queried in about the same way (say: users, posts, messages, photos).</p> <p>By defining an XSD for the web service responses I was able to both generate classes in .net and java to store a representation of the documents. The web service basically runs the query on the right index and fills out the response xml from the hits. The .net client parses that back into objects. There's also a json interface for any client side JavaScript.</p>
25,036
<p>The software base I am developing for uses a signficant amount of yacc which I don't need to deal with. Some times I think it would be helpful in understanding some problems I find but most of the time I can get away with my complete ignorance of yacc.</p> <p>My question are there enough new projects out there that still use yacc to warrant the time I'll need to learn it?</p> <p>Edit: Given the response is mostly in favour of learning Yacc, is there a similar language that you would recommend over yacc?</p>
<p>Yes, these tools are worth learning if you ever need to create or modify code that parses a grammar. </p> <p>For many years the de facto tool for generating code to parse a grammar was yacc, or its GNU cousin, bison.</p> <p>Lately I've heard there are a couple of new kids on the block, but the principle is the same: you write a declarative grammar in a format that is more or less in Backus-Naur Form (<a href="http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form" rel="noreferrer">BNF</a>) and yacc/bison/whatever generates some code for you that would be extremely tedious to write by hand.</p> <p>Also, the principles behind grammars can be very useful to learn even if you don't need to work on such code directly. I haven't worked with parsers much since taking a course on Compiler Design in college, but understanding runtime stacks, lookahead parsers, expression evaluation, and a lot of other related things has helped me immensely to write and debug my code effectively.</p> <p><strong>edit:</strong> Given your followup question about other tools, Yacc/Bison of course are best for C/C++ projects, since they generate C code. There are similar tools for other languages. Not all grammars are equivalent, and some parser generators can only grok grammars of a certain complexity. So you might need to find a tool that can parse your grammar. See <a href="http://en.wikipedia.org/wiki/Comparison_of_parser_generators" rel="noreferrer">http://en.wikipedia.org/wiki/Comparison_of_parser_generators</a></p>
<p>We are writing new yacc code at my company for shipping products. Yes, this stuff is still used.</p>
43,115
<p>In trying to understand 3D printers, I have watched some YouTube videos where the crafters make items with hinges. That in itself blows my mind. It is hard to grasp how something with moving parts can be printed. But specifically I am wondering if the concept can be extended to food printers to make, for example, a sugar or chocolate telescoping lollipop (sucker)?</p>
<p>No, M108 does not do that. You are looking for <strong>T#</strong>, where # is the tool position you want:</p> <pre><code>T1 ; switch to tool position 1 T3 ; switch to tool position 3 </code></pre> <p>This tells the processor to send all heating, cooling and flow commands to this tool until another tool change is specified, and invokes the X/Y(/Z) offset for the new tool position.</p> <p>See <a href="http://reprap.org/wiki/G-code#T:_Select_Tool" rel="nofollow noreferrer">http://reprap.org/wiki/G-code#T:_Select_Tool</a></p>
<p>As @tbm0115 has mentioned - it differs. Your <code>M108 T{index of tool}</code> command is perfectly fine on some FlashForge printers, a company known for its different sorts of proprietary code. It is indeed used for tool changing here.</p> <p>While on the common Marlin firmware (e.g. used on the popular Creality Ender printers), <code>M108</code> does a completely different thing-namely acting as a break sequence if the G-code parser is in a closed-loop-condition (after certain commands like <code>M109</code> that wait until a certain action takes place).</p>
539
<p>I would like a Win machine to tunnel into an SSH server whenever the machine starts up. I also want the win machine to reboot the SSH program if it ever crashes. The lighterweight &amp; more stable the SSH program, the more happier I am.</p> <p>What options do I have with this? </p>
<p>Look at using srvany to launch the SSH client as a windows service. Then you can set the service to start up automatically when Windows start.</p> <p>Essentially, srvany.exe will let you launch any program from the windows service control manager.</p> <p><a href="http://support.microsoft.com/kb/137890" rel="noreferrer">http://support.microsoft.com/kb/137890</a></p>
<p>If you desire <strong>program restarting</strong> in case of disconnection, the best I know should be a software recommendation: <a href="http://www.coretechnologies.com/products/AlwaysUp/" rel="nofollow">AlwaysUp</a> (not free on May 2015). </p> <p>It is still <strong>lighweight</strong>, 4.2MB installer and a not too big <strong>memory consumer</strong>:</p> <pre><code>C:\&gt;tasklist | find "always" /i AlwaysUp.exe 3112 Console 1 17.388 KB </code></pre> <p>When converting to service, <strong>Stability</strong> (or just making the service work) with <code>SrvAny</code> or <code>SC</code> can be a nightmare. <em>AlwaysUp</em>, as long as I have tested, solves most problems and give you <strong>extra options</strong> like a detailed log, statistics, email alerts... etc.</p>
40,274
<p>I've added a custom soap header <code>&lt;MyApp:FOO&gt;</code> element to the <code>&lt;soap:Header&gt;</code> element and the requirments states that i must sign this element , how would one do that? <code>&lt;MyApp:FOO&gt;</code> contains a number of things (username, preferences, etc) that identifies a user on higher level. I've succesfully used a policy file and now a policyClass with CertificateAssertions and SoapFilters to sign wsu:Timestamp, wsu:action, wsu:MessageId etc. But now the <code>&lt;MyApp:FOO&gt;</code> element needs to signed aswell.</p> <p>What i've understood this far is that the element that needs to be signed must be indentified with a wsu:Id attribute and then transformed using xml-exc-c14n.</p> <p>So, how do I specify that the soap header should be signed aswell? This is the current class that i use for signing my message.</p> <pre><code>internal class FOOClientOutFilter: SendSecurityFilter { X509SecurityToken clientToken; public FOOClientOutFilter(SSEKCertificateAssertion parentAssertion) : base(parentAssertion.ServiceActor, true) { // Get the client security token. clientToken = X509TokenProvider.CreateToken(StoreLocation.CurrentUser, StoreName.My, "CN=TestClientCert"); // Get the server security token. serverToken = X509TokenProvider.CreateToken(StoreLocation.LocalMachine, StoreName.My, "CN=TestServerCert"); } public override void SecureMessage(SoapEnvelope envelope, Security security) { // Sign the SOAP message with the client's security token. security.Tokens.Add(clientToken); security.Elements.Add(new MessageSignature(clientToken)); } } </code></pre>
<p>My current version of SecureMessage seems to do the trick..</p> <pre><code> public override void SecureMessage(SoapEnvelope envelope, Security security) { //EncryptedData data = new EncryptedData(userToken); SignatureReference ssekSignature = new SignatureReference(); MessageSignature signature = new MessageSignature(clientToken); // encrypt custom headers for (int index = 0; index &lt; envelope.Header.ChildNodes.Count; index++) { XmlElement child = envelope.Header.ChildNodes[index] as XmlElement; // find all FOO headers if (child != null &amp;&amp; child.Name == "FOO") { string id = Guid.NewGuid().ToString(); child.SetAttribute("Id", "http://docs.oasis-" + "open.org/wss/2004/01/oasis-200401-" + "wss-wssecurity-utility-1.0.xsd", id); signature.AddReference(new SignatureReference("#" + id)); } } // Sign the SOAP message with the client's security token. security.Tokens.Add(clientToken); security.Elements.Add(signature); } </code></pre>
<p>Including supplementary articles from MSDN</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa529237.aspx" rel="nofollow noreferrer"><strong>How to: Add an Id Attribute to a SOAP Header</strong></a></p> <p><a href="http://msdn.microsoft.com/en-us/library/aa528813.aspx" rel="nofollow noreferrer"><strong>How to: Digitally Sign a Custom SOAP Header</strong></a></p>
18,390
<p>I use svn:externals to reference several open source projects. I then make some local changes to one of these external projects. Obviously I cannot check these changes back into the external repository. How do I keep these changes in my repository while still maintaining the ability to easily incorporate external changes?</p> <p>Git makes this quite easy, but I use Subversion, so I am looking for an SVN friendly way to do this. (I use Tortoise SVN client against a 1.5+ SVN server).</p>
<p>Just in case it's still relevant, and for future users: I think you want to maintain your changes to the external project in a <a href="http://svnbook.red-bean.com/en/1.5/svn.advanced.vendorbr.html" rel="nofollow noreferrer">'vendor branch'</a>.</p> <ul> <li>import a copy of the external code into a separate project in your repository</li> <li>create a branch of it in your own project, to which you can add your own modifications</li> <li>regularly, you update the project's code in the original branch so you can merge these changes into your own branch.</li> </ul>
<p>I support <a href="https://stackoverflow.com/questions/329843/external-repository-changes/1156028#1156028">jeroenh</a>'s answer above since you are using an "SVN Friendly" way to maintain external code. </p> <p>svk is not a solution as you cannot commit what you've changed to the external repos. If you use svk, you might as well just edit the external code in svn...just don't commit them.</p>
42,730
<p>Is it possible to detect a valid regular expression with another regular expression? If so please give example code below.</p>
<pre><code>/ ^ # start of string ( # first group start (?: (?:[^?+*{}()[\]\\|]+ # literals and ^, $ | \\. # escaped characters | \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes (?: [^\]\\]+ | \\. )* \] | \( (?:\?[:=!]|\?&lt;[=!]|\?&gt;)? (?1)?? \) # parenthesis, with recursive content | \(\? (?:R|[+-]?\d+) \) # recursive matching ) (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers | \| # alternative )* # repeat content ) # end first group $ # end of string / </code></pre> <p>This is a recursive regex, and is not supported by many regex engines. PCRE based ones should support it.</p> <p>Without whitespace and comments:</p> <pre><code>/^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?&lt;[=!]|\?&gt;)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/ </code></pre> <hr> <p>.NET does not support recursion directly. (The <code>(?1)</code> and <code>(?R)</code> constructs.) The recursion would have to be converted to counting balanced groups:</p> <pre><code>^ # start of string (?: (?: [^?+*{}()[\]\\|]+ # literals and ^, $ | \\. # escaped characters | \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes (?: [^\]\\]+ | \\. )* \] | \( (?:\?[:=!] | \?&lt;[=!] | \?&gt; | \?&lt;[^\W\d]\w*&gt; | \?'[^\W\d]\w*' )? # opening of group (?&lt;N&gt;) # increment counter | \) # closing of group (?&lt;-N&gt;) # decrement counter ) (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers | \| # alternative )* # repeat content $ # end of string (?(N)(?!)) # fail if counter is non-zero. </code></pre> <p>Compacted:</p> <pre><code>^(?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?&lt;[=!]|\?&gt;|\?&lt;[^\W\d]\w*&gt;|\?'[^\W\d]\w*')?(?&lt;N&gt;)|\)(?&lt;-N&gt;))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*$(?(N)(?!)) </code></pre> <p>From the comments:</p> <blockquote> <p>Will this validate substitutions and translations?</p> </blockquote> <p>It will validate just the regex part of substitutions and translations. <code>s/&lt;this part&gt;/.../</code></p> <blockquote> <p>It is not theoretically possible to match all valid regex grammars with a regex. </p> </blockquote> <p>It is possible if the regex engine supports recursion, such as PCRE, but that can't really be called regular expressions any more.</p> <blockquote> <p>Indeed, a "recursive regular expression" is not a regular expression. But this an often-accepted extension to regex engines... Ironically, this extended regex doesn't match extended regexes.</p> </blockquote> <p>"In theory, theory and practice are the same. In practice, they're not." Almost everyone who knows regular expressions knows that regular expressions does not support recursion. But PCRE and most other implementations support much more than basic regular expressions.</p> <blockquote> <p>using this with shell script in the grep command , it shows me some error.. grep: Invalid content of {} . I am making a script that could grep a code base to find all the files that contain regular expressions</p> </blockquote> <p>This pattern exploits an extension called recursive regular expressions. This is not supported by the POSIX flavor of regex. You could try with the -P switch, to enable the PCRE regex flavor.</p> <blockquote> <p>Regex itself "is not a regular language and hence cannot be parsed by regular expression..."</p> </blockquote> <p>This is true for classical regular expressions. Some modern implementations allow recursion, which makes it into a Context Free language, although it is somewhat verbose for this task.</p> <blockquote> <p>I see where you're matching <code>[]()/\</code>. and other special regex characters. Where are you allowing non-special characters? It seems like this will match <code>^(?:[\.]+)$</code>, but not <code>^abcdefg$</code>. That's a valid regex.</p> </blockquote> <p><code>[^?+*{}()[\]\\|]</code> will match any single character, not part of any of the other constructs. This includes both literal (<code>a</code> - <code>z</code>), and certain special characters (<code>^</code>, <code>$</code>, <code>.</code>).</p>
<p>In Javascript:</p> <pre><code>SyntaxError </code></pre> <p>is thrown when an invalid regex is passed to evaluate.</p> <pre><code>// VALID ONE &gt; /yes[^]*day/ Out: /yes[^]*day/ // INVALID ONE &gt; /yes[^*day/ Out: VM227:1 Uncaught SyntaxError: Invalid regular expression: missing / </code></pre> <p>Here's the function to check if the regex string is valid:</p> <p>Step 1: Regex Parser</p> <pre><code>var RegexParser = function(input) { // Parse input var m = input.match(/(\/?)(.+)\1([a-z]*)/i); // Invalid flags if (m[3] &amp;&amp; !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3])) { return RegExp(input); } // Create the regular expression return new RegExp(m[2], m[3]); }; </code></pre> <p>Step 2: Use parser</p> <pre><code>var RegexString = &quot;/yes.*day/&quot; var isRegexValid = input =&gt; { try { const regex = RegexParser(input); } catch(error) { if(error.name === &quot;SyntaxError&quot;) { return false; } else { throw error; } } return true; } </code></pre>
20,767
<p>How to move a sub directory from one directory to another, given that both are inside the same SVN repository? I am using tortoise SVN.</p>
<p>Select the folder/files that you want to move, then RIGHT-CLICK them and drag them to where you want to move them. A menu will come up with an option "<strong>SVN Move versioned files here</strong>"</p> <p>As clarified by <a href="https://stackoverflow.com/questions/264571/move-directory-across-svn-repository-using-tortoise-svn/1894533#1894533">phenry</a>, the destination folder must be recognized as an SVN folder. The folder should already be committed to the repository or you can choose Add to set it to be added.</p> <p>If the destination folder isn't part of an SVN repository, use the SVN Export command after your right-click and drag to copy the files to any destination folder.</p>
<p>If you have renamed the parent folder before moving, you would see a "Cross/Not allowed" sign when moving. </p> <p>The workaround is to first move the child and then only re-name the parent (undo if you already renamed the parent). </p>
33,143
<p>Is there a clean, preferably standard method of trimming leading and trailing whitespace from a string in C? I'd roll my own, but I would think this is a common problem with an equally common solution.</p>
<p>If you can modify the string:</p> <pre><code>// Note: This function returns a pointer to a substring of the original string. // If the given string was allocated dynamically, the caller must not overwrite // that pointer with the returned value, since the original pointer must be // deallocated using the same allocator with which it was allocated. The return // value must NOT be deallocated using free() etc. char *trimwhitespace(char *str) { char *end; // Trim leading space while(isspace((unsigned char)*str)) str++; if(*str == 0) // All spaces? return str; // Trim trailing space end = str + strlen(str) - 1; while(end &gt; str &amp;&amp; isspace((unsigned char)*end)) end--; // Write new null terminator character end[1] = '\0'; return str; } </code></pre> <p>If you can't modify the string, then you can use basically the same method:</p> <pre><code>// Stores the trimmed input string into the given output buffer, which must be // large enough to store the result. If it is too small, the output is // truncated. size_t trimwhitespace(char *out, size_t len, const char *str) { if(len == 0) return 0; const char *end; size_t out_size; // Trim leading space while(isspace((unsigned char)*str)) str++; if(*str == 0) // All spaces? { *out = 0; return 1; } // Trim trailing space end = str + strlen(str) - 1; while(end &gt; str &amp;&amp; isspace((unsigned char)*end)) end--; end++; // Set output size to minimum of trimmed string length and buffer size minus 1 out_size = (end - str) &lt; len-1 ? (end - str) : len-1; // Copy trimmed string and add null terminator memcpy(out, str, out_size); out[out_size] = 0; return out_size; } </code></pre>
<p>Here is a function to do what you want. It should take care of degenerate cases where the string is all whitespace. You must pass in an output buffer and the length of the buffer, which means that you have to pass in a buffer that you allocate.</p> <pre><code>void str_trim(char *output, const char *text, int32 max_len) { int32 i, j, length; length = strlen(text); if (max_len &lt; 0) { max_len = length + 1; } for (i=0; i&lt;length; i++) { if ( (text[i] != ' ') &amp;&amp; (text[i] != '\t') &amp;&amp; (text[i] != '\n') &amp;&amp; (text[i] != '\r')) { break; } } if (i == length) { // handle lines that are all whitespace output[0] = 0; return; } for (j=length-1; j&gt;=0; j--) { if ( (text[j] != ' ') &amp;&amp; (text[j] != '\t') &amp;&amp; (text[j] != '\n') &amp;&amp; (text[j] != '\r')) { break; } } length = j + 1 - i; strncpy(output, text + i, length); output[length] = 0; } </code></pre> <p>The if statements in the loops can probably be replaced with <strong>isspace(text[i])</strong> or <strong>isspace(text[j])</strong> to make the lines a little easier to read. I think that I had them set this way because there were some characters that I didn't want to test for, but it looks like I'm covering all whitespace now :-)</p>
14,916
<p>I am working on creating a custom project template with Visual Studio 2008 Team System edition. I have also created a custom wizard for the custom template.</p> <p>So I have to update the vstemplate file to tell the template to use my custom wizard. But the archive is corrupted!</p> <p>7zip thinks folders within the archive are using non-standard zip compression. The latest winzip thinks the CRC header on the folders doesn't match the main CRC header.</p> <p>What am I doing wrong?</p> <p>If I don't change the template zip file created by VS2008, it works just fine. But I need to be able to update the zip file. If I do, 7zip/winzip fixes the zip file structure and then VS2008 doesn't like the template anymore. Files that are in folders within the zip file are inaccessible.</p> <p>I do notice that the standard templates seem to keep a flat file structure. That is no nested folders or anything. But the vstemplate file has targetfilename attributes that recreate the original folder structure.</p> <p>For example instead of...</p> <pre><code>&lt;Folder Name="My Project" TargetFolderName="My Project"&gt; &lt;ProjectItem ReplaceParameters="true" TargetFileName="AssemblyInfo.vb"&gt;AssemblyInfo.vb&lt;/ProjectItem&gt; &lt;/Folder&gt; </code></pre> <p>the standard vstemplate defines the following...</p> <pre><code>&lt;ProjectItem ReplaceParameters="true" TargetFileName="My Project\AssemblyInfo.vb"&gt;AssemblyInfo.vb&lt;/ProjectItem&gt; </code></pre> <p>I've just had a little think about the above. Are they actually the same thing?</p> <p>Is the problem with the creation of the original zip file?</p> <p>Is the folder structure within the zip file tripping everything up?</p> <p>Should it have added all the files to the zip archive in as flat folder structure? If so is there a fix for VS2008 so that I do not have to manually fix the template archives?</p>
<p>You don't need to modify the contents of the archive to be flat.</p> <p>The trick is after editing the unzipped contents of the archive, instead of selecting the folder and zipping that, open the folder and select all the files (and folders if present), and zip those instead.</p> <p>This is what is preventing Visual Studio from recognizing the archive as a template. This should work with 7-Zip, WinRAR, or whatever you happen to prefer to the bloatware that is WinZip.</p>
<p>Same problem here. I solved it by using <code>&lt;ProjectItem&gt;MyFolder\MyFile.cs&lt;/ProjectItem&gt;</code> instead of <code>&lt;Folder&gt;...&lt;Folder&gt;</code>.</p> <p>PS: TargetFileName doesn't work for me in VS2008 + Windows7.</p>
33,628
<p>I've seen a number of examples that have a thread procedure that looks like this.</p> <pre><code> private void ThreadProc() { while (serviceStarted) { // do some work Thread.Sleep(new TimeSpan(0, 0, 5)); } Thread.CurrentThread.Abort(); } </code></pre> <p>Is the <code>Abort()</code> really necessary at the end?</p> <p>There are number of arguments against calling <code>Abort()</code></p> <ol> <li>Once the procedure exited - it is expected it has already cleaned up after itself.</li> <li>Calling <code>Abort()</code> throws an exception, which is generally more resource intensive than just exiting a procedure.</li> </ol> <p>I'd like to read an explanation for why this is or isn't a good practice.</p>
<p>Calling <code>Thread.Abort()</code> does raise an exception, and if you're writing code that will be re-used (or part of a base library) it's difficult for other developers to handle <code>ThreadAbortExcpetion</code>s. </p> <p>It's explained in this article about <a href="http://msdn.microsoft.com/en-us/library/ms228970(VS.80).aspx" rel="nofollow noreferrer">Reliability Best Practices</a>.</p> <p>I've always heard that calling <a href="http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx" rel="nofollow noreferrer"><code>Thread.Join()</code></a> is a better way to do it, if you can wait until the thread is completed processing.</p> <p>I don't know if anyone thinks it's a good practice. It can cause deadlocks (because unmanaged resources aren't properly cleaned up when you throw an exception)</p> <p>Here's <a href="http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation" rel="nofollow noreferrer">another article about it</a>, and other methods to deal with the issue.</p>
<p>Interesting question. But I would advise against it since such a statement would prevent the method from being reused easily.</p>
41,649
<p>I've worked with T-SQL for years but I've just moved to an organisation that is going to require writing some Oracle stuff, probably just simple CRUD operations at least until I find my feet. I'm not going to be migrating databases from one to the other simply interacting with existing Oracle databases from an Application Development perspective. Is there are tool or utility available to easily translate T-SQL into Oracle SQL, a keyword mapper is the sort of thing I'm looking for.</p> <p>P.S. I'm too lazy to RTFM, besides it's not going to be a big part of my role so I just want something to get me up to speed a little faster.</p>
<p>The language difference listed so far are <strong>trivial</strong> compared to the logical differences. Anyone can lookup NVL. What's hard to lookup is </p> <p><strong>DDL</strong></p> <p>In SQL server you manipulate your schema, anywhere, anytime, with little or no fuss.</p> <p>In Oracle, we don't like DDL in stored procedures so you have jump through hoops. You need to use EXECUTE IMMEDIATE to perform a DDL function.</p> <p><strong>Temp Tables</strong></p> <p>IN SQL Server when the logic becomes a bit tough, the common thing is to shortcut the sql and have it resolved to a temp table and then the next step is done using that temp table. MSSS makes it very easy to do this.</p> <p>In Oracle we don't like that. By forcing an intermediate result you completely prevent the Optimizer from finding a shortcut for you. BUT If you must stop halfway and persist the intermediate results Oracle wants you to make the temp table in advance, not on the fly.</p> <p><strong>Locks</strong></p> <p>In MSSS you worry about locking, you have nolock hints to apply to DML, you have lock escalation to reduce the count of locks.</p> <p>In Oracle we don't worry about these in that way.</p> <p><strong>Read Commited</strong></p> <p>Until recently MSSS didn't fully handle Read Committed isolation so you worried about dirty reads.</p> <p>Oracle has been that way for decades.</p> <p><strong>etc</strong></p> <p>MSSS has no concept of Bitmap indexes, IOT, Table Clusters, Single Table hash clusters, non unique indexes enforcing unique constraints....</p>
<p>If you're doing a one-off conversion, rather than trying to support two versions, you must look at <a href="http://www.oracle.com/technology/tech/migration/workbench/index_sqldev_omwb.html" rel="nofollow noreferrer">Oracle Migration Workbench</a>. This tool works with Oracle's SQLDeveloper (which you really should have if you are working with Oracle). This does a conversion of the schema, data, and some of the T-SQL to PL/SQL. Knowing both well, I found it did about an 80% job. Good enough to make it worth while to convert the bulk of procedures, and hand convert the remainder "tougher" unknown parts. </p>
6,316
<p>Let's say that you want to output or concat strings. Which of the following styles do you prefer?</p> <ul> <li><p><code>var p = new { FirstName = "Bill", LastName = "Gates" };</code></p></li> <li><p><code>Console.WriteLine("{0} {1}", p.FirstName, p.LastName);</code></p></li> <li><p><code>Console.WriteLine(p.FirstName + " " + p.LastName);</code></p></li> </ul> <p>Do you rather use format or do you simply concat strings? What is your favorite? Is one of these hurting your eyes?</p> <p>Do you have any rational arguments to use one and not the other?</p> <p>I'd go for the second one.</p>
<p>Try this code.</p> <p>It's a slightly modified version of your code.<BR></p> <ol> <li>I removed Console.WriteLine as it's probably a few orders of magnitude slower than what I'm trying to measure.<BR></li> <li>I'm starting the Stopwatch before the loop and stopping it right after, this way I'm not losing precision if the function takes for example 26.4 ticks to execute. <BR></li> <li>The way you divided the result by some iterations was wrong. See what happens if you have 1,000 milliseconds and 100 milliseconds. In both situations, you will get 0 ms after dividing it by 1,000,000.</li> </ol> <p>Code:</p> <pre><code>Stopwatch s = new Stopwatch(); var p = new { FirstName = &quot;Bill&quot;, LastName = &quot;Gates&quot; }; int n = 1000000; long fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0; string result; s.Start(); for (var i = 0; i &lt; n; i++) result = (p.FirstName + &quot; &quot; + p.LastName); s.Stop(); cElapsedMilliseconds = s.ElapsedMilliseconds; cElapsedTicks = s.ElapsedTicks; s.Reset(); s.Start(); for (var i = 0; i &lt; n; i++) result = string.Format(&quot;{0} {1}&quot;, p.FirstName, p.LastName); s.Stop(); fElapsedMilliseconds = s.ElapsedMilliseconds; fElapsedTicks = s.ElapsedTicks; s.Reset(); Console.Clear(); Console.WriteLine(n.ToString()+&quot; x result = string.Format(\&quot;{0} {1}\&quot;, p.FirstName, p.LastName); took: &quot; + (fElapsedMilliseconds) + &quot;ms - &quot; + (fElapsedTicks) + &quot; ticks&quot;); Console.WriteLine(n.ToString() + &quot; x result = (p.FirstName + \&quot; \&quot; + p.LastName); took: &quot; + (cElapsedMilliseconds) + &quot;ms - &quot; + (cElapsedTicks) + &quot; ticks&quot;); Thread.Sleep(4000); </code></pre> <p>Those are my results:</p> <blockquote> <p>1000000 x result = string.Format(&quot;{0} {1}&quot;, p.FirstName, p.LastName); took: 618ms - 2213706 ticks<br /> 1000000 x result = (p.FirstName + &quot; &quot; + p.LastName); took: 166ms - 595610 ticks</p> </blockquote>
<p>Actually, I ran these tests yesterday, but it was getting late so I didnt put my responses.</p> <p>The bottom line seems that they take both the same time on average. I did the test over 100000 iterations.</p> <p>I'll try with StringBuilder as well, and I'll post the code and results when I get home.</p>
3,713
<p>I have a 100% valid Ajax model written in Javascript with a few inputs I use being, Get or Post method, What page to communicate with, What String to send to that page and What element on my own page I might be fiddling with when I receive my response. The problem is that, should I set the request to Asynchronous (Hence Ajax), IE returns the error "The Data Necessary to Complete This Operation is Not Yet Available" in the onreadystatechange event where all I do is check if the readystate is 4 and the status is 200. The error doesn't come up in Firefox or Chrome as I would exepect as the Ajax is Asynchronous.</p> <p>Heres a snippet from the Post method</p> <pre><code>xmlhttp.open("POST", commPage, true); xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) { j = xmlhttp.responseText; i.innerHTML = j; } } xmlhttp.send(str); </code></pre> <p>Edit: I should point out that in IE, I'm using the ActiveX Control -> Msxml2.XMLHTTP or Microsoft.XMLHTTP or whichever returns true first.</p>
<p>Ho humm</p> <p>Outside of the onreadystatechange function I had a call for responsetext to check whether it existed yet, but aparently you can't do that if it doesn't exist yet so I just had to restructure some thigs. All is okay but this was the script that caused the problem</p> <pre><code>ajaxRequest(){ [...] } if(xmlhttp.responseText){ myFunc(); } </code></pre>
<p>Not sure if that's your case but I've just been struggling with this error for three hours until I found the problem. The web service class wasn't decorated with ScriptService attribute that allows methods to be called from client script! I wouldn't blame IE because IE is just strict on errors and reports everything what other browsers ignore. IE is good for debugging. Hope this helps. Well... probably not you as your post is now very old.</p>
49,796
<p>Why does <code>n</code> not equal to <code>8</code> in the following function?</p> <pre><code>void foo(char cvalue[8]) { int n = sizeof (cvalue); } </code></pre> <p>But <code>n</code> <em>does</em> equal to <code>8</code> in this version of the function:</p> <pre><code>void bar() { char cvalue[8]; int n = sizeof (cvalue); } </code></pre>
<p>Because you can't pass entire arrays as function parameters in C. You're actually passing a pointer to it; the brackets are syntactic sugar. There are no guarantees the array you're pointing to has size 8, since you could pass this function any character pointer you want.</p> <pre><code>// These all do the same thing void foo(char cvalue[8]) void foo(char cvalue[]) void foo(char *cvalue) </code></pre>
<p>The size of the parameter on 32-bit systems will be 4 and on 64-bit systems compiled with -m64 will be 8. This is because arrays are passed as pointers in functions. The pointer is merely a memory address.</p>
7,146
<p>I have a method, which will accept a parameter of a JQuery Object and will calculate totals for a section. So if you give it a JQuery Object of a div containing the section it will calculate a total for it</p> <p>so you can do this:</p> <p>var $totalcompletion = CalculateSectionCompletion(jQuery("#Section1"));</p> <p>Now I have multiple divs with the class of section container. I want to be able to call the above method on any div with that class.</p> <p>I'm doing this:</p> <p>jQuery("div.SectionContainer").each( function(i, valueOfElement){<br> CalculateSectionCompletion(valueOfElement);<br> });</p> <p>The problem is the valueOfElement is actually the DOM object and not the JQuery Object, so I can't pass this in to my method.</p> <p>Is there anyway I can loop through all JQuery Objects selected by a query, without writing some dirty code to extract the Id from the DOM object, and call JQuery(valueOfElement.id) and pass it in?</p>
<p>You can wrap any DOM element in $(..), as you do with $(document).</p> <p>So I think you should be able to </p> <pre><code>jQuery("div.SectionContainer").each( function(i, valueOfElement){ CalculateSectionCompletion($(valueOfElement)); }); </code></pre>
<p>You could also ignore the i and valueOfElement arguments altogether and use <strong>this</strong>.</p> <pre><code>jQuery("div.SectionContainer").each(function(){ CalculateSectionCompletion(jQuery(this)); }); </code></pre> <p>You could even make the CalculateSectionCompletion function wrap it's argument in the jQuery object.</p> <pre><code>jQuery("div.SectionContainer").each(function(){ CalculateSectionCompletion(this); }); function CalculateSectionCopletion(e){ jQuery(e).dostuff(); } </code></pre>
46,783
<p>I've developed a "Proof of Concept" application that logs unhandled exceptions from an application to a bug-tracking system (in this case Team Foundation Server, but it could be ANY bug tracking system). A limitation of this idea is that I don't want duplicate Bug Items opened every time the same exception is thrown (for example, many users encounter the exception - it's still a single "bug").</p> <p>My first attempt was to store the Exception Type, Message and Stack Trace as fields in the Bug Tracking System.The logging component would then do a query against the Bug "Store" to see if there is an open bug with the same information. (This example is .NET - but I would think the concept is platform independant). </p> <p>The problem obviously is that these fields can be very large (particularly the stack trace) - and requires a "Full-Text" type of implementation to store them and the searching is very expensive.</p> <p>I was wondering what approaches have been defined for this problem. I had heard that FogBugz for example had such a feature for automated bug tracking, and was curious how it was implemented.</p>
<p>You could create a checksum hash of the stack trace and store that as an indexed column. That way the query to the Bug Store would be pretty fast to avoid duplicates on insert.</p>
<p>You could look at the source code for one of the existing open-source solutions that aggregate exceptions.</p> <p>For example: <a href="https://github.com/getsentry/sentry/tree/master/src/sentry" rel="nofollow">https://github.com/getsentry/sentry/tree/master/src/sentry</a></p> <p>It is not a simple problem and there are complex heuristics (e.g. same exception reported different ways on different browsers, e.g. exceptions caused by browser extensions are common and are rarely important).</p>
36,307
<p>Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.</p>
<p>Here is the <a href="http://docs.python-requests.org/en/latest/" rel="noreferrer">Requests</a> way:</p> <pre><code>import requests r = requests.get('http://github.com', allow_redirects=False) print(r.status_code, r.headers['Location']) </code></pre>
<p>I second olt's pointer to <a href="http://www.diveintopython.org/http_web_services/redirects.html" rel="noreferrer">Dive into Python</a>. Here's an implementation using urllib2 redirect handlers, more work than it should be? Maybe, shrug.</p> <pre><code>import sys import urllib2 class RedirectHandler(urllib2.HTTPRedirectHandler): def http_error_301(self, req, fp, code, msg, headers): result = urllib2.HTTPRedirectHandler.http_error_301( self, req, fp, code, msg, headers) result.status = code raise Exception("Permanent Redirect: %s" % 301) def http_error_302(self, req, fp, code, msg, headers): result = urllib2.HTTPRedirectHandler.http_error_302( self, req, fp, code, msg, headers) result.status = code raise Exception("Temporary Redirect: %s" % 302) def main(script_name, url): opener = urllib2.build_opener(RedirectHandler) urllib2.install_opener(opener) print urllib2.urlopen(url).read() if __name__ == "__main__": main(*sys.argv) </code></pre>
13,575
<p>I have a custom aspx page loaded in a IFrame in one of the modules in MS CRM 4.0. This page basically has 6 textboxes (txtValue1, txtValue2 and so on..) with values in it. I want to access these values through javascript code either on the load event or save event. Does anybody know how to do it ? I tried couple of codes that i got from net but nothing seems to work. Any help on this would appreciated.</p>
<p>I know that in Ant, the junit task has options "haltonerror" and "haltonfailure" that controls this behavior.</p>
<p>I know that in Ant, the junit task has options "haltonerror" and "haltonfailure" that controls this behavior.</p>
22,869
<p>Given this HTML:</p> <pre><code>&lt;ul id="topnav"&gt; &lt;li id="topnav_galleries"&gt;&lt;a href="#"&gt;Galleries&lt;/a&gt;&lt;/li&gt; &lt;li id="topnav_information"&gt;&lt;a href="#"&gt;Information&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And this CSS:</p> <pre class="lang-css prettyprint-override"><code>#topnav_galleries a, #topnav_information a { background-repeat: no-repeat; text-indent: -9000px; padding: 0; margin: 0 0; overflow: hidden; height: 46px; width: 136px; display: block; } #topnav { list-style-type: none; } #topnav_galleries a { background-image: url('image1.jpg'); } #topnav_information a { background-image: url('image2.jpg'); } </code></pre> <p>How would I go about turning the <code>topnav</code> list into an inline list?</p>
<p>Try this:</p> <pre class="lang-css prettyprint-override"><code>#topnav { overflow:hidden; } #topnav li { float:left; } </code></pre> <p>And for IE you will need to add the following:</p> <pre class="lang-css prettyprint-override"><code>#topnav { zoom:1; } </code></pre> <p>Otherwise your floated &lt; li > tags will spill out of the containing &lt; ul >.</p>
<p>An alternative to floating the elements left, is this:</p> <pre class="lang-css prettyprint-override"><code>#topnav li { display: inline; } </code></pre>
6,696
<p>In order to help my team write testable code, I came up with this simple list of best practices for making our C# code base more testable. (Some of the points refer to limitations of Rhino Mocks, a mocking framework for C#, but the rules may apply more generally as well.) Does anyone have any best practices that they follow?</p> <p>To maximize the testability of code, follow these rules:</p> <ol> <li><p><strong>Write the test first, then the code.</strong> Reason: This ensures that you write testable code and that every line of code gets tests written for it.</p></li> <li><p><strong>Design classes using dependency injection.</strong> Reason: You cannot mock or test what cannot be seen.</p></li> <li><p><strong>Separate UI code from its behavior using Model-View-Controller or Model-View-Presenter.</strong> Reason: Allows the business logic to be tested while the parts that can't be tested (the UI) is minimized.</p></li> <li><p><strong>Do not write static methods or classes.</strong> Reason: Static methods are difficult or impossible to isolate and Rhino Mocks is unable to mock them.</p></li> <li><p><strong>Program off interfaces, not classes.</strong> Reason: Using interfaces clarifies the relationships between objects. An interface should define a service that an object needs from its environment. Also, interfaces can be easily mocked using Rhino Mocks and other mocking frameworks.</p></li> <li><p><strong>Isolate external dependencies.</strong> Reason: Unresolved external dependencies cannot be tested.</p></li> <li><p><strong>Mark as virtual the methods you intend to mock.</strong> Reason: Rhino Mocks is unable to mock non-virtual methods.</p></li> </ol>
<p>Definitely a good list. Here are a few thoughts on it:</p> <blockquote> <p><strong>Write the test first, then the code.</strong></p> </blockquote> <p>I agree, at a high level. But, I'd be more specific: "Write a test first, then write <em>just enough</em> code to pass the test, and repeat." Otherwise, I'd be afraid that my unit tests would look more like integration or acceptance tests.</p> <blockquote> <p><strong>Design classes using dependency injection.</strong></p> </blockquote> <p>Agreed. When an object creates its own dependencies, you have no control over them. Inversion of Control / Dependency Injection gives you that control, allowing you to isolate the object under test with mocks/stubs/etc. This is how you test objects in isolation.</p> <blockquote> <p><strong>Separate UI code from its behavior using Model-View-Controller or Model-View-Presenter.</strong></p> </blockquote> <p>Agreed. Note that even the presenter/controller can be tested using DI/IoC, by handing it a stubbed/mocked view and model. Check out <a href="http://www.atomicobject.com/pages/Presenter+First" rel="noreferrer">Presenter First</a> TDD for more on that.</p> <blockquote> <p><strong>Do not write static methods or classes.</strong></p> </blockquote> <p>Not sure I agree with this one. It is possible to unit test a static method/class without using mocks. So, perhaps this is one of those Rhino Mock specific rules you mentioned.</p> <blockquote> <p><strong>Program off interfaces, not classes.</strong> </p> </blockquote> <p>I agree, but for a slightly different reason. Interfaces provide a great deal of flexibility to the software developer - beyond just support for various mock object frameworks. For example, it is not possible to support DI properly without interfaces. </p> <blockquote> <p><strong>Isolate external dependencies.</strong> </p> </blockquote> <p>Agreed. Hide external dependencies behind your own facade or adapter (as appropriate) with an interface. This will allow you to isolate your software from the external dependency, be it a web service, a queue, a database or something else. This is <em>especially</em> important when your team doesn't control the dependency (a.k.a. external).</p> <blockquote> <p><strong>Mark as virtual the methods you intend to mock.</strong> </p> </blockquote> <p>That's a limitation of Rhino Mocks. In an environment that prefers hand coded stubs over a mock object framework, that wouldn't be necessary.</p> <p>And, a couple of new points to consider:</p> <p><strong>Use creational design patterns.</strong> This will assist with DI, but it also allows you to isolate that code and test it independently of other logic.</p> <p><strong>Write tests using <a href="http://weblogs.java.net/blog/wwake/archive/2003/12/tools_especiall.html" rel="noreferrer">Bill Wake's Arrange/Act/Assert technique</a>.</strong> This technique makes it very clear what configuration is necessary, what is actually being tested, and what is expected.</p> <p><strong>Don't be afraid to roll your own mocks/stubs.</strong> Often, you'll find that using mock object frameworks makes your tests incredibly hard to read. By rolling your own, you'll have complete control over your mocks/stubs, and you'll be able to keep your tests readable. (Refer back to previous point.)</p> <p><strong>Avoid the temptation to refactor duplication out of your unit tests into abstract base classes, or setup/teardown methods.</strong> Doing so hides configuration/clean-up code from the developer trying to grok the unit test. In this case, the clarity of each individual test is more important than refactoring out duplication.</p> <p><strong>Implement Continuous Integration.</strong> Check-in your code on every "green bar." Build your software and run your full suite of unit tests on every check-in. (Sure, this isn't a coding practice, per se; but it is an incredible tool for keeping your software clean and fully integrated.)</p>
<p>Here's a another one that I thought of that I like to do.</p> <p>If you plan to run tests from the unit test Gui as opposed to from TestDriven.Net or NAnt then I've found it easier to set the unit testing project type to console application rather than library. This allows you to run tests manually and step through them in debug mode (which the aforementioned TestDriven.Net can actually do for you).</p> <p>Also, I always like to have a Playground project open for testing bits of code and ideas I'm unfamiliar with. This should not be checked into source control. Even better, it should be in a separate source control repository on the developer's machine only.</p>
15,108
<p>Note: I have extended my question as some of you mentioned that the question is not clear.</p> <p>I am using a RAMPS 1.4 board with an Arduino mega 2560. I need to drive a stepper motor as an extruder using either E0 or E1. I am using Repetier-Firmware and can drive the extruder (stepper motor) using the E0 (RAMPS 1.4). Now for my application, I need to make sure that the extruder is in home position before it starts to drive for the very first time. I am trying to use a switch to connect to the end stop and perform this homing operation. I can do this for X, Y, and Z axes. I was wondering how (h/w connections and firmware modification) can I do it for the extruder?</p>
<p><strong>The edited question</strong> appears to mention that <strong>the actual extruders of the print head need to home / limit themselves</strong>. The answer is that this is not required. When operating direct or Bowden driven extruder setups, you know (or you can measure or find out experimentally) the distance that the filament has to travel from extruder entry to hot end (e.g. to load new filament). If already loaded, because you have printed before, you also know where the filament is (filament could stop after printing, personally I retract the filament en few mm after a print). When a new print starts you usually reverse the retraction at temperature and extrude some extra filament to prime the nozzle to counteract oozed out filament for instance. At that point, the nozzle is primed and the gcode G92 E0 is then used to tell the extruder this is the start at zero length, sort of the home position of the filament. All this is usually done in the start code of your slicer, similar to disabling bed and hot end temperature or final retract is done in the end code of your slicer.</p> <p><strong>This answer below addresses the initial question</strong>, this question was not quite clear. It was <strong>phrased as of the head containing the extruders needed to be homed correctly</strong>. The normal end-stops (can be mechanical or optical switches) already ensure that the printer head (containing the extruder or extruders) is homed correctly (if correctly configured in your printer firmware). The home offsets you define in the firmware define that you start at the origin (0,0,0). </p> <p>Your question does not state what firmware you use, but e.g. in Marlin firmware these settings are found in the <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration.h" rel="nofollow noreferrer">firmware configuration file</a>.</p> <p>In this file the following is defined:</p> <pre><code>// Travel limits (mm) after homing, corresponding to endstop positions. #define X_MIN_POS 0 #define Y_MIN_POS 0 </code></pre> <p>These values must be changed according to the offset between your switch and the origin of the heat bed (e.g. Prusa style printers have the origin at the front left).</p> <p>For my Prusa clone printer I have defined:</p> <pre><code>// Travel limits (mm) after homing, corresponding to endstop positions. #define X_MIN_POS -35 #define Y_MIN_POS -12 </code></pre> <p>What this says is that the homing switch for the X axis is 35 mm left of the origin, etc.</p>
<p>I think the question has already been answered(if at all possible because the question is still not clear exactly what you mean), but let me try putting this a different way.</p> <p>You have to ask yourself what is homing and why are you doing it. The purpose of homing your axes is to set their 0 position in space. This then means that any subsequent movements will be relative to these 0 positions and assuming the motors skip no steps should allow accurate positioning of the head inside the build volume throughout the print. In other words their relative position should match their absolute position. As has already been stated the extruder axis does not work like this.</p> <p>Now I think some of the confusion from your question comes around what you mean by homing the extruder. The extruder position is defined by the previously mentioned X, Y and Z axis. The extruder axis however controls the position of the filament inside the hotend and therefore how much filament is extruded into the build volume. This axis is arbitrarily set to 0 using G92 at the beginning of the print because unlike the spacial axes the absolute position of this axis is not particularly important. Strictly speaking if you were to care about the extruder axis’ absolute position, home would probably be the start of the roll. This however is irrelevant. All that you care about during a print is that the extruder axis remains consistent throughout the print to allow accurate extrusion.</p> <p>So typically at the beginning of a print you will prime the nozzle to ensure plastic is ready to be extruded as ooze from the previous print may create a delay between moving the extruder axis and plastic actually being extruded. Once the nozzle is primed however the axis position will just be set to 0 and then all future positions of that axis will be relative to where it started on the roll.</p> <p>Hopefully that helps but if it doesn’t I think we still need more clarification of what you are actually trying to accomplish.</p>
876
<p>How do you create SQL Server 2005 stored procedure templates in SQL Server 2005 Management Studio?</p>
<p>Another little nugget that I think will help people developing and being more productive in their database development. I am a fan of stored procedures and functions when I develop software solutions. I like my actual CRUD methods to be implemented at the database level. It allows me to balance out my work between the application software (business logic and data access) and the database itself. Not wanting to start a religious war, but I want to allow people to develop stored procedures more quickly and with best practices through templates.</p> <p>Let’s start with making your own templates in the SQL Server 2005 management Studio. First, you need to show the Template Explorer in the Studio.</p> <p><a href="http://www.cloudsocket.com/images/image-thumb10.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb10.png</a></p> <p>This will show the following:</p> <p><a href="http://www.cloudsocket.com/images/image-thumb11.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb11.png</a></p> <p><a href="http://www.cloudsocket.com/images/image-thumb12.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb12.png</a></p> <p><a href="http://www.cloudsocket.com/images/image-thumb13.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb13.png</a></p> <p>The IDE will create a blank template. To edit the template, right click on the template and select Edit. You will get a blank Query window in the IDE. You can now insert your template implementation. I have here the template of the new stored procedure to include a TRY CATCH. I like to include error handling in my stored procedures. With the new TRY CATCH addition to TSQL in SQL Server 2005, we should try to use this powerful exception handling mechanism through our code including database code. Save the template and you are all ready to use your new template for stored procedure creation.</p> <pre><code>-- ====================================================== -- Create basic stored procedure template with TRY CATCH -- ====================================================== SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: &lt;Author,,Name&gt; -- Create date: &lt;Create Date,,&gt; -- Description: &lt;Description,,&gt; -- ============================================= CREATE PROCEDURE &lt;Procedure_Name, sysname, ProcedureName&gt; -- Add the parameters for the stored procedure here &lt;@Param1, sysname, @p1&gt; &lt;Datatype_For_Param1, , int&gt; = &lt;Default_Value_For_Param1, , 0&gt;, &lt;@Param2, sysname, @p2&gt; &lt;Datatype_For_Param2, , int&gt; = &lt;Default_Value_For_Param2, , 0&gt; AS BEGIN TRY BEGIN TRANSACTION -- Start the transaction SELECT @p1, @p2 -- If we reach here, success! COMMIT END TRY BEGIN CATCH -- there was an error IF @@TRANCOUNT &gt; 0 ROLLBACK -- Raise an error with the details of the exception DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY() RAISERROR(@ErrMsg, @ErrSeverity, 1) END CATCH GO </code></pre>
<p>You bring up <em>Template Explorer</em> using Ctrl+Alt+T or trough <em>View > Template Explorer</em>. Then you can right click tree nodes to add new Templates or new folders to organize your new templates.</p>
9,064
<p>What does the <code>explicit</code> keyword mean in C++?</p>
<p>The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a <strong>single parameter</strong> to convert from one type to another in order to get the right type for a parameter.</p> <p>Here's an example class with a constructor that can be used for implicit conversions:</p> <pre><code>class Foo { private: int m_foo; public: // single parameter constructor, can be used as an implicit conversion Foo (int foo) : m_foo (foo) {} int GetFoo () { return m_foo; } }; </code></pre> <p>Here's a simple function that takes a <code>Foo</code> object:</p> <pre><code>void DoBar (Foo foo) { int i = foo.GetFoo (); } </code></pre> <p>and here's where the <code>DoBar</code> function is called:</p> <pre><code>int main () { DoBar (42); } </code></pre> <p>The argument is not a <code>Foo</code> object, but an <code>int</code>. However, there exists a constructor for <code>Foo</code> that takes an <code>int</code> so this constructor can be used to convert the parameter to the correct type.</p> <p>The compiler is allowed to do this once for each parameter.</p> <p>Prefixing the <code>explicit</code> keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call <code>DoBar (42)</code>. It is now necessary to call for conversion explicitly with <code>DoBar (Foo (42))</code></p> <p>The reason you might want to do this is to avoid accidental construction that can hide bugs.<br /> Contrived example:</p> <ul> <li>You have a <code>MyString</code> class with a constructor that constructs a string of the given size. You have a function <code>print(const MyString&amp;)</code> (as well as an overload <code>print (char *string)</code>), and you call <code>print(3)</code> (when you <em>actually</em> intended to call <code>print(&quot;3&quot;)</code>). You expect it to print &quot;3&quot;, but it prints an empty string of length 3 instead.</li> </ul>
<p>Other answers are missing one important factor which I am going to mention here.</p> <p>Along with &quot;delete&quot; keyword, &quot;explicit&quot; allows you to control the way compiler is going to generate special member functions - default constructor, copy constructor, copy-assignment operator, destructor, move constructor and move-assignment.</p> <p>Refer <a href="https://learn.microsoft.com/en-us/cpp/cpp/explicitly-defaulted-and-deleted-functions" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/cpp/cpp/explicitly-defaulted-and-deleted-functions</a></p>
14,735
<p>I've run into a few gotchas when doing C# XML serialization that I thought I'd share:</p> <ul> <li>You can't serialize items that are read-only (like KeyValuePairs)</li> <li>You can't serialize a generic dictionary. Instead, try this wrapper class (from <a href="http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx" rel="noreferrer">http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx</a>):</li> </ul> <hr/> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; [XmlRoot("dictionary")] public class SerializableDictionary&lt;TKey, TValue&gt; : Dictionary&lt;TKey, TValue&gt;, IXmlSerializable { public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); TKey key = (TKey)keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); TValue value = (TValue)valueSerializer.Deserialize(reader); reader.ReadEndElement(); this.Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); foreach (TKey key in this.Keys) { writer.WriteStartElement("item"); writer.WriteStartElement("key"); keySerializer.Serialize(writer, key); writer.WriteEndElement(); writer.WriteStartElement("value"); TValue value = this[key]; valueSerializer.Serialize(writer, value); writer.WriteEndElement(); writer.WriteEndElement(); } } } </code></pre> <p>Any other XML Serialization gotchas out there?</p>
<p>I can't make comments yet, so I will comment on Dr8k's post and make another observation. Private variables that are exposed as public getter/setter properties, and do get serialized/deserialized as such through those properties. We did it at my old job al the time.</p> <p>One thing to note though is that if you have any logic in those properties, the logic is run, so sometimes, the order of serialization actually matters. The members are <em>implicitly</em> ordered by how they are ordered in the code, but there are no guarantees, especially when you are inheriting another object. Explicitly ordering them is a pain in the rear.</p> <p>I've been burnt by this in the past.</p>
<blockquote> <p>Private variables/properties are not serialized in XML serialization, but are in binary serialization.</p> </blockquote> <p>I believe this also gets you if you are exposing the private members through public properties - the private members don't get serialised so the public members are all referencing null values.</p>
9,349
<p>I have a simple unordered list that I want to show and hide on click using the jQuery slideUp and slideDown effect. Everything seems to work fine, however in IE6 the list will slide up, flicker for a split second, and then disappear.</p> <p>Does anyone know of a fix for this?</p> <p>Thanks!</p>
<p>Apologies for the extra comment (I can't upvote or comment on Pavel's answer), but adding a DOCTYPE fixed this issue for me, and the slideUp/Down/Toggle effects now work correctly in IE7.</p> <p>See <a href="http://www.alistapart.com/articles/doctype/" rel="noreferrer">A List Apart</a> for more information on DOCTYPES, or you can try specifying the fairly lenient 4/Transitional:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; </code></pre>
<p>I posted a quick fix solution over at <a href="http://blog.clintonbeattie.com/how-to-solve-the-jquery-flickering-content-problem/" rel="nofollow noreferrer">http://blog.clintonbeattie.com/how-to-solve-the-jquery-flickering-content-problem/</a></p> <p>In short, add overflow:hidden to the containing element that you are sliding in/out. Hope this helps!</p>
13,660
<p>I've noticed that when generating a new C++ project using MS Visual Studio 2008, the <strong>Release</strong> build contains debugging symbols - specifically the following settings are enabled:</p> <ul> <li>The C++/General/Debug Information Format is set to <strong>Program Database</strong>.</li> <li>The Linker/Debugging/Generate Debug Info setting is set to <strong>Yes</strong>.</li> </ul> <p>I have never noticed this on earlier releases of Visual Studio.</p> <p>So, other than generating a larger EXE file, is there any downside to leaving these settings enabled?</p>
<p>We have turned on those settings in our commercial releases for years now with no apparent downside. The upsides are enormous,though. </p> <p>We have integrated a crash dump packager that packages the dump along with some other information and emails it (with the user's consent) to a company inbox. This has helped us find problems that would have taken us <em>forever</em> to reproduce and find otherwise.</p> <p>Although it's slightly off topic, here's a link to an excellent contribution someone made that gives you an easy way to include a crash reporter to a C++/Windows app: <a href="http://www.codeproject.com/KB/debug/crash_report.aspx" rel="noreferrer">http://www.codeproject.com/KB/debug/crash_report.aspx</a></p> <p>Note: It would be wise, though, not to include the PDB file with your release. That said, you must keep the PDB file that matches your released version so that you can correctly debug the problem in the future. If a PDB file is used that wasn't built with the same code that built the exe, the stack you see when you try to debug the dmp will be wrong.</p>
<p>The .exe will be slightly larger due to a reference to the .pdb file (i.e., an extra path). That's about it.</p>
26,849
<p>Ok, this is working on windows. My Java app is running and functioning normally</p> <pre><code>javac -classpath .;ojdbc14.jar -g foo.java java -classpath .;ojdbc14.jar foo </code></pre> <p>However, when I do the same thing on Unix I get this error: ojdbc14.jar: not found</p> <p>What am I doing wrong? I know the ";" is telling my shell that ojdbc14.jar is a new command, but I'm not sure how to fix this.</p>
<p>Use a colon (":") instead of a semicolon (";").</p> <p>See <a href="http://java.sun.com/javase/6/docs/technotes/tools/solaris/classpath.html" rel="nofollow noreferrer">Setting the class path (Solaris and Linux)</a> vs <a href="http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html" rel="nofollow noreferrer">Setting the class path (Windows)</a></p>
<pre><code>javac -classpath '.;ojdbc14.jar' -g foo.java java -classpath '.;ojdbc14.jar' foo </code></pre>
41,695
<p>We have a form that allows a user to dynamically add inputs for fields. For example if you have a form for tracking projects, you want to dynamically add tasks to that project. Just to clarify my language: you dynamically add inputs for the task field. The problem is, we have 50 of those fields. Our current solution presents all 50 fields with a plus (+) next to the field to allow them to add another input box for that field. The labels for the field are to the left of the field and each input box that is added goes below the current input box. </p> <p>Please trust that dynamically adding inputs is the right solution, please trust that it has been thought out, please trust that this is what the users wants, please trust that we have gone down various other roads and this is the best solution. </p> <p>My question is about presentation: How would you do it?</p> <p>Please keep the answers to UI design. We already have the database schema figured out.</p> <hr> <p><strong>Update</strong></p> <p><em>Current Solution is a web based application that uses JavaScript to dynamically add new inputs and looks very similar to Corey Trager's drawing:</em></p> <pre><code>Task [.............] + [.............] + [.............] + [.............] + Foo [.............] + [.............] + [.............] + Repeat 50 times... </code></pre>
<p>Thinking on from what @zachary suggested:</p> <p>Display the form as it was designed to the user with the default/ last saved number of fields. At the bottom of the form place a DropDownButton that has a + icon and the words Add Field (<strong>+ Add Field</strong>). </p> <p>Dropping down this button will show the list of all fields that are available. When the user selects one of these the form will grow (enough to house the new field) the new field with label will be displayed at the bottom of the form and the add field button will show below the new field.</p> <p><hr/> <strong>Edit:</strong></p> <p>To follow on the theme of ASCII diagrams this was is what I think my suggesting would look like.</p> <p>Task&nbsp;[......................]<br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[ + Add Task ▼] </p> <p>Foo&nbsp;&nbsp;[......................]<br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[ + Add Foo &nbsp;▼] </p>
<p>Little + icon somewhere near the last task field with a link that says "Add new task". When clicked, new task field appears below current last task.</p>
18,447
<p>Given the following:</p> <pre><code>#light //any function returning bool * 'a let foo = let x = ref 10 fun () -&gt; x := !x - 1 if !x &lt;&gt; 0 then (true, x) else (false, x) while let (c,x) = foo() in c do print_any x;//can't access x, but would be convinent. //this is how I want it to work, without all the typing let rec loop f = match f() with | (true, x) -&gt; print_any x loop f | (false, _) -&gt; () loop foo </code></pre> <p>How should I go about solving this? Or should I just go through the hassle to convert "foo" to a sequence expression?</p>
<p>I found a library in google code: <a href="http://code.google.com/p/php-email-address-validation/" rel="noreferrer">http://code.google.com/p/php-email-address-validation/</a></p> <p>Are there any others?</p>
<p>I'd recommend to look at the source code of Zend_Validate_EmailAddress [<a href="http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate/EmailAddress.php" rel="nofollow noreferrer">source</a>].</p> <p>Once you have your dependencies fixed, you can simply do the following:</p> <pre><code>$mail_validator = new Zend_Validate_EmailAddress(); $mail_validator-&gt;isValid($address); // returns true or false </code></pre> <p>The best would be to get the full Zend Library into your project via <code>svn external</code> and point the include path to it...</p> <p>But you can just download the necessary files (<a href="http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate/EmailAddress.php" rel="nofollow noreferrer">1</a>,<a href="http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate/Abstract.php" rel="nofollow noreferrer">2</a>,<a href="http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate/Ip.php" rel="nofollow noreferrer">3</a>,<a href="http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate/Interface.php" rel="nofollow noreferrer">4</a>,<a href="http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate/Hostname.php" rel="nofollow noreferrer">5</a>,<a href="http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Loader.php" rel="nofollow noreferrer">6</a>), and include them all (remove the <em>require_once</em> calls).</p>
19,499
<p>I am designing a part with a material which can bear up to a certain stress. </p> <p>To keep the stress within the design limits, I need to ensure a certain surface of solid material per layer, in other words a minimum amount of extruded filament per layer and a smoothly changing infill ratio so that the infill can transmit the load efficiently to the neighbouring layers.</p> <p>The part has an irregular shape and I cannot simply increase the infill ratio for the whole object because the part is big and it would cost more time and filament. I also cannot build straight pillars of solid material inside the part because there are no regions which are suitable for a continuous pillar.</p> <p>How can I calculate and apply a smoothly changing infill ratio or in general how to ensure that each layer is made of at least a certain amount of material?</p> <p>I use Prusa Slicer for slicing and Fusion 360 for the design.</p> <p>Related questions about variable infill, which however don't answer my question because I need to specify the amount of material and because I need a smoothly changing infill ratio:</p> <p><a href="https://3dprinting.stackexchange.com/questions/6522/different-infill-in-the-same-part">Different infill in the same part</a></p> <p><a href="https://3dprinting.stackexchange.com/questions/7025/slic3r-can-i-vary-the-infill-percentage-for-different-heights-of-my-model">slic3r: Can I vary the infill percentage for different heights of my model?</a> </p>
<p>I think you have a major XY problem. The amount of material per layer is not what determines the part strength. Unless additional material is placed in a manner that reinforces against the stress you're designing for, it's just wasted. Moreover, infill in particular is not terribly useful this way, as infill has to rest upon the support of existing infill below it. If you suddenly increase infill density at a particular layer, it will not provide any significant additional strength because the added lines will be unsupported and will not bond strongly to anything. Even the next layer above them, and the next after that for quite a few layers, will not bond well because the unsupported lines can just bend downward when the nozzle goes over them, rather than providing a surface for the newly deposited material to press firmly against and bond to.</p> <p>Generally, infill is not your main source of part strength anyway. I would start out (especially if you can test; if this is a one-off thing, the material cost is not going to be an issue anyway and just go with overkill) by increasing the number of wall lines (wall thickness). Walls generally provide the most strength, and the amount of material used will be proportional to cross-sectional perimeter rather than area, which typically will vary "linearly" rather than "quadratically" (I use these terms loosely since I don't know right off how to make it rigorous - what the independent variable should be thought of as being). My usual default (and I believe Cura's) is 2 walls; I would expect 4-5 to be very strong, and as long as you keep at least 15-20% infill, probably stronger than what you'd get by any increase in infill percent.</p>
<p>Very interesting idea! There may be a way to do this semi-automatically, but I believe it's not yet a part of any slicer.</p> <p>My suggestion would be:</p> <ul> <li>Export file as .stl (Fusion 360)</li> <li>Use a DLP slicer to create images of the layers (CHITUBox)</li> <li>Calculate the area of each of the images (Matlab - I think?)</li> <li>Calculate the required infill percentages for having the same mass on each layer (Excel)</li> <li>Open the model in PrusaSlicer, create a single "height range modifier" (PrusaSlicer)</li> <li>Save the project as .3mf (PrusaSlicer)</li> <li>Extract the .3mf file (7 Zip)</li> <li>Create the neccessary "layer config ranges" texts for PrusaSlicer (Excel)</li> <li>Inject that text into an extrated .3mf file (Notepad++)</li> <li>Pack the .3mf file again (7 Zip)</li> <li>Slice the resulting file (PrusaSlicer)</li> </ul>
1,547
<p>I want to create an allocator which provides memory with the following attributes:</p> <ul> <li>cannot be paged to disk. </li> <li>is incredibly hard to access through an attached debugger</li> </ul> <p>The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual research online and asked a few other people about this, but I cannot find a good place start on this problem.</p> <p><strong>Updates</strong></p> <p><a href="https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#27194">Josh</a> mentions using <code>VirtualAlloc</code> to set protection on the memory space. I have created a custom allocator ( shown below ) I have found the using the <code>VirtualLock</code> function it limits the amount of memory I can allocate. This seems to be by design though. Since I am using it for small objects this is not a problem.</p> <pre><code>// template&lt;class _Ty&gt; class LockedVirtualMemAllocator : public std::allocator&lt;_Ty&gt; { public: template&lt;class _Other&gt; LockedVirtualMemAllocator&lt;_Ty&gt;&amp; operator=(const LockedVirtualMemAllocator&lt;_Other&gt;&amp;) { // assign from a related LockedVirtualMemAllocator (do nothing) return (*this); } template&lt;class Other&gt; struct rebind { typedef LockedVirtualMemAllocator&lt;Other&gt; other; }; pointer allocate( size_type _n ) { SIZE_T allocLen = (_n * sizeof(_Ty)); DWORD allocType = MEM_COMMIT; DWORD allocProtect = PAGE_READWRITE; LPVOID pMem = ::VirtualAlloc( NULL, allocLen, allocType, allocProtect ); if ( pMem != NULL ) { ::VirtualLock( pMem, allocLen ); } return reinterpret_cast&lt;pointer&gt;( pMem ); } pointer allocate( size_type _n, const void* ) { return allocate( _n ); } void deallocate(void* _pPtr, size_type _n ) { if ( _pPtr != NULL ) { SIZE_T allocLen = (_n * sizeof(_Ty)); ::SecureZeroMemory( _pPtr, allocLen ); ::VirtualUnlock( _pPtr, allocLen ); ::VirtualFree( _pPtr, 0, MEM_RELEASE ); } } }; </code></pre> <p>and is used</p> <pre><code> //a memory safe std::string typedef std::basic_string&lt;char, std::char_traits&lt;char&gt;, LockedVirtualMemAllocato&lt;char&gt; &gt; modulestring_t; </code></pre> <p><a href="https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#38708">Ted Percival</a> mentions mlock, but I have no implementation of that yet.</p> <p>I found <a href="http://www.schneier.com/book-practical.html" rel="noreferrer">Practical Cryptography by Neil Furguson and Bruce Schneier</a> quite helpful as well.</p>
<p>You can't really protect against memory access. You can probably prevent paging if you are running as an admin or as the system, but you cannot prevent the admin or system from reading your memory. Even if you could somehow completely block other processes from reading your memory (which you can't), another process could still actually inject a new thread into your process and read the memory that way.</p> <p>Even if you could somehow completely lock down your process and guarantee that the OS would <em>never</em> allow anyone else to access your process, you still don't have full protection. The entire OS could be running in a virtual machine, which could be paused and inspected at any time.</p> <p>You <em>cannot</em> protect memory contents from the owner of the system. Hollywood and the music industry have been aching for this for years. If it were possible, they'd already be doing it.</p>
<p>@Derek: Oh, but with trusted computing, you can use <a href="http://en.wikipedia.org/wiki/Trusted_Computing#Memory_curtaining" rel="nofollow noreferrer">memory curtaining</a>! :-P&lt;/devils-advocate&gt;</p>
2,989
<p>How do you change controls' Z-order in MFC <strong>at design time</strong> - i.e. I can't use SetWindowPos or do this at runtime - I want to see the changed z-order in the designer (even if I have to resort to direct-editing the .rc code).</p> <p>I have an MFC dialog to which I am adding controls. If there is overlap between the edges of the controls, I want to bring one to the front of the other. In Windows Forms or WPF, etc. I can Bring to Front, Send to Back, Bring Forward, Send Back. I don't find these options in MFC, nor can I tell how it determines what is in front, as a control just added is often behind a control that was there previously. How can I manipulate the Z-order in MFC? Even if I have to manipulate the .rc file code directly (i.e. end-run around the designer).</p>
<p>I think the control in front will be the last control that occurs in the rc file. In other words, the dialog editor will draw each control as it is encountered from top to bottom in the rc file, overlapping them when necessary.</p> <p>You can edit the rc file to reorder them, or you can change the tab order in the editor, which does the same thing since tab order is also set based on the order that the controls occur in the file. To my knowledge MFC doesn't offer any other way of layering overlapping controls at design time.</p>
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/a1yzfz6d(VS.80).aspx" rel="nofollow noreferrer">CWnd::SetWindowPos()</a> to control the Z order of your controls, without changing their position in the parent window.</p>
19,363
<p>In a form, I added an overload of ShowDialog(). In Visual Studio, this overload shows up in Intellisense as the third version. How can I make my overloaded function appear as #1 (i.e. the default)?</p>
<p>As far as I know, there is no way to control the order of overloads in the overload selection intellisense tip.</p>
<p>Not unless the number of parameters is less than the current #1 in the list, I believe. Ic ould be wrong, though - I often am. :)</p> <p>I am at a loss as to why you want this, though... </p> <ol> <li>It doesn't matter. and </li> <li>there are better ways to achieve what you are looking for, as answered in other questions..</li> </ol>
35,584
<p>Ok, there are a million regexes out there for validating an email address, but how about some basic email validation that can be integrated into a TSQL query for Sql Server 2005?</p> <p>I don't want to use a CLR procedure or function. Just straight TSQL.</p> <p>Has anybody tackled this already?</p>
<p><em>Very</em> basic would be:</p> <pre><code>SELECT EmailAddress, CASE WHEN EmailAddress LIKE '%_@_%_.__%' AND EmailAddress NOT LIKE '%[any obviously invalid characters]%' THEN 'Could be' ELSE 'Nope' END Validates FROM Table </code></pre> <p>This matches everything with an @ in the middle, preceded by at least one character, followed by at least two, a dot and at least two for the TLD.</p> <p>You can write more <code>LIKE</code> patterns that do more specific things, but you will never be able to match everything that could be an e-mail address while not letting slip through things that are not. Even with regular expressions you have a hard time doing it right. Additionally, even matching according to the very letters of the RFC matches address constructs that will not be accepted/used by most emailing systems.</p> <p>Doing this on the database level is maybe the wrong approach anyway, so a basic sanity check as indicated above may be the best you can get performance-wise, and doing it in an application will provide you with far greater flexibility.</p>
<p>From Tomalak's slelect</p> <pre><code>select 1 where @email not like '%[^a-z,0-9,@,.]%' and @email like '%_@_%_.__%' </code></pre>
28,447
<p><strong>Preface</strong></p> <p>I'm using the newly released Microsoft Virtual Earth SDK v6.2 which has built-in support for pushpin clustering. I realize there are custom ways of doing clustering where my question is easy to answer, but I'd like to leverage the built-in support as much as possible, so this question is specifically related to using the clustering feature of the VE 6.2 SDK.</p> <p><strong>The Problem</strong></p> <p>After enabling the built-in clustering (via VEShapeLayer.SetClusteringConfiguration), the clusters are created as expected, however, they have the default information in them which says something like "X items located here - zoom in to see details". In the app I'm working on, I need to display more information than that - I either need to allow the user to click on the pushpin and VE will automatically zoom in so that the points are now distinct OR display the names of the points in the infobox attached to the cluster pushpin. The catch is that cluster shape that VE creates for me does not appear to be editable until after all of the clustering logic has run...at that point, I don't know what original pushpins belong to that particular cluster. Is there a way to make this happen without resorting to creating a custom clustering implementation?</p>
<p>Just set the "default" value within your constructor.</p> <pre><code>public class Person { public Person() { this.FirstName = string.Empty; } public string FirstName { get; set; } } </code></pre> <p>Also, they're called Automatic Properties.</p>
<p>[DefaultValue("MyFirstName")] public string FirstName { get; set; }</p>
25,314
<p>Can you set the startup Project in the Visual Basic 6 IDE?</p> <p>I looked all through the Settings and can't find a way to do it.</p>
<p>I assume you have multiple projects in a Group e.g. a dll and a dependent exe and you want to set the exe as the 'start up' project. Do so this, select the exe project in the Project Explorer, right click and choose 'Set as Start Up' from the context menu. The 'start up' project's name will be shown as bold text in the Project Explorer.</p>
<p>I'm not aware of a "startup Project" settting in VB6, but you can select the "Startup Object" by opening the Project menu, choosing the last menu item ("X properties", where X is the name of your project), and then selecting the General tab in the Project Properties window. The selector you seek is in the upper-right corner.</p>
46,758
<p>In C, are the shift operators (<code>&lt;&lt;</code>, <code>&gt;&gt;</code>) arithmetic or logical?</p>
<p>According to <a href="https://rads.stackoverflow.com/amzn/click/com/0131103628" rel="noreferrer" rel="nofollow noreferrer">K&amp;R 2nd edition</a> the results are implementation-dependent for right shifts of signed values.</p> <p><a href="http://en.wikipedia.org/wiki/Arithmetic_shift" rel="noreferrer">Wikipedia</a> says that C/C++ 'usually' implements an arithmetic shift on signed values.</p> <p>Basically you need to either test your compiler or not rely on it. My VS2008 help for the current MS C++ compiler says that their compiler does an arithmetic shift.</p>
<p>According to many <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a> compilers:</p> <ol> <li><code>&lt;&lt;</code> is an arithmetic left shift or bitwise left shift.</li> <li><code>&gt;&gt;</code> is an arithmetic right shiftor bitwise right shift.</li> </ol>
2,918
<p>I have some function to find a value:</p> <pre><code>struct FindPredicate { FindPredicate(const SomeType&amp; t) : _t(t) { } bool operator()(SomeType&amp; t) { return t == _t; } private: const SomeType&amp; _t; }; bool ContainsValue(std::vector&lt;SomeType&gt;&amp; v, SomeType&amp; valueToFind) { return find_if(v.begin(), v.end(), FindPredicate(valueToFind)) != v.end(); } </code></pre> <p>Now I would like to write a function that checks if all members of a vector satisfy that predicate:</p> <pre><code>bool AllSatisfy(std::vector&lt;SomeType&gt;&amp; v) { /* ... */ } </code></pre> <p>One solution is to use the <code>std::count_if</code> algorithm.</p> <p>Does anyone know a solution that involves negating the predicate?</p>
<p>The best solution is to use the <a href="http://www.keithschwarz.com/cs106l/fall2007/handouts/200_STL_Functional_Library.pdf" rel="noreferrer">STL functional library</a>. By deriving your predicate from <code>unary_function&lt;SomeType, bool&gt;</code> , you'll then be able to use the <code>not1</code> function, which does precisely what you need (i.e. negating a unary predicate).</p> <p>Here is how you could do that :</p> <pre><code>struct FindPredicate : public unary_function&lt;SomeType, bool&gt; { FindPredicate(const SomeType&amp; t) : _t(t) {} bool operator()(const SomeType&amp; t) const { return t == _t; } private: const SomeType&amp; _t; }; bool AllSatisfy(std::vector&lt;SomeType&gt;&amp; v, SomeType&amp; valueToFind) { return find_if(v.begin(), v.end(), not1(FindPredicate(valueToFind))) == v.end(); } </code></pre> <hr> <p>If you want to roll your own solution (which is, IMHO, not the best option...), well, you could write another predicate that is the negation of the first one :</p> <pre><code>struct NotFindPredicate { NotFindPredicate(const SomeType&amp; t) : _t(t) { } bool operator()(SomeType&amp; t) { return t != _t; } private: const SomeType&amp; _t; }; bool AllSatisfy(std::vector&lt;SomeType&gt;&amp; v) { return find_if(v.begin(), v.end(), NotFindPredicate(valueToFind)) == v.end(); } </code></pre> <p>Or you could do better and write a template functor negator, like :</p> <pre><code>template &lt;class Functor&gt; struct Not { Not(Functor &amp; f) : func(f) {} template &lt;typename ArgType&gt; bool operator()(ArgType &amp; arg) { return ! func(arg); } private: Functor &amp; func; }; </code></pre> <p>that you could use as follow :</p> <pre><code>bool AllSatisfy(std::vector&lt;SomeType&gt;&amp; v, SomeType&amp; valueToFind) { FindPredicate f(valueToFind); return find_if(v.begin(), v.end(), Not&lt;FindPredicate&gt;(f)) == v.end(); } </code></pre> <p>Of course, the latter solution is better because you can reuse the <em>Not</em> struct with every functor you want.</p>
<p>As you are using it, you don't need the FindPredicate functor, since in the example you are only testing equality.</p> <pre><code>bool all_equal(std::vector&lt;SomeType&gt;&amp; v, SomeType&amp; valueToFind) { return v.end() == find_if(v.begin(), v.end(), std::bind1st (equal_to (), valueToFind) ); } bool all_not_equal( std::vector&lt;SomeType&gt;&amp; v, SomeType &amp;valueToFind ) { { return v.end() == find_if(v.begin(), v.end(), std::bind1st (not_equal_to (), valueToFind) ); } </code></pre> <p>And you could just make this a template by itself.</p> <pre><code>template&lt; typename InputIterator , typename Predicate &gt; bool test_all( InputIterator first, InputIterator last, Predicate pred ) { return last == find_if( first, last, pred ); } test_all( v.begin(), v.end(), std::bind1st( not_equals_to_( value )) ); </code></pre>
33,238
<p>Is it possible to use gcov for coverage testing of multi-threaded applications? </p> <p>I've set some trivial tests of our code-base up, but it would be nice to have some idea of the coverage we're achieving. If gcov isn't appropriate can anyone recommend an alternative tool (possible oprofile), ideally with some good documentation on getting started.</p>
<p>We've certainly used gcov to get coverage information on our multi-threaded application.</p> <p>You want to compile with gcc 4.3 which can do coverage on dynamic code.</p> <p>You compile with the <code>-fprofile-arcs -ftest-coverage</code> options, and the code will generate .gcda files which gcov can then process.</p> <p>We do a separate build of our product, and collect coverage on that, running unit tests and regression tests.</p> <p>Finally we use lcov to generate HTML results pages.</p>
<p>I have not used gcov for multi-threaded coverage work. However, on MacOS the Shark tool from Apple handles multiple threads. It's primarily a profiler, but can do coverage info too.</p> <p><a href="http://developer.apple.com/tools/sharkoptimize.html" rel="nofollow noreferrer">http://developer.apple.com/tools/sharkoptimize.html</a></p>
5,859
<p>I had svnserve configured to look at directory "Foo" for the repository it served. Now I changed the configuration from one repository to multiple repositories, all contained in one directory "Bar". I reconfigured svnserve to look at "Bar", but now my client can't find any repositories. What am I doing wrong? Do I need one service for each repository?</p> <p>Thanks, Miel.</p>
<p>Did you configure your client to use svn://svn-server/Foo ? (Assuming Foo and Foo2 are repositories in directory Bar, which you're serving)</p> <p>Since you're serving "Bar" now ("svnserve -r /repositories/Bar" instead of "svnserve -r /repositories/Bar/Foo") you should make a change on your client-side repository URL.</p> <p>Another solution would be to fire up multiple SVN servers with different ports using the --listen-port parameter. That would also change your URL.</p> <p>Yet another alternative is just adding new projects to your single existing repository; note that you'll have a single repository configuration this way -- and that means a single set of users, simpler access control, etc.</p>
<p>This <a href="http://svnbook.red-bean.com/en/1.0/ch06s03.html" rel="nofollow noreferrer">documentation</a> about svnserve may also come in handy for ya.</p>
30,183
<p>How would one create a Singleton class using PHP5 classes?</p>
<pre><code>/** * Singleton class * */ final class UserFactory { private static $inst = null; // Prevent cloning and de-serializing private function __clone(){} private function __wakeup(){} /** * Call this method to get singleton * * @return UserFactory */ public static function Instance() { if ($inst === null) { $inst = new UserFactory(); } return $inst; } /** * Private ctor so nobody else can instantiate it * */ private function __construct() { } } </code></pre> <p>To use:</p> <pre><code>$fact = UserFactory::Instance(); $fact2 = UserFactory::Instance(); </code></pre> <p><code>$fact == $fact2;</code></p> <p>But:</p> <pre><code>$fact = new UserFactory() </code></pre> <p>Throws an error.</p> <p>See <a href="http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static" rel="nofollow noreferrer" title="PHP: Variable Scope : Using Static Variables">http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static</a> to understand static variable scopes and why setting <code>static $inst = null;</code> works.</p>
<p>Here's my example that provides ability to call as $var = new Singleton() and also creating 3 variables to test if it creates new object: </p> <pre><code>class Singleton{ private static $data; function __construct(){ if ($this::$data == null){ $this-&gt;makeSingleton(); } echo "&lt;br/&gt;".$this::$data; } private function makeSingleton(){ $this::$data = rand(0, 100); } public function change($new_val){ $this::$data = $new_val; } public function printme(){ echo "&lt;br/&gt;".$this::$data; } } $a = new Singleton(); $b = new Singleton(); $c = new Singleton(); $a-&gt;change(-2); $a-&gt;printme(); $b-&gt;printme(); $d = new Singleton(); $d-&gt;printme(); </code></pre>
24,877
<p>I've been working with ASP.NET MVC for the last few weeks, learning as I go, from tutorials and mostly trial and error. </p> <p>I'm sorta groping in the dark, since I have no other experience with MVC frameworks and I'm just moving ahead blindly trying to figure things out as I move along. </p> <p>So, I'm looking for better, more organized source to learn the platform and its features, and in general, the MVC structure and how the framework implements it, but no books on the subject have been released yet, and are all due in a few months at best. </p> <p>Does anyone know of any good, thorough resources from which I can expand my knowledge about the ASP.NET MVC framework?</p>
<p>Rob Conery has his <a href="http://blog.wekeroad.com/mvc-storefront/" rel="noreferrer">ASP.NET MVC Storefront</a> series, which is what I used to get my feet wet. It is around twenty-something parts long already.</p> <p>He takes you threw the entire conceptual design and execution of an application, which is an incredible way to learn how something applies to the real world.</p>
<p>I bet that you can't find any better book than "Pro ASP NET MVC Framework" by Steven Sanderson. I read many books but never read such good book.</p>
44,285
<p>I'm relatively familiar with the concepts of DI/IOC containers having worked on projects previously where their use were already in place. However, for this new project, there is no existing framework and I'm having to pick one.</p> <p>Long story short, there are some scenarios where we'll be configuring several implementations for a given interface. Glancing around the web, it seems like using any of the mainstream frameworks to selectively bind to one of the implementations is quite simple.</p> <p>There are however contexts where we'll need to run <em>ALL</em> the configured implementations. I've scoured all the IOC tagged posts here and I'm trying to pour through documentation of the major frameworks (so far looking at Unity, Ninject, and Windsor), but docs are often sparse and I've not the time to inspect source for all the packages.</p> <p>So, are there any mainstream IOC containers that will allow me to bind to all the configured concrete types for one of my services?</p>
<p>One thing that caught me the first time I was trying to resolve all implementations of a registered type was that un-named (default) type registrations will <em>not</em> be returned when you call ResolveAll(). Only named instances are returned.</p> <p>So:</p> <pre><code>IUnityContainer container = new UnityContainer(); container.RegisterType&lt;IMyInterface, MyFirstClass&gt;(); container.RegisterType&lt;IMyInterface, MySecondClass&gt;("Two"); container.RegisterType&lt;IMyInterface, MyThirdClass&gt;("Three"); var instances = container.ResolveAll&lt;IMyInterface&gt;(); Assert.AreEqual(2, instances.Count, "MyFirstClass doesn't get constructed"); </code></pre>
<p>So I somehow missed this my first pass looking through Unity somehow...but I'll answer my own question.</p> <p>Unity has precisely what I wanted. <a href="http://msdn.microsoft.com/en-us/library/cc440943.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cc440943.aspx</a></p> <p>Also, for anyone else doing the IOC hunt and dance like me, this link proved to be invaluable. <a href="http://blog.ashmind.com/index.php/2008/09/08/comparing-net-di-ioc-frameworks-part-2/" rel="nofollow noreferrer">http://blog.ashmind.com/index.php/2008/09/08/comparing-net-di-ioc-frameworks-part-2/</a></p>
40,796
<p>In <a href="https://web.archive.org/web/20141127115939/https://blogs.msmvps.com/kathleen/2008/09/05/in-praise-of-nested-classes/" rel="noreferrer">Kathleen Dollard's 2008 blog post</a>, she presents an interesting reason to use nested classes in .net. However, she also mentions that FxCop doesn't like nested classes. I'm assuming that the people writing FxCop rules aren't stupid, so there must be reasoning behind that position, but I haven't been able to find it.</p>
<p>Use a nested class when the class you are nesting is only useful to the enclosing class. For instance, nested classes allow you to write something like (simplified):</p> <pre><code>public class SortedMap { private class TreeNode { TreeNode left; TreeNode right; } } </code></pre> <p>You can make a complete definition of your class in one place, you don't have to jump through any PIMPL hoops to define how your class works, and the outside world doesn't need to see anything of your implementation.</p> <p>If the TreeNode class was external, you would either have to make all the fields <code>public</code> or make a bunch of <code>get/set</code> methods to use it. The outside world would have another class polluting their intellisense.</p>
<p>As <a href="https://stackoverflow.com/a/16093091/199154">nawfal</a> mentioned implementation of Abstract Factory pattern, that code can be axtended to achieve <a href="https://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaEncyclopedia/ClassClusters/ClassClusters.html" rel="nofollow noreferrer">Class Clusters pattern</a> which is based on Abstract Factory pattern.</p>
7,128
<p>Is there a standard idiom for comparing version numbers? I can't just use a straight String compareTo because I don't know yet what the maximum number of point releases there will be. I need to compare the versions and have the following hold true:</p> <pre><code>1.0 &lt; 1.1 1.0.1 &lt; 1.1 1.9 &lt; 1.10 </code></pre>
<p>Another solution for this old post (for those that it might help) :</p> <pre><code>public class Version implements Comparable&lt;Version&gt; { private String version; public final String get() { return this.version; } public Version(String version) { if(version == null) throw new IllegalArgumentException("Version can not be null"); if(!version.matches("[0-9]+(\\.[0-9]+)*")) throw new IllegalArgumentException("Invalid version format"); this.version = version; } @Override public int compareTo(Version that) { if(that == null) return 1; String[] thisParts = this.get().split("\\."); String[] thatParts = that.get().split("\\."); int length = Math.max(thisParts.length, thatParts.length); for(int i = 0; i &lt; length; i++) { int thisPart = i &lt; thisParts.length ? Integer.parseInt(thisParts[i]) : 0; int thatPart = i &lt; thatParts.length ? Integer.parseInt(thatParts[i]) : 0; if(thisPart &lt; thatPart) return -1; if(thisPart &gt; thatPart) return 1; } return 0; } @Override public boolean equals(Object that) { if(this == that) return true; if(that == null) return false; if(this.getClass() != that.getClass()) return false; return this.compareTo((Version) that) == 0; } } </code></pre> <hr> <pre><code>Version a = new Version("1.1"); Version b = new Version("1.1.1"); a.compareTo(b) // return -1 (a&lt;b) a.equals(b) // return false Version a = new Version("2.0"); Version b = new Version("1.9.9"); a.compareTo(b) // return 1 (a&gt;b) a.equals(b) // return false Version a = new Version("1.0"); Version b = new Version("1"); a.compareTo(b) // return 0 (a=b) a.equals(b) // return true Version a = new Version("1"); Version b = null; a.compareTo(b) // return 1 (a&gt;b) a.equals(b) // return false List&lt;Version&gt; versions = new ArrayList&lt;Version&gt;(); versions.add(new Version("2")); versions.add(new Version("1.0.5")); versions.add(new Version("1.01.0")); versions.add(new Version("1.00.1")); Collections.min(versions).get() // return min version Collections.max(versions).get() // return max version // WARNING Version a = new Version("2.06"); Version b = new Version("2.060"); a.equals(b) // return false </code></pre> <hr> <p>Edit:</p> <p>@daiscog: Thank you for your remark, this piece of code has been developed for the Android platform and as recommended by Google, the method "matches" check the entire string unlike Java that uses a regulatory pattern. (<a href="http://developer.android.com/reference/java/lang/String.html#matches%28java.lang.String%29">Android documentation</a> - <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#matches%28java.lang.String%29">JAVA documentation</a>)</p>
<pre><code>public class VersionComparator { /* loop through both version strings * then loop through the inner string to computer the val of the int * for each integer read, do num*10+&lt;integer read&gt; * and stop when stumbling upon '.' * When '.' is encountered... * see if '.' is encountered for both strings * if it is then compare num1 and num2 * if num1 == num2... iterate over p1++, p2++ * else return (num1 &gt; num2) ? 1 : -1 * If both the string end then compare(num1, num2) return 0, 1, -1 * else loop through the longer string and * verify if it only has trailing zeros * If it only has trailing zeros then return 0 * else it is greater than the other string */ public static int compareVersions(String v1, String v2) { int num1 = 0; int num2 = 0; int p1 = 0; int p2 = 0; while (p1 &lt; v1.length() &amp;&amp; p2 &lt; v2.length()) { num1 = Integer.parseInt(v1.charAt(p1) + ""); num2 = Integer.parseInt(v2.charAt(p2) + ""); p1++; p2++; while (p1 &lt; v1.length() &amp;&amp; p2 &lt; v2.length() &amp;&amp; v1.charAt(p1) != '.' &amp;&amp; v2.charAt(p2) != '.') { if (p1 &lt; v1.length()) num1 = num1 * 10 + Integer.parseInt(v1.charAt(p1) + ""); if (p2 &lt; v2.length()) num2 = num2 * 10 + Integer.parseInt(v2.charAt(p2) + ""); p1++; p2++; } if (p1 &lt; v1.length() &amp;&amp; p2 &lt; v2.length() &amp;&amp; v1.charAt(p1) == '.' &amp;&amp; v2.charAt(p2) == '.') { if ((num1 ^ num2) == 0) { p1++; p2++; } else return (num1 &gt; num2) ? 1 : -1; } else if (p1 &lt; v1.length() &amp;&amp; p2 &lt; v2.length() &amp;&amp; v1.charAt(p1) == '.') return -1; else if (p1 &lt; v1.length() &amp;&amp; p2 &lt; v2.length() &amp;&amp; v2.charAt(p2) == '.') return 1; } if (p1 == v1.length() &amp;&amp; p2 == v2.length()) { if ((num1 ^ num2) == 0) return 0; else return (num1 &gt; num2) ? 1 : -1; } else if (p1 == v1.length()) { if ((num1 ^ num2) == 0) { while (p2 &lt; v2.length()) { if (v2.charAt(p2) != '.' &amp;&amp; v2.charAt(p2) != '0') return -1; p2++; } return 0; } else return (num1 &gt; num2) ? 1 : -1; } else { if ((num1 ^ num2) == 0) { while (p1 &lt; v1.length()) { if (v1.charAt(p1) != '.' &amp;&amp; v1.charAt(p1) != '0') return 1; p1++; } return 0; } else return (num1 &gt; num2) ? 1 : -1; } } public static void main(String[] args) { System.out.println(compareVersions("11.23", "11.21.1.0.0.1.0") ^ 1); System.out.println(compareVersions("11.21.1.0.0.1.0", "11.23") ^ -1); System.out.println(compareVersions("11.23", "11.23.0.0.0.1.0") ^ -1); System.out.println(compareVersions("11.2", "11.23") ^ -1); System.out.println(compareVersions("11.23", "11.21.1.0.0.1.0") ^ 1); System.out.println(compareVersions("1.21.1.0.0.1.0", "2.23") ^ -1); System.out.println(compareVersions("11.23", "11.21.1.0.0.1.0") ^ 1); System.out.println(compareVersions("11.23.0.0.0.0.0", "11.23") ^ 0); System.out.println(compareVersions("11.23", "11.21.1.0.0.1.0") ^ 1); System.out.println(compareVersions("1.5.1.3", "1.5.1.3.0") ^ 0); System.out.println(compareVersions("1.5.1.4", "1.5.1.3.0") ^ 1); System.out.println(compareVersions("1.2.1.3", "1.5.1.3.0") ^ -1); System.out.println(compareVersions("1.2.1.3", "1.22.1.3.0") ^ -1); System.out.println(compareVersions("1.222.1.3", "1.22.1.3.0") ^ 1); } } </code></pre>
24,170
<p>What is a generic list manipulation function in C? (I saw this when I was going through some materials.)</p> <p>What is the difference between this function and a function which can accept elements of any kind?</p> <p>Are they same...? How can we implement them individually if they are not same?</p>
<p>A generic list is likely to be singly-linked, and probably assumes that the items in the list have a structure like this:</p> <pre><code>typedef struct list_item list_item; struct list_item { list_item *next; ...data for node... }; </code></pre> <p>Using this layout, you can write functions to manipulate lists using just the next pointers.</p> <p>Sometimes, the '<code>...data for node...</code>' will be a simple '<code>void *</code>'; that is, the list items will contain pointers to the next node in the list (or NULL if there is no next node) and pointers to the data.</p> <pre><code>typedef struct list list; struct list { list *next; void *data; }; </code></pre> <p>Since you can cast any pointer to '<code>void *</code>', you can have any mix of data types in the list - but your code must know how to handle them.</p> <p>You ask about 'a' generic list function, but there probably isn't a single one-function-does-all design, and certainly not a simple one. There are a number of possible sets of functions that could make generic list functions. One set, inspired by Lisp, would consist of:</p> <pre><code>void *car(list *lp); // Return the data for the first item on the list list *cdr(list *lp); // Return the tail of the list list *cons(list *lp1, list *lp2); // Construct a list from lists lp1 and lp2 list *cond(list *lp, void *data); // Append data item to list </code></pre> <p>You probably want to provide the ability to test whether the list is empty, and a few other items.</p> <p>One good exposition, admittedly in C++, is found in Koenig's "<a href="https://rads.stackoverflow.com/amzn/click/com/0201423391" rel="nofollow noreferrer" rel="nofollow noreferrer">Ruminations on C++</a>". The ideas can be adapted into C quite easily - it isn't dreadfully hard (though the storage management in C is harder than in C++).</p>
<p>As mentioned above, I tried using MACROS approach to create the list manipulation functions. Its easy to create the INSERT operation routine but difficult to create Delete and traverse operations. Following it the list structure and the INSERT routine signature:</p> <pre><code>#define LIST_DEFINE(type) \ struct list_node_##type \ { \ type *data; \` struct list_node_##type *next; \ }; LIST_INSERT(&amp;ListHead,&amp;Data, DataType); </code></pre> <p>Where:<br> <code>ListHead</code> - Head of the linked list<br> <code>Data</code> - The Data for which a new node will be created and data is inserted in the node <code>DataType</code> - Is the data-type of the data passed</p> <p>FYI, I am allocating memory in the function and copying all the data passed in the newly created node and them append the node in linked list.</p> <p>Now, when a <code>LIST_DELETE</code> routine is created, the node needs to be deleted will be identified using a unique identifier within the data. That identifier is also passed in the <code>MACRO</code> routine as key that will be replaced in the <code>MACRO</code> expansion. The routine signature could be:</p> <pre><code>LIST_DELETE(&amp;ListHead, DataType, myvar-&gt;data-&gt;str, char*); </code></pre> <p>Where:<br> <code>ListHead</code> - Head of the linked list<br> <code>DataType</code> - Is the data-type of the data<br> <code>myvar-&gt;data-&gt;str</code> - Unique key<br> <code>char*</code> - Key type</p> <p>Now, when the key is expanded, that same key cannot be used for comparison as if we write</p> <pre><code>if((keytype)ListHead-&gt;data-&gt;key == (keytype)key) </code></pre> <p>It expands to </p> <pre><code>ListHead-&gt;data-&gt;myvar-&gt;data-&gt;str == myvar-&gt;data-&gt;str </code></pre> <p>And here there is no variable like: <code>ListHead-&gt;data-&gt;myvar-&gt;data-&gt;str</code></p> <p>So, this approach cannot work to write delete routines and as the traversal and search routines also use unique key, same problem will be faced in them as well.</p> <p>And, on an unrelated note, how to determine the matching logic for unique key, as the unique key could be anything.</p>
42,261
<p>I'm in the process of making my PHP site Unicode-aware. I'm wondering if anyone has experience with the <code>mbstring.func_overload</code> setting, which replaces the normal string functions (e.g. <code>strlen</code>) with their multi-byte equivalents (<code>mb_strlen</code>). There aren't any comments on the PHP manual page.</p> <p>Are there any potential problems that I should be aware of? Any cases where calling the multi-byte version is a bad idea?</p> <p>I suppose one example would be functions that deal with encryption, since they may expect to deal with strings of bytes, rather than strings of characters.</p> <p>Also, the manual page includes a note: "It is not recommended to use the function overloading option in the per-directory context, because it's not confirmed yet to be stable enough in a production environment and may lead to undefined behaviour."</p> <p>Does that mean that it's not stable in a per-directory context, or it's generally not stable? The wording is unclear.</p>
<p>one issue you should definitely watch for is 3rd party scripts (perhaps a library or pear extension) which uses non mb-aware versions of functions. for example, libraries that use <code>strlen()</code> could cause issues if you overload it.</p> <p>as well, this <a href="http://bugs.php.net/bug.php?id=27421" rel="nofollow noreferrer">bug report</a> shows that the virtual host bleeding of mb_overloaded functions have been corrected in 5.2/5.3 CVS versions. the bug is specific to per-directory configurations.</p>
<p>one issue you should definitely watch for is 3rd party scripts (perhaps a library or pear extension) which uses non mb-aware versions of functions. for example, libraries that use <code>strlen()</code> could cause issues if you overload it.</p> <p>as well, this <a href="http://bugs.php.net/bug.php?id=27421" rel="nofollow noreferrer">bug report</a> shows that the virtual host bleeding of mb_overloaded functions have been corrected in 5.2/5.3 CVS versions. the bug is specific to per-directory configurations.</p>
27,470
<p>I want to implement a simple 2 part FormWizard. Form 1 will by dynamically generated something like this:</p> <pre><code>class BuyAppleForm(forms.Form): creditcard = forms.ChoiceField(widget = forms.RadioSelect) type = forms.ChoiceField(widget = forms.RadioSelect) def __init__(self,*args, **kwargs): user = kwargs['user'] del kwargs['user'] super(BuyAppleForm, self).__init__(*args, **kwargs) credit_cards = get_credit_cards(user) self.fields['creditcard'].choices = [(card.id,str(card)) for card in credit_cards] apple_types= get_types_packages() self.fields['type'].choices = [(type.id,str(type)) for type in apple_types] </code></pre> <p>This will dynamically create a form with lists of available choices.</p> <p>My second form, I actually want no input. I just want to display a confirmation screen containing the credit card info, apple info, and money amounts (total, tax, shipping). Once user clicks OK, I want the apple purchase to commence.</p> <p>I was able to implement the single form way by passing in the request.user object in the kwargs. However, with the FormWizard, I cannot figure this out.</p> <p>Am I approaching the problem wrong and is the FormWizard not the proper way to do this? If it is, how can the Form <code>__init__</code> method access the user object from the HTTP request? </p>
<p>I haven't used it, but for the situation you describe, it seems like you may want to try the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/formtools/form-preview/#ref-contrib-formtools-form-preview" rel="nofollow noreferrer">FormPreview</a> instead of the FormWizard. From the documentation it sounds like what you're after.</p>
<p>Thank you krys for answering to your own question. Helped me, but I still got some remarks.</p> <p>FormPreview is not the way to go since it as far as I know does not support dynamic forms. It relies on a fixed form class to generate the from from there. But we are generating dynamically here with a function. Maybe FormPreview will support this one day (or already does and I dont know how).</p> <p>Krys solution seems to do the same as FormPreview. Only the hash is left out, so user may change data in the hidden fields or do you check it again?. If you check it again, that would not be following DRY because you duplicate the check (okay, could be in a reusable method, so only tiny repetition).</p> <p>What I was wondering, how do you adjust the widget? Do you duplicate the form with the new widgets or is there a way to change that dynamically?</p>
46,742
<p>I'm trying to grok the purpose of .NET's SecureString. From MSDN:</p> <blockquote> <p>An instance of the System.String class is both immutable and, when no longer needed, cannot be programmatically scheduled for garbage collection; that is, the instance is read-only after it is created and it is not possible to predict when the instance will be deleted from computer memory. Consequently, if a String object contains sensitive information such as a password, credit card number, or personal data, there is a risk the information could be revealed after it is used because your application cannot delete the data from computer memory.</p> <p>A SecureString object is similar to a String object in that it has a text value. However, the value of a SecureString object is automatically encrypted, can be modified until your application marks it as read-only, and can be deleted from computer memory by either your application or the .NET Framework garbage collector.</p> <p>The value of an instance of SecureString is automatically encrypted when the instance is initialized or when the value is modified. Your application can render the instance immutable and prevent further modification by invoking the MakeReadOnly method.</p> </blockquote> <p>Is the automatic encryption the big payoff?</p> <p>And why can't I just say:</p> <pre><code>SecureString password = new SecureString(&quot;password&quot;); </code></pre> <p>instead of</p> <pre><code>SecureString pass = new SecureString(); foreach (char c in &quot;password&quot;.ToCharArray()) pass.AppendChar(c); </code></pre> <p>What aspect of SecureString am I missing?</p>
<p>Some parts of the framework that currently use <a href="https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring" rel="noreferrer"><code>SecureString</code></a>:</p> <ul> <li>WPF's <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.passwordbox" rel="noreferrer"><code>System.Windows.Controls.PasswordBox</code></a> control keeps the password as a SecureString internally (exposed as a copy through <code>PasswordBox::SecurePassword</code>)</li> <li>The <a href="https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.password" rel="noreferrer"><code>System.Diagnostics.ProcessStartInfo::Password</code></a> property is a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring" rel="noreferrer"><code>SecureString</code></a></li> <li>The constructor for <a href="https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2" rel="noreferrer"><code>X509Certificate2</code></a> takes a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring" rel="noreferrer"><code>SecureString</code></a> for the password</li> </ul> <p>The main purpose is to reduce the attack surface, rather than eliminate it. <a href="https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring" rel="noreferrer"><code>SecureStrings</code></a> are "pinned" in RAM so the Garbage Collector won't move it around or make copies of it. It also makes sure the plain text won't get written to the Swap file or in core dumps. The encryption is more like obfuscation and won't stop a determined hacker, though, who would be able to find the <a href="https://en.wikipedia.org/wiki/Symmetric-key_algorithm" rel="noreferrer">symmetric key</a> used to encrypt and decrypt it.</p> <p>As others have said, the reason you have to create a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring" rel="noreferrer"><code>SecureString</code></a> character-by-character is because of the first obvious flaw of doing otherwise: you presumably have the secret value as a plain string already, so what's the point? </p> <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring" rel="noreferrer"><code>SecureString</code></a>s are the first step in solving a Chicken-and-Egg problem, so even though most current scenarios require converting them back into regular strings to make any use of them at all, their existence in the framework now means better support for them in the future - at least to a point where your program doesn't have to be the weak link.</p>
<p>Another use case is when you are working with payment applications (POS) and you simply <em>can't use immutable data structures</em> in order to store sensitive data because you are careful developer. For instance: if I will store sensitive card data or authorisation metadata into immutable string there always would be the case when this data will be available in memory for significant amount of time after it was discarded. I cannot simply overwrite it. Another huge advantage where such sensitive data being kept in memory encrypted.</p>
17,054
<p>I recently upgraded to <a href="https://www.creality3donline.com/creality-polypropylene-build-plate-for-ender-3-ender-5-cr20_p0124.html" rel="nofollow noreferrer">a Polypropylene</a> print bed, but I haven't actually been able to complete a print. </p> <p>Adhesion seems incredibly inconsistent, even on the same spot. Sometimes it goes down great, and sometimes it just curls up and clumps on the nozzle. I even cranked the temp up to 220&nbsp;&deg;C for the PLA and 70&nbsp;&deg;C for the bed in an effort to get it to stick for an initial layer, and it still isn't sticking. </p> <p>Any tips? I've been cleaning with rubbing alcohol, but I don't know if there's any trick. Clean when hot? Cold? Let sit after cleaning before using? Is it just a matter of incredibly precise bed leveling?</p>
<p>When you updated the print bed, you may have affected either the manual or auto calibration of the bed height and bed leveling.</p> <p>First layer adhesion is depends critically on an accurate first layer thickness, which depends on the bed height calibration. Adding or, perhaps more critically, removing any bed surface thickness could cause a problem.</p> <p>With many forms of auto bed calibration, a sensor detects a steel or metallic reference under the surface. The thickness from that reference to the surface of the bed is not automatically detected or compensated. Changing the bed surface, even renewing the surface with another sheet of the same material, may alter the bed thickness enough to affect the adhesion fo the first layer.</p> <p>If the bed is properly adjusted, the problem may be the surface of the polypropylene. I see that some instructions for cleaning polypropylene build surfaces suggest isopropyl alcohol and/or a mild soap solution. I find that with a PEI build plate, it is sometimes necessary to clean the surface with acetone.</p> <p>Acetone is superior at removing oils and films from the surface and will do better than multiple isopropanol cleanings. I checked a table of chemical compatibility, and polypropylene is highly compatible with acetone, so a thorough cleaning will not degrade it.</p>
<p>If you are using PLA, 200 for the extruder sticks the best for me. The other issue with adhesion is the greater the difference between the extruder temperature and the bed the poorer adhesion. There are other things can help with this. Using a higher bed temperature for the first layer can help. A slower extrusion speed allows the extrusion to cool more before getting as long of a length to for the contraction force; thus improving adhesion. </p>
1,285
<p>I have an application with 5 <code>UIViewController</code>s each inside a corresponding <code>UINavigationController</code>, all tucked inside a <code>UITabBarController</code> that displays 5 tabs at the bottom of the screen.</p> <p>I want to display another <code>UIViewController</code> (inside a <code>UINavigationController</code>) when a dialog button is pressed.</p> <p>This view should only be loaded and unloaded programatically; i.e. it should not appear in the tab bar. However, I want the tab bar to be visible always.</p> <p>If I add the <code>[UINavigationController view]</code> to <code>[self window]</code> the <code>UITabBar</code> is covered. If I add it to any other layer, the <code>UINavigationController</code> adds on the compensation it has for the status bar so appears further down than expected.</p> <p>A solution would be to have the 6th <code>UINavigationController</code> added to the <code>UITabBar</code> with the others, but with its <code>tabBarItem</code> hidden. Then I can show it and hide it using the <code>tabBar</code>s <code>selectedIndex</code> property.</p> <p>Accessing the <code>tabBarItem</code> through the <code>UIViewController</code> shows no obvious way of doing this.</p> <hr> <p>@wisequark, I think you completely misunderstood and you have almost rewritten the architecture of my application. However I have a separate navigation controller for each view as they are mutually exclusive and there is no concept of "drilling down".</p> <p>@Kendall, This is what I expect I will have to do - have the modal view appear with a hide button to bring back the normal interface. But it would be nice to keep the tab bar always visible, so I was just wondering if anyone knew of a way.</p>
<p>It sounds as though you have a mess on your hands. A <code>UINavigationController</code> is a distinct object that is very different from a <code>UITabBarController</code>. In general, your application should have a tab controller, one of who's tab's loads a <code>UINavigationController</code> which in turn loads it's views - not that both maintain management over the different views. It is also improper to refer to the display of a <code>UIViewController</code> as such an object doesn't have a visual representation. In the case of a <code>UINavigationController</code>, the navigation controller object is responsible for displaying a navigation bar and a table view (in the most common case) and for managing the display of all the views in the navigation hierarchy. It itself has no corresponding representation on screen. Similarly, a <code>UITabBarController</code> presents a tab bar and is responsible for the loading and unloading of the views and/or view controllers attached to the tab buttons. If we were to present this as an image, it would look something like this - <a href="http://img.skitch.com/20081112-2sqp7q4wafa34te1ga337u4k8.png">alt text http://img.skitch.com/20081112-2sqp7q4wafa34te1ga337u4k8.png</a></p>
<p>The best idea I could think of would be to either push a modal navigation controller for your view (which would hide the tab bar which you do not want), or to get the tab bar controller current selected view controller (really your navigation controller for a tab) and push your new view controller on there - and then pop that view when another tab is selected with a tab bar delegate.</p> <p>It seems wierd to me to push the view onto random tabs though, if the view is created from a dialog that is modal, I don't see why the view itself should not also be modal and hide tabs.</p>
36,068
<p>What is the best way to secure an intranet website developed using <code>PHP</code> from outside attacks?</p>
<p>That's a stunningly thought-provoking question, and I'm surprised that you haven't received better answers. </p> <h2>Summary</h2> <p>Everything you would do for an external-facing application, and then some. </p> <h2>Thought Process</h2> <p>If I'm understanding you correctly, then you are asking a question which <em>very</em> few developers are asking themselves. Most companies have poor defence in depth, and once an attacker is in, he's in. Clearly you want to take it up a level. </p> <p>So, what kind of attack are we thinking about?<br> If I'm the attacker and I'm attacking your intranet application, then I must have got access to your network somehow. This may not be as difficult as it sounds - I might try spearphishing (targetting email to individuals in your organisation, containing either malware attachements or links to sites which install malware) to get a trojan installed on an internal machine. </p> <p>Once I've done this (and got control of an internal PC), I'll try all the same attacks I would try against any internet application. </p> <p>However, that's not the end of the story. I've got more options: if I've got one of your user's PCs, then I might well be able to use a keylogger to gather usernames and passwords, as well as watching all your email for names and phone numbers.<br> Armed with these, I may be able to log into your application directly. I may even learn an admin username/password. Even if I don't, a list of names and phone numbers along with a feel for company lingo gives me a decent shot at socially engineering my way into wider access within your company. </p> <h2>Recommendations</h2> <ul> <li>First and foremost, before all technical solutions: <strong>TRAIN YOUR USERS IN SECURITY</strong></li> </ul> <p>The common answers to securing a web app: </p> <ul> <li>Use multi-factor authentication <ul> <li>e.g. username/password and some kind of pseudo-random number gadget. </li> </ul></li> <li>Sanitise all your input. <ul> <li>to protect against cross-site scripting and SQL injection. </li> </ul></li> <li>Use SSL (otherwise known as HTTPS). <ul> <li>this is a pain to set up (EDIT: actually that's improving), but it makes for much better security. </li> </ul></li> <li>Adhere to the principals of "Segregation of Duties" and "Least Priviledge" <ul> <li>In other words, by ensuring that all users have only the permissions they need to do their jobs (and nobody else's jobs) you make sure they have the absolute minimum ability to do damage.</li> </ul></li> </ul>
<p>You could only allow access from internal IPs from the php app itself. Also dont ignore the usual security and best practices. Input validation and output encoding(whitelisting only), user accounts with hashed passwords etc.</p>
16,022
<p>As I said in the title there is some issue with my z axis steppers. They will make a humming sound and vibrate a little but won't actually spin. I'm fairly sure this is an issue with the firmware (but I might be totally wrong) since they turn when the wires are switched with the ones for the Y axis and swapping the driver board for a spare had no impact on them. Any help would be appreciated. I am using RAMPs 1.4 and marlin firmware.</p>
<p>Try connecting Y-motor to your Z ports. If Y-motor will behave like Z-motors, then there's problem with your Z ports, be it hardware or software. I'm not a RAMPS user, but have heard that there is voltage regulator for every motor port. Sounds like your motors may be underpowered.</p>
<p>Hello it's seems to be the voltage regutaltor on the steppers drivers for the nema motors. Check to adjust the voltage with a multimeter connecting the red pin from the multimeter on the voltage regulator on the driver and the black pin on the GND pin on the ramps 12v connector.</p> <p>Also make sure that you have connected the jumpers to setup the microstep resolution: </p> <p>Full step,Half step,Quarter step,Eighth step,Sixteenth step</p> <p>Best regards.</p> <p>Rodrigo</p>
748
<p>I would like to use the ispell-buffer command in Emacs. It uses the English language by default. Is there an easy way to switch to another dictionary (for example, another language)?</p>
<p>The following command proposes a list of installed dictionaries to use:</p> <pre><code>M-x ispell-change-dictionary </code></pre> <p>Usually, <code>M-x isp-c-d</code> expands to the above also.</p>
<p>Here is some code to remap the C-\ key to automatically toggle between multiple languages <em>and</em> to change the input method to the corresponding language. (derived from this post: <a href="https://stackoverflow.com/a/45891514/17936582">https://stackoverflow.com/a/45891514/17936582</a> )</p> <pre><code>;; Toggle both distionary and input method with C-\ (let ((languages '(&quot;en&quot; &quot;it&quot; &quot;de&quot;))) (setq ispell-languages-ring (make-ring (length languages))) (dolist (elem languages) (ring-insert ispell-languages-ring elem))) (defun ispell-cycle-languages () (interactive) (let ((language (ring-ref ispell-languages-ring -1))) (ring-insert ispell-languages-ring language) (ispell-change-dictionary language) (cond ((string-match &quot;it&quot; language) (activate-input-method &quot;italian-postfix&quot;)) ((string-match &quot;de&quot; language) (activate-input-method &quot;german-postfix&quot;)) ((string-match &quot;en&quot; language) (deactivate-input-method))))) (define-key (current-global-map) [remap toggle-input-method] 'ispell-cycle-languages) </code></pre>
26,885
<p>I fear this is probably a bit of a dummy question, but it has me pretty stumped.</p> <p>I'm looking for the simplest way possible to pass a method of an object into a procedure, so that the procedure can call the object's method (e.g. after a timeout, or maybe in a different thread). So basically I want to:</p> <ul> <li>Capture a reference to an object's method.</li> <li>Pass that reference to a procedure.</li> <li>Using that reference, call the object's method from the procedure.</li> </ul> <p>I figure I could achieve the same effect using interfaces, but I thought there was another way, since this "procedure of object" type declaration exists.</p> <p>The following <em>doesn't</em> work, but might it help explain where I'm confused...?</p> <pre><code>interface TCallbackMethod = procedure of object; TCallbackObject = class procedure CallbackMethodImpl; procedure SetupCallback; end; implementation procedure CallbackTheCallback(const callbackMethod: TCallbackMethod); begin callbackMethod(); end; procedure TCallbackObject.CallbackMethodImpl; begin // Do whatever. end; procedure TCallbackObject.SetupCallback; begin // following line doesn't compile - it fails with "E2036 Variable required" CallbackTheCallback(@self.CallbackMethodImpl); end; </code></pre> <p>(Once the question is answered I'll remove the above code unless it aids the explanation somehow.)</p>
<p>Just remove the Pointer stuff. Delphi will do it for you:</p> <pre><code>procedure TCallbackObject.SetupCallback; begin CallbackTheCallback(CallbackMethodImpl); end; </code></pre>
<p>The reason you don't need the pointer syntax is that you've declared the method type as a procedure of object. The compiler will figure out from the "of object" statement how to handle passing the method off the callback proc.</p>
21,462
<p>As the title suggests, is it correct or valid to import/export static data from within a C++ class?</p> <p>I found out my problem - the author of the class I was looking at was trying to export writable static data which isn't supported on this platform.</p> <p>Many thanks for the responses however.</p>
<p>Is it correct inasmuch as it'll work and do what you expect it to? Assuming that you are talking about using _declspec(dllexport/dllimport) on a class or class member, yes, you can do that and it should give you the expected result - the static data would be accessible outside your dll and other C++ code could access it provided that that C++ access specification (public/protected/private) wouldn't block outside access in the first place.</p> <p>Is it a good idea? Personally I don't think so as you would be exposing class internals not only within your library but to the outside world, which means that it will be pretty much impossible to change what is an implementation detail at the end of the day. Ask yourself if you are 100% certain if the interface of this class and large parts of its implementation will never, ever change...</p>
<p>dllexport (or import) on a class's (non-static) data member does nothing. Exported "things" are either functions or global data (though this is a questionable design choice). dllexport on a class is just a shortcut for saying "export all of these functions".</p>
27,408
<p>I've been reading about the <a href="http://en.wikipedia.org/wiki/Open/closed_principle" rel="noreferrer">OCP principle</a> and how to use the strategy pattern to accomplish this.</p> <p>I was going to try and explain this to a couple of people, but the only example I can think of is using different validation classes based on what status an &quot;order&quot; is.</p> <p>I've read a couple of articles online, but these don't usually describe a real alike reason to use the strategy, like generating reports/bills/validation, etc...</p> <p>Are there any real-world examples where you think a strategy pattern is common?</p>
<p>What about this: </p> <p>You have to encrypt a file. </p> <p>For small files, you can use "in memory" strategy, where the complete file is read and kept in memory ( let's say for files &lt; 1 gb ) </p> <p>For large files, you can use another strategy, where parts of the file are read in memory and partial encrypted results are stored in tmp files.</p> <p>These may be two different strategies for the same task.</p> <p>The client code would look the same:</p> <pre><code> File file = getFile(); Cipher c = CipherFactory.getCipher( file.size() ); c.performAction(); // implementations: interface Cipher { public void performAction(); } class InMemoryCipherStrategy implements Cipher { public void performAction() { // load in byte[] .... } } class SwaptToDiskCipher implements Cipher { public void performAction() { // swapt partial results to file. } } </code></pre> <p>The </p> <pre><code> Cipher c = CipherFactory.getCipher( file.size() ); </code></pre> <p>Would return the correct strategy instance for the cipher.</p> <p>I hope this helps.</p> <p><em>( I don't even know if Cipher is the right word :P )</em></p>
<p>From wikipedia </p> <blockquote> <p>In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use</p> </blockquote> <p>In Windows Paint application you can see a strategy pattern where you can choose the shape and color independently in a different sections. Here the shape and color are the algorithms which can changed at runtime. </p> <p>If you want to draw a circle with red color, rather than providing an option of 'RedCircle' they let you choose the circle and a color of your choice.</p> <pre><code>Shape redCircle = new RedCircle(); // Without stretegy Pattern Shaped redCircle = new Shape("red","circle"); // With Strategy pattern </code></pre> <p>Without strategy pattern will increase the number of classes with the Cartesian product of shape and color. Also the interface changes for each implementation.</p>
48,364
<p>My WCF service involves the sending of a dataset (in csv format) data between client and service. This dataset must be encrypted so that the data cannot be intercepted. I'm using wshttpbinding and trying to encrypt the message by using the following settings in web.config:</p> <pre><code>&lt;wsHttpBinding&gt; &lt;binding name="wsHttp"&gt; &lt;reliableSession enabled="true" /&gt; &lt;security mode="Message"&gt; &lt;message clientCredentialType="UserName" algorithmSuite="TripleDes" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/wsHttpBinding&gt; </code></pre> <p>When I try and generate a client proxy I get a long error messagebox (which cannot be completely read because it goes off the bottom of the screen!). The error message does mention something about a "service certificate not being provided".</p> <p>How do I encrypt a message? Do I need a certificate? I should mention that this service will be used over the internet from different domains so I'm not sure whether using "Username" security is the best option (?)</p> <p>Basically I'm confused!</p>
<p>Yes, your service needs a certificate so that your encryption keys can be exchanged securely. You can create a test service authentication certificate with makecert.exe. See <a href="http://web.archive.org/web/20070306040207/http://martinparry.com/cs/blogs/mparry_software/archive/2006/10/30/97.aspx" rel="nofollow noreferrer">this entry in my blog</a> for the details of that.</p> <p>You also need to ensure that the account your service is running as is able to read the certificate's private key file. If you're on Windows Vista (or later) the Certificates MMC snap-in allows you to control permissions on that private-key, but for earlier versions of Windows it's a bit harder. I used to use a utility that came with WSE3, but someone else might be able to suggest a more direct way. Unless your service runs as an admin, you will most likely have to adjust these permissions.</p> <p>Update: like all good things, my blog came to an end. Thanks to makerofthings7 for reminding me. The makecert command you need to generate a service authentication certificate is something like this...</p> <pre><code>makecert -sr LocalMachine -ss My -pe -n CN=subject-name -eku 1.3.6.1.5.5.7.3.1 -sky exchange </code></pre> <p>...simply replace <em>subject-name</em> with any certificate name that makes sense for your service.</p>
<p>I am still trying to find the solution this problem. I have it too, but with signing an xml. Still to find the user IIS is running in WinXP Start > Right-Click My Computer > Manage > Services And Applications > Services > IIS Admin > Double click and in the Log on tab it will usually say Local System.</p> <p>EDIT</p> <p>OK, this is how I solved my problem. I had a ceritificate that I used this <a href="http://www.digwin.com/view/howto-use-makecert-for-trusted-root-certification-authority-and-ssl-certificate-issuance" rel="nofollow noreferrer">article</a> to make the cert. If the project is a ASPWebSite that is saved to your C Folder you may not have issues with this. But if its saved to IIS as an HTTP project then you will have issues. </p> <p>The way to solve it after weeks of investigationg is not that hard. Microsoft has something called the Web Services Enhancements you will download the lastest but I am using the second one with the lastest service pack. When I installed I enabled everything.</p> <p>Certificates can be in a physical file but they are usually in the Certificate Management Store to get to it use the tool X509 Certificate tool in WSE 2.0. Here open your certificate by looking for it in the diferent sections until you find it. Then open it and at the bottom there will be a View Private Key, in the security tab add LOCALHOST\ASPNET . And this should enable your website to read the certificate.</p> <p>In short what happens is that when you create the public and private keys, althought you may see the private key just fine, it really its send to Timbuktu in the file system and you need to find it to add the ASPNET account for read access. I am reading than in Vista this is much easier but I am using XP.</p>
35,521
<p>What is a good error handling practice for an asp.net site? Examples? Thanks!</p>
<p>As with any .net project I find the best way is to only catch specific error types if they are may to happen on the given page. </p> <p>For example you could catch Format Exceptions for a users given input (just incase JavaScript validation fails and you have not use tryparse) but always leave the catching of the top level Exception to the global error handler.</p> <pre><code> try { //Code that could error here } catch (FormatException ex) { //Code to tell user of their error //all other errors will be handled //by the global error handler } </code></pre> <p>You can use the open source <a href="http://code.google.com/p/elmah/" rel="nofollow noreferrer">elmah</a> (Error Logging Modules and Handlers) for ASP.Net to do this top level/global error catching for you if you want. </p> <p>Using <a href="http://code.google.com/p/elmah/" rel="nofollow noreferrer">elmah</a> it can create a log of errors that is viewable though a simple to configure web interface. You can also filter different types of errors and have custom error pages of your own for different error types. </p>
<p>Well, that's pretty wide open, which is completely cool. I'll refer you to a word .doc you can download from <a href="http://www.dotnetspider.com/tutorials/BestPractices.aspx" rel="nofollow noreferrer">Dot Net Spider</a>, which is actually the basis for my small company's code standard. The standard includes some very useful error handling tips.</p> <p>One such example for exceptions (I don't recall if this is original to the document or if we added it to the doc): Never do a “catch exception and do nothing.” If you hide an exception, you will never know if the exception happened. You should always try to avoid exceptions by checking all the error conditions programmatically.</p> <p>Example of what not to do:</p> <pre><code>try { ... } catch{} </code></pre> <p>Very naughty unless you have a good reason for it.</p>
18,767
<p>I have found many pieces of documentations and recommendations about <code>IEnumerator</code>, <code>IEnumerable</code>, <code>ICollection</code>, <code>IList</code> and their generic counterparts. Sadly, I didn't find yet a tutorial or book which explains the whole hierarchy of interfaces, generic implementations of those interfaces <strong>and</strong> the best usage of each type of those.</p> <p>What was your best source of knowledge about the generics, their interfaces, and examples of recommended usage of those in C#?</p>
<p>The main way I came to understand them was just by looking at their interfaces.</p> <p>The inheritance goes like this:</p> <p>IList : ICollection : IEnumerable</p> <p>When you look up IEnumerable's interface, notice that it only has the bare minimum necessary to be able to loop through a bunch of items. It doesn't have count or anything else. IEnumerable works well even if what you're looking at is just a stream coming over a wire.</p> <p>ICollection adds Count. If you are implementing some kind of collection, and if it's easy to know the size of it, then you should implement this. In this case, the generic interface is a little different. ICollection&lt;T&gt; also has methods to modify the collection by adding and removing members. An unordered set would be a good candidate for ICollection.</p> <p>IList adds the ability to get and set collection members by index. Use this when the order of items is significant. When you have indexes, you can do things like swap the 4th and 5th items to change their order.</p>
<p>you just missed one :)</p> <p><strong>IDictionary</strong> : IList : ICollection : IEnumerable</p>
24,742
<p>I'm using the <a href="http://msdn.microsoft.com/en-us/library/ms178329.aspx" rel="nofollow noreferrer">ASP.NET Login Controls</a> and <a href="http://msdn.microsoft.com/en-us/library/aa480476.aspx" rel="nofollow noreferrer">Forms Authentication</a> for membership/credentials for an ASP.NET web application. And I'm using a <a href="http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx" rel="nofollow noreferrer">site map</a> for site navigation.</p> <p>I have ASP.NET TreeView and Menu navigation controls populated using a SiteMapDataSource. But off-limits administrator-only pages are visible to non-administrator users.</p> <hr> <blockquote> <p><strong><a href="https://stackoverflow.com/users/1574/kevin-pang">Kevin Pang</a></strong> wrote:</p> <p>I'm not sure how this question is any different than your <a href="https://stackoverflow.com/questions/33263/how-do-i-best-handle-role-based-permissions-using-forms-authentication-on-my-as">other question</a>&hellip;</p> </blockquote> <p>The other question deals with assigning and maintaining permissions.</p> <p>This question just deals with presentation of navigation. Specifically TreeView and Menu controls with sitemap data sources.</p> <pre><code>&lt;asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" /&gt; &lt;asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" ShowStartingNode="False" /&gt; </code></pre> <hr> <blockquote> <p><strong><a href="https://stackoverflow.com/users/2808/nicholas">Nicholas</a></strong> wrote:</p> <p>add role="SomeRole" in the sitemap</p> </blockquote> <p>Does that only handle the display issue? Or are such page permissions enforced?</p>
<p>You pretty much need to keep the same data context available throughout the lifetime of the operations you want to perform if you're ever going to be storing changes which are to be <code>.SubmitChanges()</code>'d later, as otherwise you will lose those changes.</p> <p>If you're just querying stuff then it's fine to create them as needed, but then if later you want to <code>.SubmitChanges()</code> you'll have to refactor your code a lot, so you may as well adopt the pattern of effectively keeping the <code>datacontext</code> global throughout your app from the beginning.</p> <p>Note the data context is <em>disconnected</em>. The connection is only made when the query data is <em>enumerated</em> (not when you first run the query, it's a 'lazy' data type so only provides data when it's needed), and then closed immediately afterwards. On <code>.SubmitChanges()</code> the connection is opened to submit the changes then closed immediately afterwards. So don't think keeping the <code>datacontext</code> around keeps a connection open, it doesn't (you can hook the <code>StateChange</code> event of the connection to confirm this for yourself, that's how I'm sure).</p> <p>There is a great article over at <a href="http://www.west-wind.com/weblog/posts/246222.aspx" rel="nofollow noreferrer">Rick Strahl's Blog</a> which covers this topic in depth, far more than my answer here provides!!</p>
<p>I think Jeff Atwood talked about this in the <a href="http://herdingcode.com/?p=36" rel="nofollow noreferrer">Herding Code podcast</a>, when he was questioned about the exact same thing. Listen to it towards the last 15-20 minutes or so.</p> <p>I think in SO, the datacontext is created in the Controller class. Not sure about a lot of details here. But that's what it looked like.</p>
5,343
<p>Before I explain what I'm trying to do, note that I have the good fortune of only having to target Webkit (meaning, I can use lots of neat CSS).</p> <p>So, basically, I want to have a block with a flexible height, position fixed, maximum height being that of the available window height, with some elements at the top and bottom of the block that are always visible, and in the middle an area with overflow auto. Basically it'd look like this:</p> <pre> ---------------------- | Top item | | | | | | stuff | | | | | | | | | Last item | | |------------ | | | | | ---------------------- ---------------------- | Top item | | |-----------| | | lots |^| | | of |_| | | stuff |_| | | | | | | | | | |-----------| | | Last item | | ----------------------</pre> <p>Can it be done with CSS? Or will I have to hack it with Javascript? I'd be willing to accept a little div-itis if that's what it takes to make this work—better div-itis than trying to account for every stupid little thing like reflow and window resize and all of that nonsense.</p> <p>I'm prepared for the bad news that this isn't something CSS can do, but I've been pleasantly surprised by the magic some folks on SO can work before.</p>
<p>Another modification:</p> <pre><code>function update() { $.get("response.php", function(data) { $("#some_div").html(data); window.setTimeout(update, 10000); }); } </code></pre> <p>The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening. </p> <p>Also, if the server fails to respond, it won't keep trying. </p> <p>I've used a similar method in the past using .ajax to handle even more complex behaviour:</p> <pre><code>function update() { $("#notice_div").html('Loading..'); $.ajax({ type: 'GET', url: 'response.php', timeout: 2000, success: function(data) { $("#some_div").html(data); $("#notice_div").html(''); window.setTimeout(update, 10000); }, error: function (XMLHttpRequest, textStatus, errorThrown) { $("#notice_div").html('Timeout contacting server..'); window.setTimeout(update, 60000); } } </code></pre> <p>This shows a loading message while loading (put an animated gif in there for typical "web 2.0" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.</p> <p>This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.</p>
<p><a href="http://plugins.jquery.com/project/Timer" rel="nofollow noreferrer">There's a jQuery Timer plugin</a> you may want to try</p>
27,188
<p>Is there any way to print an OOXML document (.docx file) without having MS Word installed? </p> <p>It works nicely via the MS Word interface but I need to find a way to use it on servers where MS Word is not installed. I've been digging through the API and haven't found anything obvious so I'm inclined to believe there isn't a way. Is this the case?</p> <p><strong>EDIT:</strong> Devin's answer is basically what I understood to be the case. I should have mentioned that I'm using the .NET framework. So I wondered if there is perhaps a .NET library which would be able to be handle a docx file for printing? I see when adding a job to the <code>DefaultPrinterQueue</code> on a <code>LocalPrintServer</code> (in the <code>System.Printing</code> namespace) it can handle an XPS document. So perhaps this is the way to go.</p>
<p>I was curious about the answer myself, so I Googled it. Seems there is support in some Novel and IBM products. Here's a link to a partial answer which seems to say support in OpenOffice is in development. <a href="http://wiki.services.openoffice.org/wiki/Office_Open_XML" rel="nofollow noreferrer">http://wiki.services.openoffice.org/wiki/Office_Open_XML</a></p>
<p>Well yes and no. Yes it is possible without MSWord but you will need an application or library that understands ooxml. There are many other products now that do support (as pointed out by Devin) but if your requirements says you cannot have any of them on the server then...use a library and do it yourself.</p> <p>It will then depend on what platform you are developing in...for instance there is a <a href="http://www.openxml4j.org/Documentation/Overview.html" rel="nofollow noreferrer">OOXML4J</a> library for Java. And there are other libraries for other platforms as you will find <a href="http://openxmldeveloper.org/" rel="nofollow noreferrer">here</a>.</p>
40,420
<p>I have all the forms in one folder and all the code modules in an other folder in VB6. How do I create a better folder structure for the source files?</p> <p>For example if I have twenty forms and twenty code modules, how can I create subfolders Main, Sales, and Employees and put the source files under those subfolders?</p>
<p>You should investigate whether some of your files could reside in a ActiveX DLL instead of the main EXE project. As Konrad pointed out the VB6 IDE project explorer doesn't support folders. Large VB6 projects, like my own, organize the classes into a hierarchy of ActiveX DLLs. For example Utility DLL which has commonly used routines used across the company's applications (file handling, etc). Business Object DLL which has the specific classes used by your applications. Report DLL has the classes that handles reports for that applications. And so on.</p> <p>The gotcha is that you have to worry about compatibility issues between versions.</p>
<p>well if you're talking about adding a new folder from vb6 project explorer view, i'm not sure that you can do so.</p> <p>but if you want to sort it you can apply some naming convention, i.e. module1_xxx, module1_yyy.</p>
39,154
<p>I have an assembly that is targeted for .NET 3.5.</p> <p>I have an application targeted for .NET 2.0 and wonder if I should have any trouble referencing the 3.5 assembly from the 2.0 application.</p> <p>I understand that the IL is supposedly the same, so I'm assuming that it will work, but would like to hear some experiences from others who have tried this.</p> <p>The runtime environment will have both 2.0 and 3.5 installed.</p>
<p>There's no problem. There is only one runtime version executing the app. .NET Framework v2.0.</p>
<p>However - when deploying your .net2.0 application, your user will be prompted to install .net3.5 (as there is a .net 3.5 assembly referenced).</p>
48,250
<p>I'm working on a website that will switch to a new style on a set date. The site's built-in semantic HTML and CSS, so the change should just require a CSS reference change. I'm working with a designer who will need to be able to see how it's looking, as well as a client who will need to be able to review content updates in the current look as well as design progress on the new look.</p> <p>I'm planning to use a magic querystring value and/or a javascript link in the footer which writes out a cookie to select the new CSS page. We're working in ASP.NET 3.5. Any recommendations?</p> <p>I should mention that we're using IE Conditional Comments for IE8, 7, and 6 support. I may create a function that does a replacement:</p> <pre><code>&lt;link href=&quot;Style/&lt;% GetCssRoot() %&gt;.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt; &lt;!--[if lte IE 8]&gt; &lt;link type=&quot;text/css&quot; href=&quot;Style/&lt;% GetCssRoot() %&gt;-ie8.css&quot; rel=&quot;stylesheet&quot; /&gt; &lt;![endif]--&gt; &lt;!--[if lte IE 7]&gt; &lt;link type=&quot;text/css&quot; href=&quot;Style/&lt;% GetCssRoot() %&gt;-ie7.css&quot; rel=&quot;stylesheet&quot; /&gt; &lt;![endif]--&gt; &lt;!--[if lte IE 6]&gt; &lt;link type=&quot;text/css&quot; href=&quot;Style/&lt;% GetCssRoot() %&gt;-ie6.css&quot; rel=&quot;stylesheet&quot; /&gt; &lt;![endif]--&gt; </code></pre>
<p>In Asp.net 3.5, you should be able to set up the Link tag in the header as a server tag. Then in the codebehind you can set the href property for the link element, based on a cookie value, querystring, date, etc.</p> <p>In your aspx file:</p> <pre><code>&lt;head&gt; &lt;link id="linkStyles" rel="stylesheet" type="text/css" runat="server" /&gt; &lt;/head&gt; </code></pre> <p>And in the Code behind:</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { string stylesheetAddress = // logic to determine stylesheet linkStyles.Href = stylesheetAddress; } </code></pre>
<p>I would do the following:</p> <p><a href="http://www.website.com/?stylesheet=new.css" rel="nofollow noreferrer">www.website.com/?stylesheet=new.css</a></p> <p>Then in your ASP.NET code:</p> <pre><code>if (Request.Querystring["stylesheet"] != null) { Response.Cookies["stylesheet"].Value = Request.QueryString["stylesheet"]; Response.Redirect(&lt;Current Page&gt;); } </code></pre> <p>Then where you define your stylesheets:</p> <pre><code>if (Request.Cookies["stylesheet"] != null) { // New Stylesheet } else { // Default } </code></pre>
2,710
<p>I have a program in which I've lost the C++ source code. Are there any good C++ decompilers out there?</p> <p>I've already ran across <a href="http://boomerang.sourceforge.net/" rel="noreferrer">Boomerang</a>.</p>
<p>You can use <a href="http://www.hex-rays.com/idapro/" rel="noreferrer">IDA Pro</a> by <a href="http://www.hex-rays.com/" rel="noreferrer">Hex-Rays</a>. You will usually not get good C++ out of a binary unless you compiled in debugging information. Prepare to spend a <strong>lot</strong> of manual labor reversing the code.</p> <p>If you didn't strip the binaries there is some hope as IDA Pro can produce C-alike code for you to work with. Usually it is very rough though, at least when I used it a couple of years ago.</p>
<p>Depending on how large and how well-written the original code was, it might be worth starting again in your favourite language (which might still be C++) and learning from any mistakes made in the last version. Didn't someone once say about writing one to throw away?</p> <p>n.b. Clearly if this is a huge product, then it may not be worth the time.</p>
25,115
<p>The NUnit documentation doesn't tell me when to use a method with a <code>TestFixtureSetup</code> and when to do the setup in the constructor.</p> <pre><code>public class MyTest { private MyClass myClass; public MyTest() { myClass = new MyClass(); } [TestFixtureSetUp] public void Init() { myClass = new MyClass(); } } </code></pre> <p>Are there any good/bad practices about the <code>TestFixtureSetup</code> versus default constructor or isn't there any difference?</p>
<p>Why would you need to use a constructor in your test classes?</p> <p>I use <code>[SetUp]</code> and <code>[TearDown]</code> marked methods for code to be executed before and after each test, and similarly <code>[TestFixtureSetUp]</code> and <code>[TestFixtureTearDown]</code> marked methods for code to be executed only once before and after all test in the fixture have been run.</p> <p>I guess you could probably substitute the <code>[TestFixtureSetUp]</code> for a constructor (although I haven't tried), but this only seems to break from the clear convention that the marked methods provide.</p>
<p>The constructor and the <code>SetUp</code> methods are used differently:<br> The constructor is run only once.<br> However, the <code>SetUp</code> methods are run multiple times, before every test case is executed.</p>
26,145
<p>i'm fairly new to NHibernate and although I'm finding tons of infos on NHibernate mapping on the web, I am too silly to find this piece of information.</p> <p>So the problem is, i've got the following Model:</p> <p><img src="https://i.stack.imgur.com/DihaU.jpg" alt="Datamodel"></p> <p>this is how I'd like it to look. One clean person that has two Address Properties. </p> <p>In the database I'd like to persist this in one table. So the Person row would have a ShippingStreetname and a Streetname Column, the one mapped to ShippingAddress.Streetname and the other to Address.StreetName</p> <p>I found an <a href="http://nhforge.org/blogs/nhibernate/archive/2008/09/06/a-fluent-interface-to-nhibernate-part-2-value-objects.aspx" rel="nofollow noreferrer">article on fluent interfaces</a>, but still haven't figured out how to do this through the XML Configuration.</p> <p>Thanks in advance!</p> <p>Update: I found the solution to this by myself. This can be done through the node and works rather straightforward.</p> <p>To achieve the mapping of Address and ShippingAddress I just had to add the following to the </p> <pre><code>&lt;component name="Address" class="Address"&gt; &lt;property name="Streetname"&gt;&lt;/property&gt; &lt;property name="Zip"&gt;&lt;/property&gt; &lt;property name="City"&gt;&lt;/property&gt; &lt;property name="Country"&gt;&lt;/property&gt; &lt;/component&gt; &lt;component name="ShippingAddress" class="Address"&gt; &lt;property name="Streetname" column="ShippingStreetname" /&gt; &lt;property name="Zip" column="ShippingZip" /&gt; &lt;property name="City" column="ShippingCity" /&gt; &lt;property name="Country" column="ShippingCountry" /&gt; &lt;/component&gt; </code></pre>
<p>Ok. I found the solution myself. The key is the construct in the XML configuration and it works rather nicely.</p> <p>Here is how it's done:</p> <pre><code>&lt;component name="Address" class="Address"&gt; &lt;property name="Streetname"&gt;&lt;/property&gt; &lt;property name="Zip"&gt;&lt;/property&gt; &lt;property name="City"&gt;&lt;/property&gt; &lt;property name="Country"&gt;&lt;/property&gt; &lt;/component&gt; &lt;component name="ShippingAddress" class="Address"&gt; &lt;property name="Streetname" column="ShippingStreetname" /&gt; &lt;property name="Zip" column="ShippingZip" /&gt; &lt;property name="City" column="ShippingCity" /&gt; &lt;property name="Country" column="ShippingCountry" /&gt; &lt;/component&gt; </code></pre>
<p>you could configure this as two relations. e.g.</p> <pre><code>&lt;many-to-one name="ShippingAddress" class="Yournamespace.Address"/&gt; &lt;many-to-one name="Address" class="Yournamespace.Address"/&gt; </code></pre>
26,862
<p>I embedded a swf in my html page, but I would like it to swap to another swf when I clicked on a button in html. I used swfobject.js to embed the swf, and I use prototype to write the javascript. I thought I can just do this</p> <pre><code>$('movie').value = 'swf/bhts.swf'; alert($('movie').value); </code></pre> <p>the value did change to swf/bhts.swf, but it is still playing the original swf file... this is the code I use to embed swf</p> <pre><code>&lt;object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="530" height="298" id="flashcontent"&gt; &lt;param id="movie" name="movie" value="swf/trailer.swf" /&gt; &lt;/object&gt; </code></pre> <p>thanks.</p>
<p>Using swfObject:</p> <pre><code>&lt;div id='flashContent'&gt; &lt;/div&gt; &lt;script type='text/javascript'&gt; // Setup your initial flash var so = new SwfObject(.....); so.write ('flashContent'); // Some event handler someElement.onclick = function () { // Load up the new SWF so = new swfObject(....); so.write('flashContent'); } &lt;/script&gt; </code></pre>
<p>How are you using SWFObject? If you use the swfobject.embedSWF method to add the SWF to your HTML file, then you can call that again with the same ID and it should remove the old Flash player object and add a new one with your new URL.</p> <p>You also can use the SWF's own methods to replace the URL that it's using. If you've got the ID of the Flash object, use something like</p> <pre><code>var swf = getElementById("flash_id"); swf.LoadMovie(0, "http://example.com/newSwfUrl.swf"); </code></pre> <p>and that should direct the Flash player to reload from a different location, replacing layer 0 (the default one). That may not work with really old Flash players, but should be fine in Flash 8 and later.</p>
37,201
<p>I want to find a way to develop database projects quickly in Visual Studio. Any ideas?</p>
<p>I have a method of creating and updating database projects in Visual Studio 2005 that I thought was common knowledge. After asking a few coworkers if they knew how to update their database projects with this method and receiving no's, I thought I would blog about it and pass along some helpful hints and best practices.</p> <p>I work a lot with databases and especially stored procedures that are built to be used with business logic/data access .NET framework. I enjoy working with databases and always create database projects to live with my .NET projects. I am psychotic about keeping database projects up to date. I have been burned too many time in my younger years where I needed to create a stored procedure that was deleted or was out of sync with the application using the database.</p> <p>After creating your database project in Visual Studio 2005 as shown:</p> <p><a href="http://www.cloudsocket.com/images/image-thumb16.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb16.png</a></p> <p>Create 3 new directories in the projects: Tables, Stored Procedures and Functions. I usually only stored these for my projects.</p> <p><a href="http://www.cloudsocket.com/images/image-thumb17.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb17.png</a></p> <p>I now open the Server Explorer in Visual Studio and create a new connection to my desired database. I am using Northwind as my example. I am not going to walk through the creation of the connection for this example.</p> <p><a href="http://www.cloudsocket.com/images/image-thumb18.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb18.png</a></p> <p>I will use a stored procedure as my example on how to update the database project. First I expand the "Stored Procedures" directory in the Server Explorer for the Northwind database. I select a stored procedure.</p> <p><a href="http://www.cloudsocket.com/images/image-thumb19.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb19.png</a></p> <p>I drag the stored procedure to the "Stored Procedures" directory in the Solution Explorer and drop it.</p> <p><a href="http://www.cloudsocket.com/images/image-thumb20.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb20.png</a></p> <p><a href="http://www.cloudsocket.com/images/image-thumb21.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb21.png</a></p> <p>If you open the file for the dragged stored procedures you will find that the IDE created the script as followed:</p> <pre><code>/****** Object: StoredProcedure [dbo].[CustOrdersOrders] Script Date: 08/25/2007 15:22:59 ******/ IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CustOrdersOrders]') AND type in (N'P', N'PC')) DROP PROCEDURE [dbo].[CustOrdersOrders] GO /****** Object: StoredProcedure [dbo].[CustOrdersOrders] Script Date: 08/25/2007 15:22:59 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CustOrdersOrders]') AND type in (N'P', N'PC')) BEGIN EXEC dbo.sp_executesql @statement = N' CREATE PROCEDURE CustOrdersOrders @CustomerID nchar(5) AS SELECT OrderID, OrderDate, RequiredDate, ShippedDate FROM Orders WHERE CustomerID = @CustomerID ORDER BY OrderID ' END GO </code></pre> <p>You can now drag over all the tables, functions and remaining stored procedures from your database. You can also right click on each script in the Solution Explorer and run the scripts on your database project's referenced database.</p>
<p>DataDude? <a href="http://msdn.microsoft.com/en-us/vsts2008/db/default.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/vsts2008/db/default.aspx</a></p>
10,942
<p>Here's my problem: I have a virtual method defined in a .h file that I want to call in a class that inherits from the base class. Sadly though, the method in the derived class doesn't get called. Is there a better way to implement what I'm trying to do?</p> <pre><code>#ifndef ofxBASE_SND_OBJ #define ofxBASE_SND_OBJ #include "ofConstants.h" class ofxBaseSndObj { public: virtual string getType(){} string key; }; #endif </code></pre> <p>Here's my buzz class</p> <pre><code>#ifndef OFXSO_BUZZ #define OFXSO_BUZZ #include "ofxBaseSndObj.h" class ofxSOBuzz : public ofxBaseSndObj { public: string getType(); }; #endif </code></pre> <p>ofxSOBuzz.cpp</p> <pre><code>string ofxSOBuzz::getType() { string s = string("ofxSOBuzz"); printf(" ********* returning string type %s", s.c_str()); // doesn't get called! return s; } </code></pre> <p>Then in another class I try to call it this way:</p> <pre><code>string ofxSndObj::createFilter(ofxBaseSndObj obj) { string str = obj.getType(); if(str.compare("ofxSOBuzz") == 0) { printf(" all is well "); } } </code></pre> <p>In the method above I need to be able to pass in one of many kinds of objects that all extend the ofxBaseSndObj object. Any suggestsions or pointers would be greatly appreciated. Thanks!</p>
<p>Change this line:</p> <pre><code>string ofxSndObj::createFilter(ofxBaseSndObj obj) </code></pre> <p>to</p> <pre><code>string ofxSndObj::createFilter(ofxBaseSndObj&amp; obj) </code></pre> <p>What you are doing is passing by value (passing a copy).</p> <p>This means you are copying the object to the function. Because the function does not know what type you are actually passing it only passes the type defined in the function declaration and thus it makes a copy of the base class (this is know as the <a href="http://www.cs.ualberta.ca/~hoover/Courses/201/201-New-Notes/lectures/section/slice.htm" rel="nofollow noreferrer">slicing</a> problem).</p> <p>The solution is to pass by reference.</p> <p>If you do not want the function to modify the object (maybe that is why you were passing by value so it could not alter the original) then pass a const reference.</p> <pre><code>class ofxBaseSndObj { public: virtual string getType() const; // If the method does not change the object mark it const string key; }; string ofxSndObj::createFilter(ofxBaseSndObj const&amp; obj) { // allowed to call this if getType() is a const string str = obj.getType(); if(str.compare("ofxSOBuzz") == 0) { printf(" all is well "); } } </code></pre>
<p>You could use dynamic_cast or type_id</p>
29,323
<p>I'm working on a project in C#. The previous programmer didn't know object oriented programming, so most of the code is in huge files (we're talking around 4-5000 lines) spread over tens and sometimes hundreds of methods, but only one class. Refactoring such a project is a huge undertaking, and so I've semi-learned to live with it for now.</p> <p>Whenever a method is used in one of the code files, the class is instantiated and then the method is called on the object instance.</p> <p>I'm wondering whether there are any noticeable performance penalties in doing it this way? Should I make all the methods static "for now" and, most importantly, will the application benefit from it in any way?</p>
<p>From <a href="http://msdn.microsoft.com/en-us/library/ms973852.aspx" rel="noreferrer">here</a>, a static call is 4 to 5 times faster than constructing an instance every time you call an instance method. However, we're still only talking about tens of nanoseconds per call, so you're unlikely to notice any benefit unless you have really tight loops calling a method millions of times, and you could get the same benefit by constructing a single instance outside that loop and reusing it.</p> <p>Since you'd have to change every call site to use the newly static method, you're probably better spending your time on gradually refactoring.</p>
<p>It's not valid in PHP,<br /> Object Method is faster :<br /> <a href="http://www.vanylla.it/tests/static-method-vs-object.php" rel="nofollow noreferrer">http://www.vanylla.it/tests/static-method-vs-object.php</a></p>
24,781
<p>I need a simple way to monitor multiple text log files distributed over a number of HP-UX servers. They are a mix of text and XML log files from several distributed legacy systems. Currently we just ssh to the servers and use <em>tail -f</em> and <em>grep</em>, but that doesn't scale when you have many logs to keep track of.</p> <p>Since the logs are in different formats and just files in folders (automatically rotated when they reach a certain size) I need to both collect them remotely and parse each one differently.</p> <p>My initial thought was to make a simple daemon process that I can run on each server using a custom file reader for each file type to parse it into a common format that can be exported over the network via a socket. Another viewer program running locally will connect to these sockets and show the parsed logs in some simple tabbed GUI or aggregated to a console.</p> <p>What log format should I try to convert to if I am to implement it this way?</p> <p>Is there some other easier way? Should I attempt to translate the log files to the log4j format to use with <a href="http://logging.apache.org/chainsaw/" rel="noreferrer">Chainsaw</a> or are there better log viewers that can connect to remote sockets? Could I use <a href="http://www.baremetalsoft.com/baretail/" rel="noreferrer">BareTail</a> as suggested in <a href="https://stackoverflow.com/questions/18632/how-to-monitor-a-text-file-in-realtime#18690">another log question</a>? This is not a <a href="https://stackoverflow.com/questions/35292/log-files-in-massively-distributed-systems">massivly distributed system</a> and changing the current logging implementations for all applications to use UDP broadcast or put messages on a JMS queue is not an option.</p>
<p>Probably the lightest-weight solution for real-time log watching is to use <a href="http://www.netfort.gr.jp/~dancer/software/dsh.html.en" rel="noreferrer">Dancer's shell</a> in concurrent mode with tail -f:</p> <pre><code>dsh -Mac -- tail -f /var/log/apache/*.log </code></pre> <ul> <li>The -a is for all machine names that you've defined in ~/.dsh/machines.list</li> <li>The -c is for concurrent running of tail</li> <li>The -M prepends the hostname to every line of output.</li> </ul>
<p>Awstats provides a perl script that can merge several apache log files together. This script scales well since the memory footprint is very low, logs files are never loaded in memory. I know that si not exactly what you needs, but perhaps you can start from this script and adapt it for your needs.</p>
10,930
<ol> <li><p>I want to create a scrollable list of pictures fetched from the internet and give the user the ability to click on it. How do i go about doing it in WinForms/C#? Is it possible to add picturebox control/ controls to the listBox?</p></li> <li><p>I tried adding a list of picturebox into UserControl with AutoScroll set to true, which will give me a feel like using a listBox, Is this a right approach?</p></li> <li><p>I also tried setting the ImageLocation of the pictureBox to a URI of the image and then called Load() to load the image, it did work, however my Form is freezing up! How do i go on updating each of the picturebox in a sequential way without freezing my form?</p></li> </ol> <p>Thank you, Azlam</p>
<p>I'll answer your third question first, becuase that's the only one I REALLY know the answer to. There's a LoadAsync() method on the picture box that will load the image in a seperate thread and won't hang your app.</p> <p>As for the other questions, I too would most likely start with a user control and put the images there. The only thing I can suggest would be to first create a user control that has a picture box, and maybe a multiline textbox or richtextbox next to it. Turn off the border on the textbox, and have a slight border around the entire control. This will allow you to display the image, with some text next to it. Then, your actual final control will just be a collection of these controls with the ability to add them as needed.</p> <p>--my 2 cents...</p>
<p>Do you mind scrolling vertically? </p> <p>I would start with the DataGridView control as a base and create the following implementation:</p> <p>1) Create custom column and celltype deriving from DataGridViewImageColumn. You could call them "CronosNetImageColumn", "CronosNetImageCell".</p> <p>2) Create a class "CronosImageDetails" to hold the cell data (include properties for display text and image url). This will be passed in as the value for each cell. Ex:</p> <p>ImageGrid.Rows.Add(new CronosImageDetails { DisplayText="Day at the Beach", ImageURL="http://...beach.jpg" });</p> <p>3) Override the cell Paint() to use a WebClient to get the image and use e.Graphics.DrawImage(ImageObtainedFromWebClient) to paint the image to the cell. You could use e.Graphics.DrawString((CronosImageDetails)value.DisplayText,...) to overlay the text in the cell.</p> <p>This quick solution would get you a scrolling imagelist that only loads images as the user scrolls through the list and provides a solid base for improvement.</p> <p>Recommended further optimizations:</p> <p>A) Create a backbuffer bitmap and graphics for drawing cell data.</p> <p>B) Setup Paint() to simply paint the backbuffer instead of doing the work to get the image</p> <p>C) Create a new cell method LoadImage() that spawns a new thread that downloads the image and paints it onto the back buffer.</p> <p>D) Have Paint() (or a seperate helper thread) track the direction and acceleration of scrolling and estimate which cells need to be preloaded. Trigger LoadImage() on those cells.</p> <p>E) Initialize the back buffer of each cell with a loading image.</p> <p>F) Track and use empirical data from the image loading times to help determine which cells need to be preloaded.</p>
41,144
<p>If a hacker has access to the hashes in my DB, he has access to the rest of the information in the DB anyways. So why would he bother trying to decrypt the passwords? Should I be storing the passwords on a different server to the rest of my data? That is the only scenario in which I can envision it being useful. </p>
<ol> <li><p>Sometimes a hacker doesn't get full access to your DB. Sometimes they find a little SQL injection hole or other weakness that someone didn't code correctly, and so they can only do simple things at first like print out database cells one at a time. If they can print out a real password all of a sudden things get much worse.</p></li> <li><p>Things happen: backup tapes are lost, accidentally thrown away, or stolen. A retired system wasn't wiped properly. A breach elsewhere leads to accidental exposure of a database. If a hacker gets access to a snapshot like this he can learn a lot about your system. But if the passwords are still hashed he can't also use the system to do something malicious, like log in as a different user and start changing things.</p></li> <li><p>I've heard that most hacks are an inside job. Better to remove the ability even for people you trust to log in as others.</p></li> <li><p>It's not about just you. Users tend to share passwords across systems. Maybe some day (God forbid) you have a breach that has nothing to do with passwords, but in the course of that breach your authentication tables will be one of the attacker's targets. If you store passwords in plain-text, you have also just compromised user accounts at many other services, and your very bad day just got quite a lot worse.</p></li> </ol> <p>If you think this kind of thing doesn't happen, go talk to the guys at reddit.</p>
<p>When a hacker access your database it does not mean that he can access the procedural code, those procedures can alter databases outside the hacked database boundaries or inclusive can alter other procedures. </p> <p>By the way now I´m going to ask you something: If a user is hacked and someone has his or her password, how do you make clear that it is not your application or security fault?</p> <p>If you don't have stored passwords you don't have such responsability! </p>
36,595
<p>If I’m writing an applet that shows a video sequence (eg. streaming from a camera, or the applet itself is running the on the camera), do my clients need to download the Java Media Framework libraries inorder to see the sequence?</p>
<p>They need to install Java Media Framework on their computers, or you'll need to bundle the JMF together with your applet somehow.</p>
<p>Did you consider to use <a href="http://javafx.com/" rel="nofollow noreferrer">Java FX</a>? This technology is dealing with this problem of downloading media libraries and so no. Of course. It is still in development. If to be first-adopter is option, it will be worth of considering this. </p>
25,603
<p>I am attempting to rewrite my <a href="http://ForestPad.com" rel="nofollow noreferrer">ForestPad</a> application utilizing WPF for the presentation layer. In WinForms, I am populating each node programmatically but I would like to take advantage of the databinding capabilities of WPF, if possible.</p> <p>In general, what is the best way to two-way databind the WPF TreeView to an Xml document?</p> <p>A generic solution is fine but for reference, the structure of the Xml document that I am trying to bind to looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;forestPad guid="6c9325de-dfbe-4878-9d91-1a9f1a7696b0" created="5/14/2004 1:05:10 AM" updated="5/14/2004 1:07:41 AM"&gt; &lt;forest name="A forest node" guid="b441a196-7468-47c8-a010-7ff83429a37b" created="01/01/2003 1:00:00 AM" updated="5/14/2004 1:06:15 AM"&gt; &lt;data&gt; &lt;![CDATA[A forest node This is the text of the forest node.]]&gt; &lt;/data&gt; &lt;tree name="A tree node" guid="768eae66-e9df-4999-b950-01fa9be1a5cf" created="5/14/2004 1:05:38 AM" updated="5/14/2004 1:06:11 AM"&gt; &lt;data&gt; &lt;![CDATA[A tree node This is the text of the tree node.]]&gt; &lt;/data&gt; &lt;branch name="A branch node" guid="be4b0993-d4e4-4249-8aa5-fa9c940ae2be" created="5/14/2004 1:06:00 AM" updated="5/14/2004 1:06:24 AM"&gt; &lt;data&gt; &lt;![CDATA[A branch node This is the text of the branch node.]]&gt;&lt;/data&gt; &lt;leaf name="A leaf node" guid="9c76ff4e-3ae2-450e-b1d2-232b687214aa" created="5/14/2004 1:06:26 AM" updated="5/14/2004 1:06:38 AM"&gt; &lt;data&gt; &lt;![CDATA[A leaf node This is the text of the leaf node.]]&gt; &lt;/data&gt; &lt;/leaf&gt; &lt;/branch&gt; &lt;/tree&gt; &lt;/forest&gt; &lt;/forestPad&gt; </code></pre>
<p>Well, it would be easier if your element hierarchy was more like...</p> <pre><code>&lt;node type="forest"&gt; &lt;node type="tree"&gt; ... </code></pre> <p>...rather than your current schema.</p> <p>As-is, you'll need 4 <code>HierarchicalDataTemplate</code>s, one for each hierarchical element including the root, and one <code>DataTemplate</code> for <code>leaf</code> elements:</p> <pre><code>&lt;Window.Resources&gt; &lt;HierarchicalDataTemplate DataType="forestPad" ItemsSource="{Binding XPath=forest}"&gt; &lt;TextBlock Text="a forestpad" /&gt; &lt;/HierarchicalDataTemplate&gt; &lt;HierarchicalDataTemplate DataType="forest" ItemsSource="{Binding XPath=tree}"&gt; &lt;TextBox Text="{Binding XPath=data}" /&gt; &lt;/HierarchicalDataTemplate&gt; &lt;HierarchicalDataTemplate DataType="tree" ItemsSource="{Binding XPath=branch}"&gt; &lt;TextBox Text="{Binding XPath=data}" /&gt; &lt;/HierarchicalDataTemplate&gt; &lt;HierarchicalDataTemplate DataType="branch" ItemsSource="{Binding XPath=leaf}"&gt; &lt;TextBox Text="{Binding XPath=data}" /&gt; &lt;/HierarchicalDataTemplate&gt; &lt;DataTemplate DataType="leaf"&gt; &lt;TextBox Text="{Binding XPath=data}" /&gt; &lt;/DataTemplate&gt; &lt;XmlDataProvider x:Key="dataxml" XPath="forestPad" Source="D:\fp.xml"&gt; &lt;/XmlDataProvider&gt; &lt;/Window.Resources&gt; </code></pre> <p>You can instead set the <code>Source</code> of the <code>XmlDataProvider</code> programmatically:</p> <pre><code>dp = this.FindResource( "dataxml" ) as XmlDataProvider; dp.Source = new Uri( @"D:\fp.xml" ); </code></pre> <p>Also, re-saving your edits is as easy as this:</p> <pre><code>dp.Document.Save( dp.Source.LocalPath ); </code></pre> <p>The <code>TreeView</code> itself needs a <code>Name</code> and an <code>ItemsSource</code> bonded to the <code>XmlDataProvider</code>:</p> <pre><code>&lt;TreeView Name="treeview" ItemsSource="{Binding Source={StaticResource dataxml}, XPath=.}"&gt; </code></pre> <p>I this example, I did <code>TwoWay</code> binding with <code>TextBox</code>es on each node, but when it comes to editing just one node at a time in a separate, single <code>TextBox</code> or other control, you would be binding it to the currently selected item of the <code>TreeView</code>. You would also change the above <code>TextBox</code>es to <code>TextBlock</code>s, as clicking in the <code>TextBox</code> does not actually select the corresponding <code>TreeViewItem</code>.</p> <pre><code>&lt;TextBox DataContext="{Binding ElementName=treeview, Path=SelectedItem}" Text="{Binding XPath=data, UpdateSourceTrigger=PropertyChanged}"/&gt; </code></pre> <p>The reason you must use two <code>Binding</code>s is that you cannot use <code>Path</code> and <code>XPath</code> together.</p> <p><strong>Edit:</strong></p> <p>Timothy Lee Russell asked about saving CDATA to the data elements. First, a little on <code>InnerXml</code> and <code>InnerText</code>.</p> <p>Behind the scenes, <code>XmlDataProvider</code> is using an <code>XmlDocument</code>, with it's tree of <code>XmlNodes</code>. When a string such as "stuff" is assigned to the <code>InnerXml</code> property of an <code>XmlNode</code>, then those tags are really tags. No escaping is done when getting or setting <code>InnerXml</code>, and it is parsed as XML.</p> <p>However, if it is instead assigned to the <code>InnerText</code> property, the angle brackets will be escaped with entities &amp;lt; and &amp;gt;. The reverse happens when the value is retreived. Entities (like &amp;lt;) are resolved back into characters (like &lt;).</p> <p>Therefore, if the strings we store in the data elements contain XML, entities have been escaped, and we need to undo that simply by retrieving <code>InnerText</code> before adding a CDATA section as the node's child...</p> <pre><code>XmlDocument doc = dp.Document; XmlNodeList nodes = doc.SelectNodes( "//data" ); foreach ( XmlNode node in nodes ) { string data = node.InnerText; node.InnerText = ""; XmlCDataSection cdata = doc.CreateCDataSection( data ); node.AppendChild( cdata ); } doc.Save( dp.Source.LocalPath ); </code></pre> <p>If the node already has a CDATA section and the value has not been changed in any way, then it still has a CDATA section and we essentially replace it with the same. However, through our binding, if we change the value of the data elements contents, it replaces the CDATA in favor of an escaped string. Then we have to fix them.</p>
<p>I know this is an old post, but there's a more elegant solution. You can indeed use a single <code>HierarchicalDataTemplate</code>, if you use an XPath expression that selects all of the nodes that you want the template to use: <code>XPath=tree|branch|leaf</code>.</p> <pre><code>&lt;HierarchicalDataTemplate x:Key=&quot;forestTemplate&quot; ItemsSource=&quot;{Binding XPath=tree|branch|leaf}&quot;&gt; &lt;TextBlock Text=&quot;{Binding XPath=data}&quot; /&gt; &lt;/HierarchicalDataTemplate&gt; </code></pre> <p>Here's a full <code>Page</code> example with XData embedded in the <code>XmlDataProvider1</code>:</p> <pre><code>&lt;Page xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&gt; &lt;Page.Resources&gt; &lt;XmlDataProvider x:Key=&quot;sampleForestPad&quot; XPath=&quot;forestPad/forest&quot;&gt; &lt;x:XData&gt; &lt;forestPad xmlns=&quot;&quot; guid=&quot;6c9325de-dfbe-4878-9d91-1a9f1a7696b0&quot; created=&quot;5/14/2004 1:05:10 AM&quot; updated=&quot;5/14/2004 1:07:41 AM&quot;&gt; &lt;forest name=&quot;A forest node&quot; guid=&quot;b441a196-7468-47c8-a010-7ff83429a37b&quot; created=&quot;01/01/2003 1:00:00 AM&quot; updated=&quot;5/14/2004 1:06:15 AM&quot;&gt; &lt;data&gt; &lt;![CDATA[A forest node This is the text of the forest node.]]&gt; &lt;/data&gt; &lt;tree name=&quot;A tree node&quot; guid=&quot;768eae66-e9df-4999-b950-01fa9be1a5cf&quot; created=&quot;5/14/2004 1:05:38 AM&quot; updated=&quot;5/14/2004 1:06:11 AM&quot;&gt; &lt;data&gt; &lt;![CDATA[A tree node This is the text of the tree node.]]&gt; &lt;/data&gt; &lt;branch name=&quot;A branch node&quot; guid=&quot;be4b0993-d4e4-4249-8aa5-fa9c940ae2be&quot; created=&quot;5/14/2004 1:06:00 AM&quot; updated=&quot;5/14/2004 1:06:24 AM&quot;&gt; &lt;data&gt; &lt;![CDATA[A branch node This is the text of the branch node.]]&gt;&lt;/data&gt; &lt;leaf name=&quot;A leaf node&quot; guid=&quot;9c76ff4e-3ae2-450e-b1d2-232b687214aa&quot; created=&quot;5/14/2004 1:06:26 AM&quot; updated=&quot;5/14/2004 1:06:38 AM&quot;&gt; &lt;data&gt; &lt;![CDATA[A leaf node This is the text of the leaf node.]]&gt; &lt;/data&gt; &lt;/leaf&gt; &lt;/branch&gt; &lt;/tree&gt; &lt;/forest&gt; &lt;/forestPad&gt; &lt;/x:XData&gt; &lt;/XmlDataProvider&gt; &lt;HierarchicalDataTemplate x:Key=&quot;forestTemplate&quot; ItemsSource=&quot;{Binding XPath=tree|branch|leaf}&quot;&gt; &lt;TextBlock Text=&quot;{Binding XPath=data}&quot; /&gt; &lt;/HierarchicalDataTemplate&gt; &lt;Style TargetType=&quot;TreeViewItem&quot;&gt; &lt;Setter Property=&quot;IsExpanded&quot; Value=&quot;True&quot;/&gt; &lt;/Style&gt; &lt;/Page.Resources&gt; &lt;TreeView ItemsSource=&quot;{Binding Source={StaticResource sampleForestPad}}&quot; ItemTemplate=&quot;{StaticResource forestTemplate}&quot;/&gt; &lt;/Page&gt; </code></pre> <p>This will render as:</p> <p><a href="https://i.stack.imgur.com/gjfgJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gjfgJ.png" alt="ForestTreeView" /></a></p>
22,786
<p>I'm currently building a Spring MVC application. I was looking to use JSP pages with tag libraries for handling the view layer and formatting of the HTML, but I've come across another group in my company that uses Velocity templates for the same purpose.</p> <p>From what I can see, it seems to me as if there are a lot of similarities between the two approaches:</p> <ol> <li>Both have easy-to-understand syntax. Makes it easy for non-developers to understand and use, allowing the designers to focus on the HTML/CSS and only having to use directives/tag libraries in the few cases where they need conditionals/dynamic content without having to have a full understanding of Java. </li> <li>Simple to see which part of the content is HTML vs which are directives/logic.</li> <li>Both are heavily used and well supported.</li> <li>Simple to integrate with Spring MVC.</li> </ol> <p>But in comparing the two technologies, I can't see any specific reasons to use one versus the other. I'm having trouble thinking of any cons specific to either Velocity or JSTL.</p> <p>So my question is, what are the pros and cons of each in your opinion? If you have built a (Spring) MVC app using one or the other, what made you decide on the view layer technology you are using and what (if anything) made you decide against the other?</p> <p><strong>Update</strong>: I've found a similar discussion of this same topic archived on the Spring Framework forum's <a href="http://forum.springframework.org/archive/index.php/t-10443.html" rel="noreferrer">here</a>, which might be of some interest to anyone making the same decision between JSTL and Velocity as I am.</p>
<p>I would prefer to use Velocity just because using JSP+JSTL can allow lazy/sloppy developers to get into trouble by adding scriptlets. There should be no reason to have java code in your view tier. It doesn't take much to understand Velocity and as a matter of fact I just picked it up in about two weeks. While I don't like the formatting of the output, for the most part it works pretty well. We're actually not using it in the app's view tier but rather for generating HTML for use by other browsers. We save the output from Velocity as files which is then deployed to a different server for consumption by other web clients.</p>
<p>JSP is also more difficult to visually differentiate from the embedded HTML. With Velocity, it is very obvious.</p> <p>Also, the VelocityTools package provides a great deal of additional functionality.</p>
49,992
<p>For homework, I was given the following 8 code fragments to analyze and give a Big-Oh notation for the running time. Can anybody please tell me if I'm on the right track? </p> <pre><code>//Fragment 1 for(int i = 0; i &lt; n; i++) sum++; </code></pre> <p>I'm thinking O(N) for fragment 1</p> <pre><code>//Fragment 2 for(int i = 0; i &lt; n; i+=2) sum++; </code></pre> <p>O(N) for fragment 2 as well</p> <pre><code>//Fragment 3 for(int i = 0; i &lt; n; i++) for( int j = 0; j &lt; n; j++) sum++; </code></pre> <p>O(N^2) for fragment 3</p> <pre><code>//Fragment 4 for(int i = 0; i &lt; n; i+=2) sum++; for(int j = 0; j &lt; n; j++) sum++; </code></pre> <p>O(N) for fragment 4</p> <pre><code>//Fragment 5 for(int i = 0; i &lt; n; i++) for( int j = 0; j &lt; n * n; j++) sum++; </code></pre> <p>O(N^2) for fragment 5 but the n * n is throwing me off a bit so I'm not quite sure</p> <pre><code>//Fragment 6 for(int i = 0; i &lt; n; i++) for( int j = 0; j &lt; i; j++) sum++; </code></pre> <p>O(N^2) for fragment 6 as well</p> <pre><code>//Fragment 7 for(int i = 0; i &lt; n; i++) for( int j = 0; j &lt; n * n; j++) for(int k = 0; k &lt; j; k++) sum++; </code></pre> <p>O(N^3) for fragment 7 but once again the n * n is throwing me off</p> <pre><code>//Fragment 8 for(int i = 1; i &lt; n; i = i * 2) sum++; </code></pre> <p>O(N) for fragment 8</p>
<p>I think fragment 5 is O(n^3), and similarly fragment 7 is O(n^5)*. It also looks like O(log(n)) for fragment 8.</p> <p>For the n * n problems, you have to execute the body of the loop n * n times, so it would be O(n^2), then you compound that with the order of the other code. Fragment 8 actually doubles the counter instead of incrementing it, so the larger the problem, the less additional work you have to do, so it's O(log(n))</p> <p><strong>*edit:</strong> Fragment 7 is O(n^5), not O(n^4) as I previously thought. This is because both j <i>and k</i> go from 1 to n * n. Sorry I didn't catch this earlier.</p>
<p>You appear to be on the right track. With regards to the N*N what effect do you think it would have? It is another factor of N so it would likely be a higher order.</p> <p>Just a warning, I saw another post like this and it was extremely down voted. Be careful. <a href="https://stackoverflow.com/questions/216496/logic-equivalence-question">Here</a> is the post.</p>
26,650
<p>I've got the bare minimum to handle the Linux/MySQL parts of the stack, but I want to have a basic grasp of PHP before I dive in. I'll be working on WordPress plugins, in case there's anything specifically interesting for that.</p> <p>PS - any recommendations regarding recommended source control/IDEs would also be great, but I guess that's a separate question.</p>
<p>I would recomment the <a href="http://www.php.net/manual/en/" rel="noreferrer">PHP manual</a> too!</p>
<p>The best php/mysql book is probably <a href="http://ibmdw.safaribooksonline.com/9780672329166" rel="nofollow noreferrer" title="PHP and MySQL web development">PHP and MySQL web development</a> but if you already have an experience in web development you might just need something like the <a href="http://safari.oreilly.com/0596101015" rel="nofollow noreferrer" title="PHP Cookbook">PHP cookbook</a>.</p> <p>Also, if you don't have any experience with share hosting, you should read something like <a href="http://ibmdw.safaribooksonline.com/0596007248" rel="nofollow noreferrer" title="Apache Security">Apache security</a> (chapter 6).</p>
27,150
<p>I have the following Transact-Sql that I am trying to convert to LINQ ... and struggling. </p> <pre><code>SELECT * FROM Project WHERE Project.ProjectId IN (SELECT ProjectId FROM ProjectMember Where MemberId = 'a45bd16d-9be0-421b-b5bf-143d334c8155') </code></pre> <p>Any help would be greatly appreciated ... I would like to do it with Lambda expressions, if possible. </p> <p>Thanks in advance!</p>
<p>GFrizzle beat me to it. But here is a C# version</p> <pre><code>var projectsMemberWorkedOn = from p in Projects join projectMember in ProjectMembers on p.ProjectId equals projectMember.ProjectId where projectMember.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155" select p; </code></pre> <p>And as a bonus a purely LINQ method chain version as well:</p> <pre><code>var projectsMemberWorkedOn = Projects.Join( ProjectMembers, p =&gt; p.ProjectId, projectMember =&gt; projectMember.ProjectId, ( p, projectMember ) =&gt; new { p, projectMember } ) .Where( @t =&gt; @t.projectMember.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155" ) .Select(@t =&gt; @t.p ); </code></pre>
<p>No need for a lambda, you've just got a simple LINQ join here:</p> <pre><code>From p in db.Projects _ Join m in db.ProjectMember On p.ProjectId Equals m.ProjectId _ Where m.MemberId = "a45bd16d-9be0-421b-b5bf-143d334c8155" _ Select p </code></pre>
45,816
<p>I'm building a 3d printer of size 500 x 500 x 500 build area. For the Z axis, I'm planning to use this <a href="https://www.3dprintronics.com/Linear-Actuator-Ball-Screw-1204-p108536003" rel="nofollow noreferrer">Linear actuator</a>. </p> <p>The maximum weight Z axis might encounter is 15 Kg due to it being a clay printer. A single linear actuator can, according to the specs, lift 10 Kg. So I'm planning to use two of this.</p> <p>My question is a ball screw of pitch 4mm or 5mm, will it be able to Maintain it's position when the motor is de-energized under a load of 15 kg shared by two systems.</p> <p>What effect the diameter of rod has on it??</p> <p>Is there any way to find that??</p>
<blockquote> <p>My question is a ball screw of pitch 4mm or 5mm, will it be able to Maintain it's position when motor is deenergized under a load of 15 kg shared by two systems.</p> </blockquote> <p>The detent torque of a <a href="https://motion.schneider-electric.com/downloads/quickreference/NEMA23.pdf" rel="noreferrer">typical NEMA 23 stepper</a> varies between around 3 and 7 N·cm. This is the torque produced when the windings are not energized.</p> <p>Using this <a href="https://www.daycounter.com/Calculators/Lead-Screw-Force-Torque-Calculator.phtml" rel="noreferrer">leadscrew torque calculator</a>, you can find that the torque required for a 12 mm diameter, 4 mm pitch leadscrew to hold up a 75 N load, is around 5 N·cm - assuming there is no friction. If there is friction, then the required torque will be lower.</p> <p>So, the torque required is almost equal to or possibly even higher than the detent torque. Therefore, you should not count on a de-energized motor holding up the build platform. In practice, you might see that friction is enough to hold up the build platform, but that any disturbance (such as somebody bumping into the printer) is enough to get the leadscrews to start spinning and have the platform drop like a rock.</p> <blockquote> <p>What effect the diameter of rod has on it?</p> </blockquote> <p>Increasing the pitch also increases the torque required (so, go with a lower pitch leadscrew). The diameter does not affect the torque directly, but having a larger diameter increases the friction and so is beneficial.</p>
<p>Adding to the other more scientific answers here. The backdriving force will move the lead screws depending on the stiction between the lead screw and the nut. If it was friction less then it will always slide. Basically you need to keep the lead screw from turning while the machine is off. You can make a basic electromagnetic clutch which will add some resistance to turning by using double pole double throw relays to short the motor leads to ground when the power is off. You can test this yourself by just connecting all the lead wires together and then try turning the motor spindle by hand.</p> <p><a href="https://i.stack.imgur.com/Rycew.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rycew.gif" alt="Concept of an electromagnetic brake"></a></p> <p><a href="https://en.wikipedia.org/wiki/Electromagnetic_brake" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Electromagnetic_brake</a></p>
1,043
<p>I got a new CR-10S 3D printer (I received it at Christmas). It has been printing just fine until yesterday, I was doing a print and it randomly paused, it did not restart on its own, I had to restart the print, then the item finished just fine. I am printing today, a very small item, the printer now stopped 3 times. How can I fix this, or do I need to return it?</p>
<p>The cr10s has a filament run-out sensor. If the microswitch doesn't function properly, or you have issues with the wiring, the print pauses.</p>
<p>It would be great if you can write what the printer says when it stops. </p> <p>I suggest you try printing other small objects. If that also stops then the printer itself has a problem. But if the printer prints other objects without stopping, then the one you want to print has bad gcode files. You also need to make sure to keep it up-to-date Cura. It would also be great if you can update your printer firmware. But other than that, problems could be heat problem, power problem, and other stuff; it would be great again if you can write the problem that says on the printer as it stops... </p>
1,563
<p>Is it possible to develop custom PLAF themes for Swing? I would appreciate constructive suggestions in this topic Thanks</p>
<p>Yes! But don't do that. If you need just change colors. Try JGoodies or Substance and obey writing your own PLAF.</p>
<p>It is possible to create a custom PLAF using the built-in Synth Look-and-Feel. It's basically a PLAF that allows you to customize the appearance of all components (or just specific ones via component naming) via an XML configuration file. The <code>[javax.swing.plaf.synth][1]</code> package JavaDoc gives a good overview of what's possible, and there is additional documentation linked to in the JavaDocs for using this PLAF.</p> <p>I've used this in my own projects before and it's very easy to work with. You can use your own custom graphic images for all components, and can customize pretty much anything you want without having to go through all that cumbersome custom coding that used to be necessary to make a PLAF</p>
33,589
<p>In Python specifically, how do variables get shared between threads?</p> <p>Although I have used <code>threading.Thread</code> before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing?</p> <p>I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem. </p> <p>Thanks in advance!</p>
<p>In Python, everything is shared, except for function-local variables (because each function call gets its own set of locals, and threads are always separate function calls.) And even then, only the variables themselves (the names that refer to objects) are local to the function; objects themselves are always global, and anything can refer to them. The <code>Thread</code> object for a particular thread is not a special object in this regard. If you store the <code>Thread</code> object somewhere all threads can access (like a global variable) then all threads can access that one <code>Thread</code> object. If you want to atomically modify <em>anything</em> that another thread has access to, you have to protect it with a lock. And all threads must of course share this very same lock, or it wouldn't be very effective.</p> <p>If you want actual thread-local storage, that's where <code>threading.local</code> comes in. Attributes of <code>threading.local</code> are not shared between threads; each thread sees only the attributes it itself placed in there. If you're curious about its implementation, the source is in <a href="https://github.com/python/cpython/blob/master/Lib/_threading_local.py" rel="noreferrer">_threading_local.py</a> in the standard library.</p>
<p>Worth mentioning <code>threading.local()</code> is not a singleton.</p> <p>You can use more of them per thread. It is <strong>not one storage</strong>.</p>
13,060
<p>We are using <a href="http://activemq.apache.org/" rel="noreferrer">ActiveMQ 5.2</a> as our implementation of choice and we picked it a while ago. It performs well enough for our use right now. Since its been a while, I was wondering what other Java Message Service implementations are in use and why? Surely there are more than a few.</p>
<p>Before delving into JMS, consider AMQP as well - might be a new standard. JMS providers I worked with (in varying degrees):</p> <p>TIBCO EMS - very quick and robust, good API support, Java friendly, native C API exists. Best commercial choice I've used.</p> <p>Websphere MQ (and its JMS implementation) - so, so. Pub/sub not exactly quick, many configurations options and choices are 'strange' and overly complex from the long history of that product. Just look at the amount of documentation...</p> <p>Solace JMS - very high throughput (the JMS broker is built in hardware !), good choices of connecting protocols (MQTT, AMQP, XML over http as admin protocols)</p> <p>Fiorano MQ - used to be agressive in marketing but lost a lot of market share, maturity concerns</p> <p>Sonic MQ - solid product, also supports a C API</p> <p>Active MQ - if you want to go with an open-source product (unexpensive support, great community, limited add-on products, limited enterprise features) this is probably your best choice. Works out of the box and is the backbone of several tools like Apache Camel, for example.</p>
<p>We are using SonicMQ, JBossMQ and the "micro broker" of Lotus Expeditor Integrator. We are using them for different purposes:</p> <p>-JBossMQ is used internally and to communicate out of all our Java EE applications which run on JBoss. -Lotus Expeditor is used in "remote sites" where we do only have limited resources and IT staff -SonicMQ is our Messaging backbone, we use it for connecting central systems, but also to connect remote systems in approx. 1000 sites. </p> <p>We are having good experiences with all of them, but our experience is also that with a more complex environment you have to do a more active administration of the Messaging system. This became especially true with SonicMQ at our site :-) . From a performance perspective we made the best experiences with SonicMQ especially in Queue based persistent messaging.</p>
15,060
<p>I am trying to print something that might take 15 hours. I don't want to risk my printer so if I print for 15 hours, what is the worst that can happen? So far, I haven't printed anything for more than 5 hours.</p>
<p>Playing around with the nozzle height will help: back it off until just before you have first layer adhesion issues. Don't jam the filament into the bed as you might for ABS. This helps with small prints. However, my experience has been that if you have a large enough continuous contact area (i.e. more than a few square inches) with the print bed, there will be problems getting the print off. So I still use painters tape (in case I have to rip the print off with force) and glue sticks (so that I don't often need to) on my aluminum print bed as I've found that makes it much easier to deal with without damaging either the bed or the print.</p> <p>You can also try dialing back the heated bed temperature a bit (I think I've got mine set to 70-75c for PETG) but that also doesn't eliminate the issue with larger prints. Also, if I lowered it too much I had problems with first layer adhesion on any size print.</p> <p>I also have a glass plate that I use for ABS, which I don't use with PETG. I've read too many accounts of it sticking too well to glass as well (to the point of the plate being destroyed) and didn't want to try using the amount of force on it that I sometimes have to when removing a PETG print. I also considered trying BuildTak but read accounts of similar issues with it and PETG. So I stayed with what's been working for me: tape and glue sticks.</p>
<p>Correctly level your bed. Seriously, that's the answer. PETG does stick well, but it only gets difficult to remove if you're smashing the first layer against the bed with a nozzle that's way too close. With the bed leveled properly - using feeler gauges or test prints and a sub-0.1-mm-precision caliper - I have no trouble taking PETG prints off a buildtak-clone bed. Glass should be easier.</p> <p>If you already have PETG stuck to a build surface you care about and don't want to risk destroying it, try heat, or alternating heat and cold.</p>
1,777
<p>If you have a domain object, and you want to do something useful and central to that domain object's responsibility like ensure it is valid, you sometimes need to access the state of related objects in order to perform this validation. </p> <p>How to avoid the domain object needing to call out to a Repository or Data Access Layer? You can't always walk the collection relationships, even with lazy loading, because of performance, and you often want to execute queries in the domain object. You can dependency inject repository implementation into the domain, but not really pure and complicates testing.</p> <p>I've always relaxed things and allowed access out from domain to a repository using DI. I have seen no clear examples of how to have a 'pure' domain layer in a complex application which is not also anemic and has a service/application layer doing all the grunt and messing with what should be innards of the domain objects.</p>
<ul> <li><p>If the object is a value object, it should be immutable and validated during construction.</p></li> <li><p>If the object is a root aggregate, and that its own state is sufficient to tell you if it is valid or not, you could add a validation method on it, which cascades through the aggregation.</p></li> <li><p>Lastly, and I think it is your main concern, if you need to access several related objects (that are not in the same aggregate) to ensure one of them is valid, you definitively needs to deport this logic in a specific validation service.</p></li> </ul> <p>I really think that injecting services and repositories into entities are not the best choice. Creating dedicated services seems more appropriate, and I don't see why it will leads you to have anemic domain objects.</p> <p>In short, if you can validate you object state without relying on services or repositories, let the object takes care of it, at the aggregate root level. When you need to query services or repositories, or when you need other entities, then strongly consider moving this logic outside the object.</p>
<p>I answered a similar question just a few hours ago. The answer contains some guidance I use when a try to enrich my model with logic and behavior without making it dirty with dependencies to infra-tech related stuff. <a href="https://stackoverflow.com/questions/7306109/having-trouble-putting-real-world-logic-into-the-ddd-domain-layer/7316621#7316621">Having trouble putting real-world logic into the DDD domain layer</a></p> <p>the answer also links to other useful resources.</p> <p>Good Luck and feel free to mail me or ask me about DDD and avoiding Anemic models. It is a interesting topic where people tend to solve this in different ways.</p>
21,439
<p>I'm trying to get a specific asp:button onclick event to fire when I press the enter key in a specific asp:textbox control.</p> <p>The other factor to be taken into account is that the button is within a asp:Login control template.</p> <p>I've no idea how to do this, suggestions on a postcard please.</p>
<p>You could look at the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.panel.defaultbutton.aspx" rel="noreferrer"><code>DefaultButton</code></a> property of the panel control.</p>
<p>You need to do it with javascript. It's really easy with <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery.</a></p> <p>You can do something like (off the top of my head, not tested):</p> <pre><code>$('#myTextBox').keypress(function(e){ if(e.which == 13) $('#myBtn').click(); }); </code></pre> <p>Edit: Be aware that although jQuery works exceptionally cross browser, there are some quirks with keypress described <a href="http://docs.jquery.com/Events/keypress" rel="nofollow noreferrer">here</a>.</p> <p>Whoops i didnt see you said the "enter key" i thought you said "any key", yeah in that case use DefaultButton on asp:panel</p>
33,712
<p>My company is just starting to look at using WPF for migrating all of our 10 year old business applications. These applications will most of the time be running on computers that have limited/old hardware. We are now a little worried that the hardware might be too limited for using WPF. </p> <p>We have installed Family.Show (<a href="http://www.vertigo.com/familyshow.aspx" rel="noreferrer">http://www.vertigo.com/familyshow.aspx</a>) on an basic older computer and that seems to run ok. But we would like know what your experiences with WPF on older hardware is? Anyone out there willing to share some experiences with us?</p>
<p>I would add several things:</p> <ol> <li><p>The first is, as Stu said, it really depends on what you are doing. In particular, we have found a noticeable difference between WPF 2D and WPF 3D. <strong>If you are doing any WPF 3D stuff at all, your performance is highly dependent on the quality of the video card</strong> (see the <a href="http://msdn.microsoft.com/en-gb/library/ms742196.aspx" rel="nofollow noreferrer">Graphic Rendering Tiers</a> link already mentioned). In particular, we released a WPF 3D feature in April of this year, and it really only worked smoothly on Tier 2 hardware.</p></li> <li><p>Second, I would point you to Jossef Goldberg's <a href="http://blogs.msdn.com/jgoldb/default.aspx" rel="nofollow noreferrer">blog</a>. It has a wealth of information on WPF performance related items.</p></li> <li><p>Third, I would grab and utilize the WPFPerf tools. They were recently updated actually. Jossef's blog <a href="http://blogs.msdn.com/jgoldb/archive/2008/09/25/updated-wpfperf-performance-profiling-tools-for-wpf.aspx" rel="nofollow noreferrer">post</a> will point you in the right direction there as well.</p></li> <li><p>Fourth, take advantage of <a href="http://blogs.msdn.com/jgoldb/archive/2008/03/25/quick-tips-to-improve-wpf-app-memory-footprint.aspx" rel="nofollow noreferrer">virtualization</a> wherever you can.</p></li> <li><p>Finally, I would recommend monitoring performance all the way through the development life cycle. I think the story goes that originally the Blend team did not evaluate performance (for their first release) till closer to the end, and it made solving the problem much more difficult.</p></li> </ol> <p><strong>Update:</strong> There is another StackOverflow <a href="https://stackoverflow.com/questions/222070/how-to-speed-up-wpf-programs">post</a> on this subject. Just wanted to point others to it.</p>
<p>WPF apps will <em>generally</em> run no slower than their equivalents using other technologies. In other words, performance depends on what you're doing. If you have a basic app with some simple data entry controls and a grid or two then it'll be a lot less demanding than an app that has animated custom controls with overlaid video, etc.</p> <p>You should also bear in mind that you must have at least XP SP2 to install WPF, which sets a reasonable hardware baseline anyway.</p> <p>In summary you should have no problems running a WPF app on older hardware as long as you are sensible with the frills. Given WPF's templated controls it's also fairly trivial to test for a basic level of client performance at runtime (see <a href="http://msdn.microsoft.com/en-gb/library/ms742196.aspx" rel="nofollow noreferrer">Graphics Rendering Tiers</a>) and only enable more advanced features on suitable hardware.</p>
29,665
<p>I am completely on board with the ideas behind TDD, Refactoring and Patterns however it does seem like there is a huge gaping whole in these ideas, mainly that they are great for dev teams of 1, but when you start refactoring code that 10 people are working on you start getting merge conflicts all over the place and most diff/merge software can't tell that you refactored a function into its own class.</p> <p>How do you clean up your code, by refactoring, without causing major headaches for everyone on your team?</p>
<p>Small changes committed often.</p> <p>As for your example, you would start by creating the class, committing that change. Then adding a similar function in the class as the old one and commit that change. Then change all the references from the old function to the new class function, commit that. Then remove the old function and commit that change.</p> <p>Of course, no one said it was going to be easy.</p>
<p>Communication.</p> <p>Tools can't solve this for you, unless the specific tool is your email or IM client.</p> <p>It's the same as if you were making any other major change in a shared project -- you need to be able to tell your coworkers/collaborators "hey, hands off for a couple of hours, I have a big change to the FooBar module coming in".</p> <p>Alternately, if you're going to be making a change so major that it has the potential to cause huge merge conflicts with the work of 10 other people, run the change by them beforehand. Have a code review. Ask for architectural input. Then, when you're as close to consensus as you're likely to get, take that virtual lock on the section of the repository you need, check in your changes, and send out an all-clear.</p> <p>It's not a perfect solution, but it's as close as you'll get. Lots of source control systems support explicit locks on sections of the source base, but I've never really seen those lead to good results in these areas. It's a social problem, and you only really need to resort to technical solutions if you can't trust the people you're working with.</p>
9,395