instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I have a table like as follows:</p> <pre> SoftwareName Count Country Project 15 Canada Visio 12 Canada Project 10 USA Visio 5 USA </pre> <p>How do I query it to give me a summary like...</p> <pre> SoftwareName Canada USA Total Project 15 10 25 Visio 12 5 17 </pre> <p>How to do in T-SQL?</p>
<pre><code>SELECT SoftwareName, SUM( CASE Country WHEN 'Canada' THEN [Count] ELSE 0 END ) AS Canada, SUM( CASE Country WHEN 'USA' THEN [Count] ELSE 0 END ) AS USA, SUM( [Count] ) AS Total FROM [Table] GROUP BY SoftwareName; </code></pre>
<p>i think you can use this Link :</p> <p><a href="https://stackoverflow.com/questions/17165381/sum-of-unique-records-better-performance-than-a-cursor/18657739#18657739">Sum of unique records - better performance than a cursor</a></p> <p>and i think using PIVOT Function have a best performance rater SUM() function.!</p>
30,947
<p>I'm maintaining some code that uses a *= operator in a query to a Sybase database and I can't find documentation on it. Does anyone know what *= does? I assume that it is some sort of a join.</p> <pre><code>select * from a, b where a.id *= b.id</code></pre> <p>I can't figure out how this is different from:</p> <pre><code>select * from a, b where a.id = b.id</code></pre>
<p>From <a href="http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc34982_1500/html/mig_gde/mig_gde160.htm" rel="noreferrer">http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc34982_1500/html/mig_gde/mig_gde160.htm</a>:</p> <p>Inner and outer tables</p> <p>The terms outer table and inner table describe the placement of the tables in an outer join:</p> <ul> <li><p>In a left join, the outer table and inner table are the left and right tables respectively. The outer table and inner table are also referred to as the row-preserving and null-supplying tables, respectively.</p></li> <li><p>In a right join, the outer table and inner table are the right and left tables respectively.</p></li> </ul> <p>For example, in the queries below, T1 is the outer table and T2 is the inner table:</p> <ul> <li>T1 left join T2</li> <li>T2 right join T1</li> </ul> <p>Or, using Transact-SQL syntax:</p> <ul> <li>T1 *= T2</li> <li>T2 =* T1</li> </ul>
<pre><code>select * from a, b where a.id = b.id</code></pre> <p>Requires that a row exist in where b.id = a.id in order to return an answer</p> <pre><code>select * from a, b where a.id *= b.id</code></pre> <p>Will fill the columns from b with nulls when there wasn't a row in b where b.id = a.id.</p>
6,190
<p>On a 32-bit CPU, an integer is 4 bytes and a short integer is 2 bytes. If I am writing a C/C++ application that uses many numeric values that will always fit within the provided range of a short integer, is it more efficient to use 4 byte integers or 2 byte integers?</p> <p>I have heard it suggested that 4 byte integers are more efficient as this fits the bandwidth of the bus from memory to the CPU. However, if I am adding together two short integers, would the CPU package both values in a single pass in parallel (thus spanning the 4 byte bandwidth of the bus)?</p>
<p>Yes, you should definitely use a 32 bit integer on a 32 bit CPU, otherwise it may end up masking off the unused bits (i.e., it will always do the maths in 32 bits, then convert the answer to 16 bits)</p> <p>It won't do two 16 bit operations at once for you, but if you write the code yourself and you're sure it won't overflow, you can do it yourself.</p> <p><strong>Edit</strong>: I should add that it also depends somewhat on your definition of "efficient". While it will be able to do 32-bit operations more quickly, you will of course use twice as much memory. </p> <p>If these are being used for intermediate calculations in an inner loop somewhere, then use 32-bit. If, however, you're reading this from disk, or even if you just have to pay for a cache miss, it may still work out better to use 16-bit integers. As with all optimizations, there's only one way to know: <strong>profile it</strong>.</p>
<p>If you are operating on a large dataset, the biggest concern is memory footprint. A good model in this case is to assume that the CPU is infinitely fast, and spend your time worrying about how much data has to be moved to/from memory. In fact, CPUs are now so fast that it is sometimes more efficient to encode (e.g., compress) the data. That way, the CPU does (potentially much) more work (decoding/coding), but the memory bandwidth is substantially reduced.</p> <p>Thus, if your dataset is large, you are probably better off using 16 bit integers. If your list is sorted, you might design a coding scheme that involves differential or run-length encoding, which will reduce memory bandwidth even more.</p>
19,734
<p>Recently I've been thinking about <em>finite state machines</em> (FSMs), and how I would implement them in software (programming language doesn't matter).</p> <p>My understanding is that <em>deterministic state machines</em> are in widespread use (parses/lexers, compilers and so on), but what's the matter with <em>non-deterministic state machines</em>?</p> <p>I know that is possible to <em>convert</em> all non-deterministic state machines to deterministic ones (even programmatically). That's not my point. I also imagine that non-deterministic state machines are much more complicated to implement.</p> <p>Anyway, does it make <strong>any</strong> sense to implement a non-deterministic state machine? Are there any special applications I don't know about? What could be the reasons to do that? Maybe optimized and specialized non-deterministic state machines are faster?</p>
<p>Most regular expression engines use <em>non</em>-deterministic automata since they offer much greater flexibility. DFAs are much more restricted. Have a look at some implementations and you'll see this. Microsoft even underlines this fact in their documentation of the .NET <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex%28VS.80%29.aspx" rel="noreferrer">Regex</a> class:</p> <blockquote> <p>The .NET Framework regular expression engine is a backtracking regular expression matcher that incorporates a traditional Nondeterministic Finite Automaton (NFA) engine such as that used by Perl, Python, Emacs, and Tcl.</p> </blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/0yzc2yb0%28VS.80%29.aspx" rel="noreferrer">Matching behavior</a> (first paragraph) – this article also offers a rationale for the employment of an NFA rather than the more efficient DFA.</p>
<p><a href="http://www.cs.cornell.edu/bigreddata/cayuga/" rel="nofollow noreferrer">Cayuga</a> utilizes non-deterministic finite state machines under the hood for complex event processing. Well, it looks like they call it "Stateful Publish/Subscribe for Event Monitoring", but I believe it is CEP.</p> <p>I believe some of their papers even discuss why they are using an automata model. You might want to poke around their site.</p> <blockquote> <p>...Cayuga automata, extended from standard non-deterministic finite automata.</p> </blockquote>
24,198
<p>I have a multi-line string that I want to do an operation on each line, like so:</p> <pre><code>inputString = &quot;&quot;&quot;Line 1 Line 2 Line 3&quot;&quot;&quot; </code></pre> <p>I want to iterate on each line:</p> <pre><code>for line in inputString: doStuff() </code></pre>
<pre class="lang-py prettyprint-override"><code>inputString.splitlines() </code></pre> <p>Will give you a list with each item, the <a href="https://docs.python.org/3/library/stdtypes.html#str.splitlines" rel="noreferrer"><code>splitlines()</code></a> method is designed to split each line into a list element.</p>
<p>I wish comments had proper code text formatting, because I think @1_CR 's answer needs more bumps, and I would like to augment his answer. Anyway, He led me to the following technique; it will use cStringIO if available (BUT NOTE: cStringIO and StringIO are <strong>not the same</strong>, because you cannot subclass cStringIO... it is a built-in... but for basic operations the syntax will be identical, so you can do this):</p> <pre><code>try: import cStringIO StringIO = cStringIO except ImportError: import StringIO for line in StringIO.StringIO(variable_with_multiline_string): pass print line.strip() </code></pre>
20,781
<p>I have a ListView control, and I'm trying to figure out the easiest/best way to disallow changing the selected row(s), without <em>hiding</em> the selected row(s).</p> <p>I know there's a <code>HideSelection</code> property, but that only works when the <code>ListView</code> is still enabled (but not focused). I need the selection to be viewable even when the ListView is disabled.</p> <p>How can I implement this?</p>
<p>You could also make the ListView ownerdraw. You then have complete control over how the items look whether they are selected or not or whether the ListView itself is enabled or not. The DrawListViewItemEventArgs provides a way to ask the ListView to draw individual parts of the item so you only have to draw the bits you're interested in. For example, you can draw the background of the item but leave it up to the ListView to draw the text.</p>
<p>Implement SelectedIndexChanged and do this</p> <pre><code> private void listViewABC_SelectedIndexChanged(object sender, EventArgs e) { listViewABC.SelectedItems.Clear(); } </code></pre>
3,489
<p>I am a programmer who writes a lot of code for desktop applications, now started considering cross-platform apps as an issue but at work I write C# apps and I come from C++ and CS background and of course, I wrote several things in QT/C++. But now I am kinda confused about web applications, I have done some work on PHP and I know how things go there, I was a gmail and google docs user for a lot of time and I have seen how much web applications were improved with new web 2.0 technology including Ajax, XML so on. And my confusion is that should I start looking forward for web application development? and continue exploring the power of web 2.0 or I have to just stick with my old world where I feel very comfortable on parallelism and other stuff? Because believe me I had too many offers to work as a web application developer but I didn't realize this opportunity and now I am kinda confused whether I must start writing web apps. Have you been writing desktop applications and switched to web? or have somebody experience in this scenario?</p> <p>Thank you.</p>
<p>The boundaries between desktop and web applications have really blurred. Whilst once upon a time the nature of developing for the web was totally different to developing for the desktop, nowadays you find the same concepts (such as parallelism which you referred to) cropping up in both. Don't think of developing web applications as taking a huge step away from traditional software development as you'll employ just as many skills and concepts as you already use. You wouldn't need to learn a whole lot more to get involved in web development if you have C# experience, as you could code backends to web applications in a very similar way to how you currently work. If you wanted/needed to get involved in the UI side of things, there are new technologies you'd need to pick up, but they're not essential to get a job in web development (as long as you weren't looking for a frontend role obviously).</p> <p>To follow up Dustman's comments about companies wanting to keep tight control of their data etc; bear in mind that not all "web applications" involve the use of the internet. Really all the term means is "applications developed on web-based technologies" and as well as being deployed publically on the web, they're commonly deployed on intranets and other closed-access environments. I work for a software company which develops "web applications" but a large number of systems are hosted by clients for use on their internal networks for the very reasons Dustman refers to - they want to keep tight control of their data. The beauty of web based technologies is that you can achieve this whilst still reaping the benefits of a centralised system, meaning there is no need to manage deployment across 100s of workstations, no need to worry too much about the specifications of client devices, the ability to access the system across different types of device (mobile etc), regular and easily deployed updates, and so I could continue.</p>
<p>In the near future, the boundary between the web development and the desktop application development will go on erasing. For a professional programmer, learning new things is the real growth. learning web development for an experienced programmer is not a difficult task. you can obviously go ahead and learn the web development. You should recognize web well as it will certainly come to meet the desktop apps in the near future.</p>
16,803
<p>Here's an interface:</p> <pre><code>public interface Foo&lt;T&gt; extends Comparable&lt;Foo&lt;T&gt;&gt; { ... } </code></pre> <p>And there are some classes implementing this interface:</p> <pre><code>public class Bar extends Something implements Foo&lt;Something&gt; { public Vector&lt;Foo&lt;Bar&gt;&gt; giveBar() { ... } } public class Boo extends SomethingElse implements Foo&lt;SomethingElse&gt; { public Vector&lt;Foo&lt;Boo&gt;&gt; giveBoo() { ... } } </code></pre> <p>Now I want to keep a bunch of Foos (that may really be Foos or Boos) inside a vector. </p> <pre><code>Bar bar = new Bar(); Boo boo = new Boo(); Vector&lt;Foo&lt;?&gt;&gt; vector; if (...) vector = bar.giveBar(); else vector = boo.giveBoo(); </code></pre> <p>I get:</p> <pre><code>Type mismatch: cannot convert from Vector&lt;Foo&lt;SomethingElse&gt;&gt; to Vector&lt;Foo&lt;?&gt;&gt; </code></pre> <p>The same goes for:</p> <pre><code>Vector&lt;Foo&gt; vector; if (...) vector = giveBar(); else vector = giveBoo(); </code></pre> <p>Is a superclass that both Bar and Boo extend the only solution to this problem?</p>
<p>What all that code boils down to is:</p> <pre><code>Vector&lt;A&gt; vector = new Vector&lt;B&gt;(); </code></pre> <p>In this case B extends A, but that's not allowed because the types don't match. To make clear why this doesn't work, imagine the following code:</p> <pre><code>Vector&lt;Vector&lt;?&gt;&gt; vector = new Vector&lt;Vector&lt;String&gt;&gt;(); vector.add(new Vector&lt;Integer&gt;()); </code></pre> <p>The variable's type is of a <em>vector of vectors of unknown type</em>; and what's being assigned to it is a <em>vector of vectors of strings</em>. The second line adds a <em>vector of integers</em> to that. The component type of the variable <code>Vector&lt;?&gt;</code>, which accepts <code>Vector&lt;Integer&gt;</code>; but the actual vector's component type is <code>Vector&lt;String&gt;</code>, which doesn't. If the compiler didn't object to the assignment on the first line, it would allow you to write the incorrect second line without being spotted.</p> <p>C#'s generics have a similar restriction, but the difference is that a generic class in C# stores it component type, while Java forgets component types when the code is compiled.</p> <p>ps - Why on earth are you using <code>Vector</code> rather than <code>LinkedList</code> or <code>ArrayList</code>? Is it because there are threading issues involved?</p>
<p>You can use</p> <pre><code>Vector&lt;? extends Foo&lt;?&gt;&gt; vector; </code></pre>
32,275
<p>"Assembly [AssemblyName] must have a shared name to be installed globally"</p> <p>I am getting this error message when I try to deploy some component DLLs for my application to the Global Assembly Cache.</p> <p>What is a shared name and how do i make sure my DLLs have one?</p>
<p>A &quot;shared name&quot; must be a synonym for a &quot;<a href="http://msdn.microsoft.com/en-us/library/xc31ft41.aspx" rel="nofollow noreferrer">strong name</a>,&quot; which is what I've always read/heard it called. That link shows how to sign an assembly with a strong name so that it can be added to the GAC.</p>
<p>That's correct, you need to sign your assembly with a <a href="http://msdn.microsoft.com/en-us/library/szdke3d6.aspx" rel="nofollow noreferrer">strong name</a>.</p>
46,900
<p>What are some popular spam prevention methods besides CAPTCHA?</p>
<p>I have tried doing 'honeypots' where you put a field and then hide it with CSS (marking it as 'leave blank' for anyone with stylesheets disabled) but I have found that a lot of bots are able to get past it very quickly. There are also techniques like setting fields to a certain value and changing them with JS, calculating times between load time and submit time, checking the referer URL, and a million other things. They all have their pitfalls and pretty much all you can hope for is to filter as much as you can with them while not alienating who you're here for: the users.</p> <p>At the end of the day, though, if you really, really, don't want bots to be sending things through your form you're going to want to put a CAPTCHA on it - best one I've seen that takes care of mostly everything is <a href="http://recaptcha.net" rel="noreferrer">reCAPTCHA</a> - but thanks to India's CAPTCHA solving market and the ingenuity of spammers everywhere that's not even successful all of the time. I would beware using something that is 'ingenious' but kind of 'out there' as it would be more of a 'wtf' for users that are at least somewhat used to your usual CAPTCHAs.</p>
<p>You could get some device ID software the41 has some fraud prevention software that can detect the hardware being used to access your site. I belive they use it to catch fraudsters but could be used to stop bots. Once you have identified an device being used by a bot you can just block that device. Last time a checked it can even trace your route throught he phone network ( Not your Geo-IP !! ) so can even block a post code if you want.</p> <p>Its expensive through so prop. a better cheaper solution that is a little less big brother.</p>
13,677
<p>A sysadmin teacher told me one day that I should learn to use "make" because I could use it for a lot of other things that just triggering complilations.</p> <p>I never got the chance to talk longer about it. Do you have any good example ?</p> <p>As a bonus, isn't it this tool deprecated, and what are modern alternatives (for the compilation purpose and others) ?</p>
<p>One excellent thing make can be used for besides compilation is LaTeX. If you're doing any serious work with LaTeX, you'll find make very handy because of the need to re-interpret .tex files several times when using BibTex or tables of contents.</p> <p>Make is definitely not deprecated. Although there are different ways of doing the same thing (batch files on Windows, shell scripts on Linux) make works the best, IMHO.</p>
<p>The most random use I've ever seen is make being used in place of bash for init scripts on <a href="http://bccd.cs.uni.edu/" rel="nofollow noreferrer">BCCD</a>. It actually worked decently, once you got over the wtf moment....</p> <p>Think of make as shell scripts with added oomph.</p>
12,748
<p>I want to grant a user permission to create, alter, and execute stored procedures, but without the ability to create other database objects. I excluded them from the role db_ddladmin, but explicitly granted the permissions "Create procedure" and "Execute". These permssions appear in the effective permissions list. However, when I try to create a stored procedure with this login, I get the following error: </p> <p>"The specified schema name "dbo" either does not exist or you do not have permission to use it."</p> <p>Any suggestions?</p>
<p>A user can create procedures in a schema that they own. So you can set up a schema for the user to do development work. Then, if it needs to be dbo, the admin can put it there when development is done.</p>
<p>If you can create (or alter) and execute a stored procedure, you can do anything. </p> <p>Execute on a stored procedure implies all other permissions within the context of that procedure. So if you can change a procedure <em>and</em> run it, there's no point in restricting anything else. You could just make the procedure act as a proxy on your behalf.</p>
28,051
<p>I need to add the ability for users of my software to select records by character ranges.<br> How can I write a query that returns all widgets from a table whose name falls in the range Ba-Bi for example?</p> <p>Currently I'm using greater than and less than operators, so the above example would become:</p> <pre><code>select * from widget where name &gt;= 'ba' and name &lt; 'bj' </code></pre> <p>Notice how I have "incremented" the last character of the upper bound from i to j so that "bike" would not be left out.</p> <p>Is there a generic way to find the next character after a given character based on the field's collation or would it be safer to create a second condition?</p> <pre><code>select * from widget where name &gt;= 'ba' and (name &lt; 'bi' or name like 'bi%') </code></pre> <p>My application needs to support localization. How sensitive is this kind of query to different character sets?</p> <p>I also need to support both MSSQL and Oracle. What are my options for ensuring that character casing is ignored no matter what language appears in the data?</p>
<p>Let's skip directly to localization. Would you say "aa" >= "ba" ? Probably not, but that is where it sorts in Sweden. Also, you simply can't assume that you can ignore casing in any language. Casing is explicitly language-dependent, with the most common example being Turkish: uppercase i is İ. Lowercase I is ı.</p> <p>Now, your SQL DB defines the result of &lt;, == etc by a "collation order". This is definitely language specific. So, you should explicitly control this, for every query. A Turkish collation order will put those i's where they belong (in Turkish). You can't rely on the default collation.</p> <p>As for the "increment part", don't bother. Stick to >= and &lt;=.</p>
<p>For MSSQL see this thread: <a href="http://bytes.com/forum/thread483570.html" rel="nofollow noreferrer">http://bytes.com/forum/thread483570.html</a> .</p> <p>For Oracle, it depends on your Oracle version, as Oracle 10 now supports regex(p) like queries: <a href="http://www.psoug.org/reference/regexp.html" rel="nofollow noreferrer">http://www.psoug.org/reference/regexp.html</a> (search for regexp_like ) and see this article: <a href="http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/rischert_regexp_pt1.html" rel="nofollow noreferrer">http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/rischert_regexp_pt1.html</a></p> <p>HTH</p>
18,405
<p>I am working with:</p> <pre><code>#top ul li.corner span.right-corner:hover { background-image:url("images/corner-right-over.gif"); width:4px; height:15px; float:left; } #top ul li.corner span.left-corner:hover { background-image:url("images/corner-left-over.gif"); float:left; width:4px; height:15px; } </code></pre> <p>And I can't seem to get the <code>:hover</code> working properly? Not sure why, does anyone have any suggestions?</p>
<p>I believe the problem is that SPAN elements display inline by default - meaning they have no height and width. Try explicitly making them block level elements by adding:</p> <pre><code>#top ul li.corner span.right-corner, #top ul li.corner span.left-corner { display: block; } </code></pre>
<p>As the commenter noted, "top" is not a valid selector. It should be "#top" or ".top"</p>
42,294
<p>Is it possible to encode an assignment into an expression tree?</p>
<p>No, I don't believe so.</p> <p>Certainly the C# compiler disallows it when converting a lambda expression:</p> <pre><code>int x; Expression&lt;Func&lt;int,int&gt;&gt; foo = (x=y); // Assign to x and return value </code></pre> <p>This yields the error:</p> <pre><code>CS0832: An expression tree may not contain an assignment operator </code></pre>
<p>You could probably work around it by nexting expression trees. Call a lambda function, where an argument is the value of the assignee.</p>
25,635
<p>I currently have a list view which has several rows of data and I have a contextmenustrip in C# .NET.</p> <p>What I am having problems with is when you click on the menu strip item I want to know which row has been selected.</p>
<p>To get selected rows as sindre says you do like this:</p> <pre><code>foreach (ListViewItem item in lvFiles.SelectedItems) { .................................... } </code></pre> <p>lvFiles is the ListView.</p>
<p>I really don't know what you mean here. Can you please explain your problem further or provide a code example?</p> <p>To get the selected row in a ListView you use the ListView.SelectedItems property. ListView.SelectedItems[0] will give you the first seleted item (as there can be more than one item selected)</p>
42,111
<p>Would it be useful to be able to mark objects where the value ofString.valueOf() would included in any stack trace. In my example below I used "trace". Variables that aren't declared at the point of the stack trace would just be ingored. It would make debugging much easier and make it much easier to write programs that are easy to debug.</p> <p>Example stack trace for the code below:</p> <pre><code>java.lang.NullPointerException: at Test.main(Test.java:7) index=0, sum=3, obj=null public class Test { Object obj; public void main(String[] args) trace obj { trace int sum = 0; for(trace int index = 0; index &lt; args.length; index++) { sum += Integer.parseInt(args[index]); sum += obj.hashCode();//Will cause NullPointerException } } } </code></pre> <p>From: <a href="http://jamesjava.blogspot.com/2005/04/extra-info-in-stack-traces.html" rel="nofollow noreferrer">http://jamesjava.blogspot.com/2005/04/extra-info-in-stack-traces.html</a></p>
<p>this might be useful, but i think it clutters the code - presumably when the code is working you would want to remove the 'trace' keywords; perhaps some form of metadata would be more appropriate</p> <p>then there's always print statements...</p>
<p>Yes, it can be quite useful. I often do this kind of thing myself, but I only have it compile into non-production code, usually.</p>
12,450
<p>The problem is quite basic. I have a JTable showing cached data from a database. If a user clicks in a cell for editing, I want to attempt a lock on that row in the database. If the lock does not succeed, I want to prevent editing.</p> <p>But I can't seem to find any clean way to accomplish this. Am I missing something?</p>
<p>Before editing/setting value the table model is asked via TableModel.isCellEditable(row,col) whether this cell is editable. Here you can implement your lock. and after TableModel.setValue(row,col,val) you should unlock this. BUT. The lock operation should take a lot of time and makes your UI un-responsible. And it si BAD. Try different approach. What about lazy fail? You lock the row, check for validity of data and fail if data are newer. If data are OK, you put them down. UNLOCK.</p>
<p>Instead, you could wait until the user actually changes something, then override JTable.editingStopped to do the work there (you could even check to see if the value changed)</p> <p>That way no locking is done until the user actually changes something.</p>
30,578
<p>Is there a tool to migrate an <a href="http://en.wikipedia.org/wiki/SQLite" rel="noreferrer">SQLite</a> database to <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="noreferrer">SQL Server</a> (both the structure and data)?</p>
<p><a href="http://en.wikipedia.org/wiki/SQLite" rel="noreferrer">SQLite</a> does have a .dump option to run at the command line. Though I prefer to use the <a href="http://sqlitebrowser.sourceforge.net/" rel="noreferrer">SQLite Database Browser</a> application for managing SQLite databases. You can export the structure and contents to a .sql file that can be read by just about anything. File > Export > Database to SQL file.</p>
<p>A idea is do some thing like this: - View squema in sql lite and get the CREATE TABLE command. - Execute, parsing sql, in SQL SERVER - Travel data creating a INSERT statment for each row. (parsing sql too)</p> <p>This code is beta, because no detect type data, and no use @parameter and command object, but run.</p> <p>(You need insert reference and install System.Data.SQLite;)</p> <p>c#: Insert this code (or neccesari) in head cs</p> <p>using System;</p> <p>using System.Collections.Generic;</p> <p>using System.Text;</p> <p>using System.Data;</p> <p>using System.Data.SqlClient;</p> <p>using System.Data.SQLite;</p> <p>using System.Threading;</p> <p>using System.Text.RegularExpressions;</p> <p>using System.IO;</p> <p>using log4net;</p> <p>using System.Net;</p> <pre><code> public static Boolean SqLite2SqlServer(string sqlitePath, string connStringSqlServer) { String SqlInsert; int i; try { string sql = "select * from sqlite_master where type = 'table' and name like 'YouTable in SQL'"; string password = null; string sql2run; string tabla; string sqliteConnString = CreateSQLiteConnectionString(sqlitePath, password); //sqliteConnString = "data source=C:\\pro\\testconverter\\Origen\\FACTUNETWEB.DB;page size=4096;useutf16encoding=True"; using (SQLiteConnection sqconn = new SQLiteConnection(sqliteConnString)) { sqconn.Open(); SQLiteCommand command = new SQLiteCommand(sql, sqconn); SQLiteDataReader reader = command.ExecuteReader(); SqlConnection conn = new SqlConnection(connStringSqlServer); conn.Open(); while (reader.Read()) { //Console.WriteLine("Name: " + reader["name"] + "\tScore: " + reader["score"]); sql2run = "" + reader["sql"]; tabla = "" + reader["name"]; /* sql2run = "Drop table " + tabla; SqlCommand cmd = new SqlCommand(sql2run, conn); cmd.ExecuteNonQuery(); */ sql2run = sql2run.Replace("COLLATE NOCASE", ""); sql2run = sql2run.Replace(" NUM", " TEXT"); SqlCommand cmd2 = new SqlCommand(sql2run, conn); cmd2.ExecuteNonQuery(); // insertar los datos. string sqlCmd = "Select * From " + tabla; SQLiteCommand cmd = new SQLiteCommand(sqlCmd, sqconn); SQLiteDataReader rs = cmd.ExecuteReader(); String valor = ""; String Valores = ""; String Campos = ""; String Campo = ""; while (rs.Read()) { SqlInsert = "INSERT INTO " + tabla; Campos = ""; Valores = ""; for ( i = 0; i &lt; rs.FieldCount ; i++) { //valor = "" + rs.GetString(i); //valor = "" + rs.GetName(i); Campo = "" + rs.GetName(i); valor = "" + rs.GetValue(i); if (Valores != "") { Valores = Valores + ','; Campos = Campos + ','; } Valores = Valores + "'" + valor + "'"; Campos = Campos + Campo; } SqlInsert = SqlInsert + "(" + Campos + ") Values (" + Valores + ")"; SqlCommand cmdInsert = new SqlCommand(SqlInsert, conn); cmdInsert.ExecuteNonQuery(); } } } return true; } //END TRY catch (Exception ex) { _log.Error("unexpected exception", ex); throw; } // catch } </code></pre>
19,720
<p>In general, what kinds of design decisions help an application scale well?</p> <p>(Note: Having just learned about <a href="http://en.wikipedia.org/wiki/Big_O_notation" rel="nofollow noreferrer">Big O Notation</a>, I'm looking to gather more principles of programming here. I've attempted to explain Big O Notation by answering my own question below, but I want the community to improve both this question and the answers.)</p> <p><strong>Responses so far</strong><br> 1) Define scaling. Do you need to scale for lots of users, traffic, objects in a virtual environment?<br> 2) Look at your algorithms. Will the amount of work they do scale linearly with the actual amount of work - i.e. number of items to loop through, number of users, etc?<br> 3) Look at your hardware. Is your application designed such that you can run it on multiple machines if one can't keep up? </p> <p><strong>Secondary thoughts</strong><br> 1) Don't optimize too much too soon - test first. Maybe bottlenecks will happen in unforseen places.<br> 2) Maybe the need to scale will not outpace Moore's Law, and maybe upgrading hardware will be cheaper than refactoring.</p>
<p>The only thing I would say is write your application so that it can be deployed on a cluster from the very start. Anything above that is a premature optimisation. Your first job should be getting enough users to have a scaling problem. </p> <p>Build the code as simple as you can first, then profile the system second and optimise only when there is an obvious performance problem.</p> <p>Often the figures from profiling your code are counter-intuitive; the bottle-necks tend to reside in modules you didn't think would be slow. Data is king when it comes to optimisation. If you optimise the parts you think will be slow, you will often optimise the wrong things.</p>
<p>One good idea is to determine how much work each additional task creates. This can depend on how the algorithm is structured.</p> <p>For example, imagine you have some virtual cars in a city. At any moment, you want each car to have a map showing where all the cars are.</p> <p>One way to approach this would be:</p> <pre> for each car { determine my position; for each car { add my position to this car's map; } } </pre> <p>This seems straightforward: look at the first car's position, add it to the map of every other car. Then look at the second car's position, add it to the map of every other car. Etc.</p> <p>But there is a scalability problem. When there are 2 cars, this strategy takes 4 "add my position" steps; when there are 3 cars, it takes 9 steps. <b>For each "position update," you have to cycle through the whole list of cars - and every car needs its position updated.</b> </p> <p>Ignoring how many other things must be done to each car (for example, it may take a fixed number of steps to calculate the position of an individual car), <b>for N cars, it takes N<sup>2</sup> "visits to cars" to run this algorithm</b>. This is no problem when you've got 5 cars and 25 steps. But as you add cars, you will see the system bog down. 100 cars will take 10,000 steps, and 101 cars will take 10,201 steps!</p> <p>A better approach would be to undo the nesting of the for loops.</p> <pre> for each car { add my position to a list; } for each car { give me an updated copy of the master list; } </pre> <p>With this strategy, the number of steps is a multiple of N, not of N<sup>2</sup>. <b>So 100 cars will take 100 times the work of 1 car - NOT 10,000 times the work</b>.</p> <p>This concept is sometimes expressed in "big O notation" - the number of steps needed are "big O of N" or "big O of N<sup>2</sup>."</p> <p>Note that this concept is only concerned with scalability - not optimizing the number of steps for each car. Here we don't care if it takes 5 steps or 50 steps per car - the main thing is that N cars take (X * N) steps, not (X * N<sup>2</sup>).</p>
6,265
<p>I'm writing an utility (<a href="http://reg2run.sf.net" rel="nofollow noreferrer">http://reg2run.sf.net</a>) which in case execution without arguments works as windows application (shows OpenFileDialog, etc), otherwise - as console application.</p> <p>So, in first case I don't want to show a console window, that's why project is Windows Application. But in second - I need to show it, and it's created with </p> <pre><code>if (ptrNew == IntPtr.Zero) { ptrNew = GetStdHandle(-11); } if (!AllocConsole()) { throw new ExternalCallException("AllocConsole"); } ptrNew = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, 3, 0, IntPtr.Zero); if (!SetStdHandle(-11, ptrNew)) { throw new ExternalCallException("SetStdHandle"); } StreamWriter newOut = new StreamWriter(Console.OpenStandardOutput()); newOut.AutoFlush = true; Console.SetOut(newOut); Console.SetError(newOut); </code></pre> <p>And what I want - is to grab parent process standard output and use it, if it exists (in case execution via cmd.exe or Far Manager). How can I do it?</p> <p>I tried</p> <pre><code>static Process GetParentProc() { int pidParent = 0; int pidCurrent = Process.GetCurrentProcess().Id; IntPtr hSnapshot = CreateToolhelp32Snapshot(2, 0); if (hSnapshot == IntPtr.Zero) { return null; } PROCESSENTRY32 oProcInfo = new PROCESSENTRY32(); oProcInfo.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32)); if (!Process32First(hSnapshot, ref oProcInfo)) { return null; } do { if (pidCurrent == oProcInfo.th32ProcessID) { pidParent = (int)oProcInfo.th32ParentProcessID; } } while (pidParent == 0 &amp;&amp; Process32Next(hSnapshot, ref oProcInfo)); if (pidParent &gt; 0) { return Process.GetProcessById(pidParent); } else { return null; } </code></pre> <p>and</p> <pre><code>StreamWriter newOut = GetParentProc().StandardInput; </code></pre> <p>but got InvalidOperationException: StandardIn has not been redirected. Because of</p> <pre><code>GetParentProc().StartInfo.RedirectStandardOutput = false </code></pre>
<p>There are several approaches for applications that need to choose whether to act as console or GUI applications, depending on context, on Windows:</p> <ol> <li>Have two separate applications, and have one conditionally start the other.</li> <li>A variant of the above strategy, have two applications, one called 'app.com' (i.e. just rename a console EXE with COM extension) and the other called 'app.exe', so that command-line invocations will find app.com first. Because of ancient DOS compatibility, .COM executables are found before .EXEs. (This in configurable in Windows; see the PATHEXT environment variable.)</li> <li>The rxvt/Cygwin technique, which is one I haven't really seen documented anywhere else.</li> </ol> <p>Let me go into a little bit of detail about how rxvt on Cygwin works. Rxvt is a terminal emulator that normally runs on the X Window system. Because of the limitations of the Win32 console, Cygwin packages it as a more fully-featured console, with support for things like lots of lines of history, dynamic resizing, per-instance configurable fonts and colour themes, non-application-freezing mouse select and copy, etc. In order to run natively on Windows, rxvt shipped with Cygwin includes a tiny X11 wrapper library for Win32. Rxvt on Windows is actually a console application for compatibility reasons with existing native Win32 executables, but most of the time you never see the console; you just see the rxvt terminal emulator window itself.</p> <p>The way it works is specifically implemented in <code>rxvt/W11/wrap/wrap.c</code> in the rxvt source tree, in the function called <code>hideConsole()</code>. Basically, it opens up its console (with a <code>CreateFile("CONOUT$" ...)</code>), and checks to see if the cursor position is at (0,0) (using <code>GetConsoleScreenBufferInfo()</code> on the console handle).</p> <p>If it is, then it infers that it has been started as a standalone application, rather than from a console parent application, and thus it knows the OS has created a dedicated Win32 console for the process. It proceeds to hide this console window, but it has to find it first. It uses <code>SetConsoleTitle</code> to set the console window's caption to a unique value based on the name of the application and the current thread ID. It then uses <code>FindWindow</code> to find this window's handle (periodically <code>Sleep</code>ing for a few ms if necessary for the title to change, because the console windows are actually controlled by a different process entirely in Windows). When it eventually finds the window handle, it hides it with <code>ShowWindowAsync</code>, passing in <code>SW_HIDE</code>.</p> <p>Using this approach, you can write an application that:</p> <ul> <li>if started from a console parent, it can continue to use this console</li> <li>if started as an application, it can optionally choose whether or not to hide the console</li> </ul> <p>The only downside is a very brief flash of a console window at application startup.</p>
<p>You can always the following P/Invoke method:</p> <pre><code>[DllImport("kernel32.dll")] static extern bool AttachConsole(int dwProcessId); const int ATTACH_PARENT_PROCESS = -1; </code></pre>
49,493
<p>Given two 3D vectors A and B, I need to derive a rotation matrix which rotates from A to B.</p> <p>This is what I came up with:</p> <ol> <li>Derive cosine from <strike>acos</strike>(A . B)</li> <li>Derive sine from <strike>asin</strike>(|A x B| / (|A| * |B|))</li> <li>Use A x B as axis of rotation</li> <li>Use matrix given near the bottom of <a href="http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToMatrix/index.htm" rel="nofollow noreferrer">this page</a> (axis angle)</li> </ol> <p>This works fine except for rotations of 0&deg; (which I ignore) and 180&deg; (which I treat as a special case). Is there a more graceful way to do this using the Direct3D library? I am looking for a Direct3D specific answer.</p> <p>Edit: Removed acos and asin (see <a href="https://stackoverflow.com/questions/286274/direct3d-geometry-rotation-matrix-from-two-vectors#286300">Hugh Allen's post</a>)</p>
<p>No, you're pretty much doing it the best way possible. I don't think there is a built-in DirectX function that does what you want. For step 4, you can use <a href="http://msdn.microsoft.com/en-us/library/bb205357(VS.85).aspx" rel="nofollow noreferrer"><code>D3DXMatrixRotationAxis()</code></a>. Just be careful about the edge cases, such as when |A| or |B| is zero, or when the angle is 0° or 180°.</p>
<p>Maybe you can use D3DXMatrixLookAtLH ?</p>
36,377
<p>I'm looking at building a Rails application which will have some pretty large tables with upwards of 500 million rows. To keep things snappy I'm currently looking into how a large table can be split to more manageable chunks. I see that as of MySQL 5.1 there is a partitioning option and that's a possible option but I don't like the way the column that determines the partitioning has to be part of the primary key on the table.</p> <p>What I'd really like to do is split the table that a AR model writes to based upon the values written but as far as I am aware there is no way to do this - does anyone have any suggestions as to how I might implement this or any alternative strategies?</p> <p>Thanks</p> <p>Arfon</p>
<p>Partition columns in MySQL are not limited to primary keys. In fact, a partition column does not have to be a key at all (though one will be created for it transparently). You can partition by RANGE, HASH, KEY and LIST (which is similar to RANGE only that it is a set of discrete values). Read the MySQL manual for <a href="http://dev.mysql.com/doc/refman/5.1/en/partitioning-types.html" rel="nofollow noreferrer">an overview</a> of partioning types.</p> <p>There are alternative solutions such as <a href="http://www.hscale.org/display/HSCALE/Home" rel="nofollow noreferrer">HScale</a> - a middleware plug-in that transparently partitions tables based on certain criteria. <a href="http://www.hivedb.org/" rel="nofollow noreferrer">HiveDB</a> is an open-source framework for horizontal partioning for MySQL.</p> <p>In addition to sharding and partioning you should employ some sort of clustering. The simplest setup is a replication based setup that helps you spread the load over several physical servers. You should also consider more advanced clustering solutions such as MySQL cluster (probably not an option due to the size of your database) and clustering middleware such as <a href="http://community.continuent.com/community/sequoia" rel="nofollow noreferrer">Sequioa</a>. </p> <p>I actually asked a relevant question regarding <a href="https://stackoverflow.com/questions/189903/scaling-solutions-for-mysql-replication-clustering">scaling with MySQL</a> here on stack-overflow some time ago, which I ended up answering myself several days later after collecting a lot of information on the subject. Might be relevant for you as well.</p>
<p>If you want to split your datas by time, the following solution may fit to your need. You can probably use <a href="http://dev.mysql.com/doc/refman/5.0/en/merge-storage-engine.html" rel="nofollow noreferrer" title="MERGE">MERGE</a> tables;</p> <p>Let's assume your table is called MyTable and that you need one table per week </p> <ol> <li>Your app always logs in the same table </li> <li>A weekly job atomically renames your table and recreates an empty one: MyTable is renamed to MyTable-Year-WeekNumber, and a fresh empty MyTable is created</li> <li>Merge tables are dropped and recreated.</li> </ol> <p>If you want to get all the datas of the past three months, you create a merge table which will include only the tables from the last 3 months. Create as many merge tables as you need different periods. If you can <em>not</em> include the table in which datas are currently inserted (MyTable in our example), you'll be even more happy, as you won't have any read / write concurrency </p>
41,967
<p>What I want to do is the following:</p> <ol> <li>read in multiple line input from <code>stdin</code> into variable <code>A</code></li> <li>make various operations on <code>A</code></li> <li>pipe <code>A</code> without losing delimiter symbols (<code>\n</code>,<code>\r</code>,<code>\t</code>,etc) to another command</li> </ol> <p>The current problem is that, I can't read it in with <code>read</code> command, because it stops reading at newline.</p> <p>I can read stdin with <code>cat</code>, like this:</p> <pre><code>my_var=`cat /dev/stdin` </code></pre> <p>, but then I don't know how to print it. So that the newline, tab, and other delimiters are still there.</p> <p>My sample script looks like this:</p> <pre><code>#!/usr/local/bin/bash A=`cat /dev/stdin` if [ ${#A} -eq 0 ]; then exit 0 else cat ${A} | /usr/local/sbin/nextcommand fi </code></pre>
<p>This is working for me:</p> <pre><code>myvar=`cat` echo "$myvar" </code></pre> <p>The quotes around <code>$myvar</code> are important.</p>
<p>Read can also be used setting option -d [DELIMITER], in which `input' DELIMITER is one character long. If you set <code>-read d ''</code> then it reads until null or all input.</p> <p>Just remember Bash cannot hold null bytes in variables, anyways.</p> <pre class="lang-sh prettyprint-override"><code>read -d'' myvar echo &quot;$myvar&quot; </code></pre> <p>Obs: trailing newline bytes are not preserved, though..</p>
26,172
<p>I have a trivial console application in .NET. It's just a test part of a larger application. I'd like to specify the "exit code" of my console application. How do I do this?</p>
<p>Three options:</p> <ul> <li>You can return it from <code>Main</code> if you declare your <code>Main</code> method to return <code>int</code>.</li> <li>You can call <a href="https://learn.microsoft.com/en-us/dotnet/api/system.environment.exit" rel="noreferrer"><code>Environment.Exit(code)</code></a>.</li> <li>You can set the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.environment.exitcode" rel="noreferrer">exit code</a> using properties: <code>Environment.ExitCode = -1;</code>. This will be used if nothing else sets the return code or uses one of the other options above).</li> </ul> <p>Depending on your application (console, service, web application, etc.), different methods can be used.</p>
<p>Just another way:</p> <pre><code>public static class ApplicationExitCodes { public static readonly int Failure = 1; public static readonly int Success = 0; } </code></pre>
18,826
<p>I have a large ADO.Net dataset and two database schemas (Oracle) with different constraints. The dataset will work with either schema, but I want to be able to tell the dataset which schema to use (via connection string) at runtime.</p> <p>Is that even possible?</p>
<p>In the .Net 2.0 world, you can change your connection string on your table adapters at run-time. You just have to be sure the Connnection property is public, which can be set from the dataset designer.</p>
<p>Datasets don't know what database they're pointing to -- they're just containers for data. If the dataset is filled with a data adapter, then as @Austin Salonen pointed out, you change that on the adapter side. </p>
14,761
<p>I need a collection that </p> <ul> <li>contains a set of objects linked to a double.</li> <li>The sequence of these pairs should be arbitrary set by me (based on an int I get from the database) and be static throughout the lifecycle.</li> <li>The number of entries will be small (0 ~ 20) but varying.</li> <li>The collection should be itteratable.</li> <li>I don't have to search the collection for anything.</li> <li>The double will be changed after intialization of the collection.</li> <li>I would like to work with existing datatypes (no new classes) since it will be used in my asp.net mvc controllers, views and services and I don't want them to all to have a dependency on a library just for this stupid holder class.</li> </ul> <p>I thought </p> <pre><code>IDictionary&lt;int, KeyvaluePair&lt;TheType, double&gt;&gt; </code></pre> <p>would do the trick, but then I can't set the double after init.</p> <p><strong>--Edit--</strong><br> I found out that the classes generated by the linq 2 sql visual studio thingy are actually partial classes so you can add to them whatever you want. I solved my question by adding a double field to the partial class.<br> Thanks all for the answers you came up with.</p>
<p>It sounds like you may just want an equivalent of <code>KeyValuePair</code>, but mutable. Given that you're only using it as a pair of values rather than a key-value pair, you could just do:</p> <pre><code>public class MutablePair&lt;TFirst, TSecond&gt; { public TFirst First { get; set; } public TSecond Second { get; set; } public MutablePair() { } public MutablePair(TFirst first, TSecond second) { First = first; Second = second; } } </code></pre> <p>This doesn't override GetHashCode or Equals, because you're not actually using those (as it's in a value position).</p>
<p>Well, KeyValuePair is immutable (which is a good thing), so you'll have to replace the entire value of KeyValuePair, not just the part of it:</p> <pre><code>yourDict[10] = new KeyValuePair&lt;TheType, Double&gt;(yourDict[10].Key, newValue); </code></pre> <p>... or think like <a href="https://stackoverflow.com/users/22656/jon-skeet">Jon Skeet</a>. Gah. :)</p>
39,728
<p>F# declared namespace is not available in the c# project or visible through the object browser.</p> <p>I have built a normal F# library project, but even after i build the project and reference it to my C# project, I am unable to access the desired namespace.</p> <p>I am also unable to see it in the object browser, i get an error telling me that it has not been built. I am running on the september release can someone point out my error ?</p> <p>F# Version 1.9.6.0</p> <p>(6) Edit : Referencing the dll directly has fixed my problem, referencing the project allows me to compile but the intellisence does not work. When the dll is directly referenced the intellisence works perfectly.</p> <hr> <p>This is the code found in the .fs file</p> <pre><code>#light namespace Soilsiu.Core module public Process = open System.Xml.Linq let private xname (tag:string) = XName.Get(tag) let private tagUrl (tag:XElement) = let attribute = tag.Attribute(xname "href") attribute.Value let Bookmarks(xmlFile:string) = let xml = XDocument.Load(xmlFile) xml.Elements &lt;| xname "A" |&gt; Seq.map(tagUrl) let PrintBookmarks (xmlFile:string) = let list = Bookmarks(xmlFile) list |&gt; Seq.iter(fun u -&gt; printfn "%s" u) </code></pre> <hr> <p>(5) Edit : Could ReSharper 4.0 be the problem?</p> <p>(4) Edit : When i say the Object browser is unable to read the resulting assembly, i mean that when I try to open the assembly in the object browser i get an error telling me the project has not yet been built. yet again i can read the assembly using reflector.</p> <p>(3) Edit : Reflector can Disassemble the dll but the Object Browser is unable to read it.</p> <p>(2) Edit : I have Upgraded my F# version to 1.9.6.2 and still the same consequence</p> <p>(1) Edit : I was able to Disassemble the dll to C# I get : (Everything seems to be fine here)</p> <pre><code>namespace Soilsiu.Core { [CompilationMapping(7)] public static class Crawler [CompilationMapping(7)] public static class Process } </code></pre> <hr> <pre><code>[CompilationMapping(7)] public static class Process { // Methods static Process(); public static IEnumerable&lt;string&gt; Bookmarks(string xmlFile); public static void PrintBookmarks(string xmlFile); internal static string tagUrl(XElement tag); internal static XName xname(string tag); // Nested Types [Serializable] internal class clo@13 : FastFunc&lt;XElement, string&gt; { // Methods public clo@13(); public override string Invoke(XElement tag@9); } [Serializable] internal class clo@17 : FastFunc&lt;string, Unit&gt; { // Methods public clo@17(); public override Unit Invoke(string u); } } </code></pre>
<p>What if you reference the produced DLL directly (i.e., not via a project reference, but via a file reference)?</p>
<p>Maybe IntelliSense is just messed up? What compiler error do you get when you try to use it in C#? When you say "the object browser is unable to read it" what does that mean? </p> <p>For what it's worth, I added this to a F# library project, referenced it (project) from a C# console app, and was able to use it. IntelliSense did not work at first though. (Had to rebuild.)</p> <p>If you can make a solid repro, I'd suggest emailing it to F# bugs alias (fsbugs). </p>
25,506
<pre><code>INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', 'aburton@wccs.edu') </code></pre> <p>I've got an Access table that has five fields: id, ename, position, phone, and email...each one is plain text field with 50 characters, save for position which is 255 and id which is an autoincrement field. I'm using a VB.NET to read data from an Excel table, which gets pushed into a simple class that's used to fill out that query. I do the same thing with two other tables, whose data are pulled from a DB2 table and a MySQL table through. The other two work, but this simple INSERT loop keeps failing, so I don't think it's my "InsertNoExe" function that handles all the OleDb stuff.</p> <p>So, um, does that query, any of the field titles, etc. look bogus? I can post other bits of code if anyone wants to see it.</p> <p><strong>EDIT:</strong> Fixed. I wasn't sure if the wide image counted as a Stack Overflow bug or not, which is why I left it.</p> <p><strong>EDIT 2:</strong> I'm dense. I use a try...catch to see the bogus query, and don't even check the ex.messsage. Gah.</p> <pre><code>INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', 'aburton@wccs.edu') at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object&amp; executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object&amp; executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object&amp; executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at EmployeeList.EmployeeDatabase.ExeNonQuery(String sql) in C:\andy\html\code\vb\EmployeeList\EmployeeDatabase.vb:line 263 Syntax error in INSERT INTO statement. </code></pre> <p><strong>EDIT 3:</strong> Thank you, Chris.</p>
<p>I beleive "position" is a reserved word.</p> <p>Try...</p> <p>INSERT into tblExcel (ename, [position], phone, email) VALUES (...</p> <p><a href="http://office.microsoft.com/en-us/access/HP010322491033.aspx" rel="nofollow noreferrer">Reserved Words</a></p>
<p>The spacing of "Web Developer / Network Assistant" looks a little wonky, maybe there is a hidden character in there (carriage return?)</p> <p>I'd try taking the slash out, and see if the insert works, if not try taking all punctuation out. Then add it back and maybe you will be able to identify the bug.</p>
6,907
<blockquote> <p>What's the best way to make an element of 100% minimum height across a wide range of browsers ?</p> </blockquote> <p>In particular if you have a layout with a <code>header</code> and <code>footer</code> of fixed <code>height</code>,</p> <p>how do you make the middle content part fill <code>100%</code> of the space in between with the <code>footer</code> fixed to the bottom ?</p>
<p>I am using the following one: <a href="http://www.xs4all.nl/~peterned/examples/csslayout1.html" rel="noreferrer">CSS Layout - 100 % height</a></p> <blockquote> <p><strong>Min-height</strong></p> <p>The #container element of this page has a min-height of 100%. That way, if the content requires more height than the viewport provides, the height of #content forces #container to become longer as well. Possible columns in #content can then be visualised with a background image on #container; divs are not table cells, and you don't need (or want) the physical elements to create such a visual effect. If you're not yet convinced; think wobbly lines and gradients instead of straight lines and simple color schemes. </p> <p><strong>Relative positioning</strong></p> <p>Because #container has a relative position, #footer will always remain at its bottom; since the min-height mentioned above does not prevent #container from scaling, this will work even if (or rather especially when) #content forces #container to become longer. </p> <p><strong>Padding-bottom</strong></p> <p>Since it is no longer in the normal flow, padding-bottom of #content now provides the space for the absolute #footer. This padding is included in the scrolled height by default, so that the footer will never overlap the above content.</p> <p>Scale the text size a bit or resize your browser window to test this layout. </p> </blockquote> <pre class="lang-css prettyprint-override"><code>html,body { margin:0; padding:0; height:100%; /* needed for container min-height */ background:gray; font-family:arial,sans-serif; font-size:small; color:#666; } h1 { font:1.5em georgia,serif; margin:0.5em 0; } h2 { font:1.25em georgia,serif; margin:0 0 0.5em; } h1, h2, a { color:orange; } p { line-height:1.5; margin:0 0 1em; } div#container { position:relative; /* needed for footer positioning*/ margin:0 auto; /* center, not in IE5 */ width:750px; background:#f0f0f0; height:auto !important; /* real browsers */ height:100%; /* IE6: treaded as min-height*/ min-height:100%; /* real browsers */ } div#header { padding:1em; background:#ddd url("../csslayout.gif") 98% 10px no-repeat; border-bottom:6px double gray; } div#header p { font-style:italic; font-size:1.1em; margin:0; } div#content { padding:1em 1em 5em; /* bottom padding for footer */ } div#content p { text-align:justify; padding:0 1em; } div#footer { position:absolute; width:100%; bottom:0; /* stick to bottom */ background:#ddd; border-top:6px double gray; } div#footer p { padding:1em; margin:0; } </code></pre> <p>Works fine for me.</p>
<p>just share what i've been used, and works nicely</p> <pre><code>#content{ height: auto; min-height:350px; } </code></pre>
4,486
<p>I have some markup for a popup menu that works in firefox but not IE. The problem is that the popup pops under other elements and is impervious to the z-index value. A complete runnable example is below.</p> <p>Now, I know that one fix is not to position the divs as relative, but I can't do that because, in the real code, I'm using scriptaculous and it adds the "position: relative" to do what it needs to do. Besides, I don't think it should matter.</p> <p>Is there another fix that would make this code work for both IE and firefox?</p> <p>Example: </p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt;&lt;title&gt;IE Problem&lt;/title&gt; &lt;style type="text/css"&gt; .mydiv{ position: relative; background: yellow; border: solid 1px black; } table{background:black;} td.menu{background:lightblue} table.menu { position:absolute; visibility:hidden; z-index:999; } &lt;/style&gt; &lt;script type="text/javascript"&gt; function showmenu(elmnt){ document.getElementById(elmnt).style.visibility="visible"; } function hidemenu(elmnt){ document.getElementById(elmnt).style.visibility="hidden"; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="mydiv" onmouseover="showmenu('one')" onmouseout="hidemenu('one')"&gt; &lt;a href="#"&gt;div one&lt;/a&gt;&lt;br /&gt; &lt;table class="menu" id="one" width="120"&gt; &lt;tr&gt;&lt;td class="menu"&gt;&lt;a href="#"&gt;Item 1&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td class="menu"&gt;&lt;a href="#"&gt;Item 2&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;div class="mydiv" onmouseover="showmenu('two')" onmouseout="hidemenu('two')"&gt; &lt;a href="#"&gt;div two&lt;/a&gt;&lt;br /&gt; &lt;table class="menu" id="two" width="120"&gt; &lt;tr&gt;&lt;td class="menu"&gt;&lt;a href="#"&gt;Item 1&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td class="menu"&gt;&lt;a href="#"&gt;Item 2&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>The z-index is scoped to within the parent if the parent has position: relative or position: absolute.</p> <p>The solution for your example is to add style="z-index: 2;" to the first "mydiv" and z-index: 1; to the second.</p>
<p>If you move the TABLEs outside of the DIVs it works. Hopefully this satisfies your needs? I think I would get confused too if I was a DIV and you asked me to Z-order something I am containing above me.</p>
40,342
<p>I am writing an application where all the request to the internet should go from it like in firewall. so that i can block the request for a particular website. In my case the program will be running on the same machine. I have tried the promiscous method but using that we can only capture all the packets comming and going from the machine,</p>
<p>You have to insert your code in the TCP/IP stack, which, if I understand correctly, requires a windows driver.</p> <p>C# cannot compile native windows drivers, so you'll need to use a library or DLL to implement at least part of your functionality. Look for solutions using C++.</p> <p>-Adam</p>
<p>You have to insert your code in the TCP/IP stack, which, if I understand correctly, requires a windows driver.</p> <p>C# cannot compile native windows drivers, so you'll need to use a library or DLL to implement at least part of your functionality. Look for solutions using C++.</p> <p>-Adam</p>
40,875
<p><em>This is a shameless information gathering exercise for my own book.</em></p> <p>One of the talks I give in the community is an introduction to web site vulnerabilities. Usually during the talk I can see at least two members of the audience go very pale; and this is basic stuff, Cross Site Scripting, SQL Injection, Information Leakage, Cross Site Form Requests and so on.</p> <p>So, if you can think back to being one, as a beginning web developer (be it ASP.NET or not) what do you feel would be useful information about web security and how to develop securely? I will already be covering the <a href="http://www.owasp.org/index.php/OWASP_Top_Ten_Project" rel="nofollow noreferrer">OWASP Top Ten</a></p> <p>(And yes this means stackoverflow will be in the acknowledgements list if someone comes up with something I haven't thought of yet!)</p> <p><em>It's all done now, and published, thank you all for your responses</em></p>
<p>First, I would point out the insecurities of the web in a way that makes them accesible to people for whom developing with security in mind may (unfortunately) be a new concept. For example, show them how to intercept an HTTP header and implement an XSS attack. The reason you want to show them the attacks is so they themselves have a better idea of what they're defending against. Talking about security beyond that is great, but without understanding the type of attack they're meant to thwart, it will be hard for them to accurately "test" their systems for security. Once they can test for security by trying to intercept messages, spoof headers, etc. then they at least know if whatever security they're trying to implement is working or not. You can teach them whatever methods you want for implementing that security with confidence, knowing if they get it wrong, they will actually know about it because it will fail the security tests you showed them to try.</p>
<p><a href="http://poignantguide.net/ruby/chapter-3.html" rel="nofollow noreferrer">Foxes</a></p>
13,458
<p>I need to cache a single page. I've used ActionController's caches_page for this. But now, I'd like to expire AND regenerate it once in every 10 minutes. What are my options?</p> <p>later: I'd like to not use any external tools for this, like cron. The important point is <strong>interval-based</strong> expiry of the cache. </p>
<p>You can also use <a href="http://code.google.com/p/timedcachedfragment/" rel="nofollow noreferrer">this</a> if you want to have fragments timeout.</p>
<p>AFAIK rails page caching compares the cache time on request and regenerates if necessary. If you need to forcibly flush that cache check out Sweepers. <a href="http://www.railsenvy.com/2007/2/28/rails-caching-tutorial#sweepers" rel="nofollow noreferrer">http://www.railsenvy.com/2007/2/28/rails-caching-tutorial#sweepers</a></p>
13,614
<p>Using the SharePoint API, how can I modify an extended webapp web.config file?</p> <p>I have to do some changes in this file to specify the connection string, membershipprovider, etc... for using Forms Authentication.</p> <p>Currently, I can change the &quot;master&quot; webapplication web.config file, but not the extended one.</p> <blockquote> <p>Edited</p> <p>I'm using Sp 2007. I'm already using SPWebConfigModification class to modify the parent webapp. Thoses modifications are propagated to the extended webapp. I have to change ONLY the extended one. But I don't find the way to do it.</p> <p>What I'm trying to achieve, is to program a little wizard that:</p> <ul> <li>Shows a WebApp list so the user can select one</li> <li>Extend that selected webapp to a different zone</li> <li>Configure that extended zone to use Forms Authentication</li> </ul> </blockquote> <p>Thanks</p>
<p>I got an answer form a blog.</p> <blockquote> <p>In your case , you need to write a Web Application scoped feature which after you provision your site using your C# app, it is deployed to the newly-provisioned site and in the receiver of the feature you inject the required web.config settings because in that context configuration API is obtainable , but again bear the following in mind:</p> <p>If you don’t use SPWebConfigModification class and either use ASP.NET 2.0 configuration API or your own mechanism , propagating changes across the farm is YOUR RESPONSIBILITY. If this happens on an standalone installation then you don;t need to be worried about this.</p> </blockquote> <p>So it cannot be done externally. We have to do a feature in order to acheve this.</p> <p>Thanks</p>
<p>Quick answer: look into the SPWebConfigModification class. I am assuming you're using SharePoint 2007. The best way to learn about this is to dig into open source projects:</p> <p>Google code search: <a href="http://www.google.com/codesearch?q=spwebconfigmodification&amp;hl=en&amp;btnG=Search+Code" rel="nofollow noreferrer">http://www.google.com/codesearch?q=spwebconfigmodification&amp;hl=en&amp;btnG=Search+Code</a> This project on CodePlex looks like it's one big SPWebConfigModification: <a href="http://www.codeplex.com/ajaxifymoss/Release/ProjectReleases.aspx?ReleaseId=13360" rel="nofollow noreferrer">http://www.codeplex.com/ajaxifymoss/Release/ProjectReleases.aspx?ReleaseId=13360</a></p>
22,279
<p>Is there any C#/F# performance comparison available on web to show proper usage of new F# language?</p>
<p>Natural F# code (e.g. functional/immutable) is slower than natural (imperative/mutable object-oriented) C# code. However, this kind of F# is much shorter than usual C# code. Obviously, there is a trade-off.</p> <p>On the other hand, you can, in most cases, achieve performance of F# code equal to performance of C# code. This will usually require coding in imperative or mutable object-oriented style, profile and remove bottlenecks. You use that same tools that you would otherwise use in C#: e.g. .Net reflector and a profiler.</p> <p>That having said, it pays to be aware of some high-productivity constructs in F# that decrease performance. In my experience I have seen the following cases:</p> <ul> <li><p>references (vs. class instance variables), only in code executed billions of times</p></li> <li><p>F# comparison (&lt;=) vs. System.Collections.Generic.Comparer, for example in binary search or sort</p></li> <li><p>tail calls -- only in certain cases that cannot be optimized by the compiler or .Net runtime. As noted in the comments, depends on the .Net runtime.</p></li> <li><p>F# sequences are twice slower than LINQ. This is due to references and the use of functions in F# library to implement translation of seq&lt;_>. This is easily fixable, as you might replace the Seq module, by one with same signatures that uses Linq, PLinq or DryadLinq.</p></li> <li><p>Tuples, F# tuple is a class sorted on the heap. In some case, e.g. a int*int tuple it might pay to use a struct.</p></li> <li><p>Allocations, it's worth remembering that a closure is a class, created with the new operator, which remembers the accessed variables. It might be worth to "lift" the closure out, or replaced it with a function that explicitly takes the accessed variables as arguments. </p></li> <li><p>Try using inline to improve performance, especially for generic code.</p></li> </ul> <p>My experience is to code in F# first and optimize only the parts that matter. In certain cases, it might be easier to write the slow functions in C# rather that to try to tweak F#. However, from programmer efficiency point of view makes sense to start/prototype in F# then profile, disassemble and optimize. </p> <p>Bottom line is, your F# code might end-up slower than C# because of program design decisions, but ultimately efficiency can be obtained.</p>
<p>Here are a few links on (or related to) this topic:</p> <ul> <li><a href="http://cs.hubfs.net/forums/thread/3207.aspx" rel="noreferrer">http://cs.hubfs.net/forums/thread/3207.aspx</a></li> <li><a href="http://strangelights.com/blog/archive/2007/06/17/1588.aspx" rel="noreferrer">http://strangelights.com/blog/archive/2007/06/17/1588.aspx</a></li> <li><a href="http://khigia.wordpress.com/2008/03/30/ocaml-vs-f-for-big-integer-surprising-performance-test/" rel="noreferrer">http://khigia.wordpress.com/2008/03/30/ocaml-vs-f-for-big-integer-surprising-performance-test/</a></li> <li><a href="http://cs.hubfs.net/blogs/f_team/archive/2006/08/15/506.aspx" rel="noreferrer">http://cs.hubfs.net/blogs/f_team/archive/2006/08/15/506.aspx</a></li> <li><a href="http://blogs.msdn.com/jomo_fisher/" rel="noreferrer">http://blogs.msdn.com/jomo_fisher/</a></li> </ul> <p>What I seem to remember from another post on Robert Pickering's blog (or was it Scott Hanselman?) that in the end, because both are sitting on the same framework, you <em>can</em> get the same performance from both, but you sometimes have to 'twist' the natural expression of the language to do so. In the example I recall, he had to twist F# to get comparable performance with C#...</p>
17,396
<p>sorry but I do not have the actual code with me, but I will try to explain:</p> <p>I have a servlet mapped to the following: </p> <pre><code>/admin/* </code></pre> <p>So, this goes to a servlet: </p> <pre><code>public class AdminController extends MainController { public void doPost(HttpServletRequest request, HttpServletResponse response) { // Do stuf here } } </code></pre> <p>Here is MainController:</p> <pre><code>public class MainController extends HttpServlet { @Override public void service(ServletRequest request, ServletResponse response) { String requesturi = ((HttpServletRequest)request).getRequestURI(); reqlist = Arrays.asList(requesturi.substring(requesturi.indexOf(Util.rootPath) + Util.rootPath.length()).split("/")); reqlist = reqlist.subList(1, reqlist.size()); doPost((HttpServletRequest)request, (HttpServletResponse)response); } </code></pre> <p>So, the request is passed to AdminController, no problem, but then I reallized something: </p> <p><b>The servlet is being called twice!</b>. And this is causing me many errors.. </p> <p>Does anybody have a clue on this? It is because I used some kind of heritance? Thank you for all!</p>
<p>The <a href="http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/http/HttpServlet.html#service(javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse)" rel="noreferrer">HttpServlet.service</a> method gets called for all request types and what you are seeing is a HEAD request and then a GET or POST request. Instead of implementing service just implement doGet or doPost. What is commonly done is to just implement one of doPost or doGet and then call the other from the one you don't have an implementation for.</p>
<p>Had the same issue, and I tried anything mentioned above and on other posts, but the issue was only on local.</p> <p>If nothing works for you too, try a deploy :)</p>
41,765
<p>I was thinking along the lines of using <code>typeid()</code> but I don't know how to ask if that type is a subclass of another class (which, by the way, is abstract)</p>
<p>You really shouldn't. If your program needs to know what class an object is, that usually indicates a design flaw. See if you can get the behavior you want using virtual functions. Also, more information about what you are trying to do would help.</p> <p>I am assuming you have a situation like this:</p> <pre><code>class Base; class A : public Base {...}; class B : public Base {...}; void foo(Base *p) { if(/* p is A */) /* do X */ else /* do Y */ } </code></pre> <p>If this is what you have, then try to do something like this:</p> <pre><code>class Base { virtual void bar() = 0; }; class A : public Base { void bar() {/* do X */} }; class B : public Base { void bar() {/* do Y */} }; void foo(Base *p) { p-&gt;bar(); } </code></pre> <p><strong>Edit:</strong> Since the debate about this answer still goes on after so many years, I thought I should throw in some references. If you have a pointer or reference to a base class, and your code needs to know the derived class of the object, then it violates <a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="noreferrer">Liskov substitution principle</a>. <a href="http://www.objectmentor.com/omTeam/martin_r.html" rel="noreferrer">Uncle Bob</a> calls this an "<a href="http://www.objectmentor.com/resources/articles/lsp.pdf" rel="noreferrer">anathema to Object Oriented Design</a>".</p>
<p>In c# you can simply say:</p> <pre><code>if (myObj is Car) { } </code></pre>
39,624
<p>Once a user starts a session (or logs in, for a registered user, to associate over multiple sessions), their specific page views are followed. The data can then be used in a number of ways from targeted advertisements to email updates to often-visited sections of the site.</p> <p>Would this be wrong, as long as this was noted in the Privacy Policy and such?</p>
<p>There are certainly legal and moral ways to do something like this. However, I think that the biggest issue with something like this is more of a marketing issue. </p> <p>There's a fine but important line between something like Google's targeted text ads (which I don't find intrusive) and things like popups, animated banner ads, etc. Similarly, there's not too big a difference between very targeted email updates (e.g., a "Please email me if this page is updated" box) and spammy updates (e.g., "You've used our site and we added this feature you may or may not care about!")</p> <p>If you use the data you collect on customers/visitors sparingly and tactfully (especially making as much of it opt-in as possible), it should probably be fine and you won't annoy your potential repeat visitors.</p>
<p>By tracking page views, you're only recording information they could reasonably expect you to anyway (it's in the weblogs anyway). What you do with that information, how you protect it, and whether you choose to anonymise it in some way are all more subjective questions, and should be clearly answered in your privacy policy.</p> <p>IANAL, but if you want to contact someone at all, they should be given the choice to opt-out, and even if they don't opt out, the communications should be limited to things you could reasonably expect them to have an interest in (which may be based on page views, purchases, general site theme, whatever).</p> <p>Opt-In gives you much wider range in what you can send them, since there's a much smaller chance that they just missed the opt-out.</p> <p>I would pick a policy you think is reasonable, and ask a couple of co-workers if they would be happy with that policy. If they agree (and you've checked with the lawyers), make it clear in the privacy policy and go ahead.</p>
23,419
<p>My Cocoa app needs some small dynamically generated windows. How can I programmatically create Cocoa windows at runtime?</p> <p>This is my non-working attempt so far. I see no result whatsoever.</p> <pre><code>NSRect frame = NSMakeRect(0, 0, 200, 200); NSUInteger styleMask = NSBorderlessWindowMask; NSRect rect = [NSWindow contentRectForFrameRect:frame styleMask:styleMask]; NSWindow * window = [[NSWindow alloc] initWithContentRect:rect styleMask:styleMask backing: NSBackingStoreRetained defer:false]; [window setBackgroundColor:[NSColor blueColor]]; [window display]; </code></pre>
<p>The problem is that you don't want to call <code>display</code>, you want to call either <code>makeKeyAndOrderFront</code> or <code>orderFront</code> depending on whether or not you want the window to become the key window. You should also probably use <code>NSBackingStoreBuffered</code>.</p> <p>This code will create your borderless, blue window at the bottom left of the screen:</p> <pre><code>NSRect frame = NSMakeRect(0, 0, 200, 200); NSWindow* window = [[[NSWindow alloc] initWithContentRect:frame styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO] autorelease]; [window setBackgroundColor:[NSColor blueColor]]; [window makeKeyAndOrderFront:NSApp]; //Don't forget to assign window to a strong/retaining property! //Under ARC, not doing so will cause it to disappear immediately; // without ARC, the window will be leaked. </code></pre> <p>You can make the sender for <code>makeKeyAndOrderFront</code> or <code>orderFront</code> whatever is appropriate for your situation.</p>
<p>This is what I've come up with myself:</p> <pre><code>NSRect frame = NSMakeRect(100, 100, 200, 200); NSUInteger styleMask = NSBorderlessWindowMask; NSRect rect = [NSWindow contentRectForFrameRect:frame styleMask:styleMask]; NSWindow * window = [[NSWindow alloc] initWithContentRect:rect styleMask:styleMask backing: NSBackingStoreBuffered defer:false]; [window setBackgroundColor:[NSColor blueColor]]; [window makeKeyAndOrderFront: window]; </code></pre> <p>This displays a blue window. I hope this is the optimal approach.</p>
40,536
<p>I have some code that looks like:</p> <pre><code>template&lt;unsigned int A, unsigned int B&gt; int foo() { int v = 1; const int x = A - B; if (x &gt; 0) { v = v &lt;&lt; x; } bar(v); } </code></pre> <p>gcc will complain about x being negative for certain instantiations of A, B; however, I do perform a check to make sure it is non-negative. What's the best way around this? I know I can cast <code>x</code> to be <code>unsigned int</code> but that will cause warnings about <code>x</code> being larger than the width of <code>v</code> (since it is casting a negative number to be positive). I know there is a work-around that involves creating a new templatized <code>shift</code> function, but I'd like to avoid that if possible.</p>
<p>Since A and B are known at compile time, not only can you get rid of your warning, but you can also get rid of a runtime <code>if</code>, without any casts, like this:</p> <pre><code>#include &lt;iostream&gt; using namespace std; template&lt; unsigned int A, unsigned int B &gt; struct my { template&lt; bool P &gt; static void shift_if( int &amp; ); template&lt;&gt; static void shift_if&lt; false &gt;( int &amp; ) {} template&lt;&gt; static void shift_if&lt; true &gt;( int &amp; v ) { v &lt;&lt;= A - B; } static void op( int &amp; v ) { shift_if&lt; (A &gt; B) &gt;( v ); } }; template&lt; unsigned int A, unsigned int B &gt; int foo() { int v = 1; my&lt; A, B &gt;::op( v ); return v; } int main() { cout &lt;&lt; foo&lt; 1, 3 &gt;() &lt;&lt; endl; cout &lt;&lt; foo&lt; 3, 1 &gt;() &lt;&lt; endl; cout &lt;&lt; foo&lt; 300, 1 &gt;() &lt;&lt; endl; cout &lt;&lt; foo&lt; 25, 31 &gt;() &lt;&lt; endl; return 0; } </code></pre>
<p>Would this work?</p> <pre><code>const short unsigned int x = A - B; </code></pre> <p>It's cutting off a lot more bits than need to be cut off, but if your values of A - B are small enough...</p>
33,518
<p>I'm looking for pseudocode, or sample code, to convert higher bit ascii characters (like, Ü which is extended ascii 154) into U (which is ascii 85).</p> <p>My initial guess is that since there are only about 25 ascii characters that are similar to 7bit ascii characters, a translation array would have to be used.</p> <p>Let me know if you can think of anything else.</p>
<p>For .NET users the <a href="http://www.codeproject.com/Articles/13503/Stripping-Accents-from-Latin-Characters-A-Foray-in" rel="noreferrer">article in CodeProject</a> (thanks to <a href="https://stackoverflow.com/a/183540/562906">GvS's tip</a>) does indeed answer the question more correctly than any other I've seen so far.</p> <p>However the code in that article (in solution #1) is cumbersome. Here's a compact version:</p> <pre><code>// Based on http://www.codeproject.com/Articles/13503/Stripping-Accents-from-Latin-Characters-A-Foray-in private static string LatinToAscii(string inString) { var newStringBuilder = new StringBuilder(); newStringBuilder.Append(inString.Normalize(NormalizationForm.FormKD) .Where(x =&gt; x &lt; 128) .ToArray()); return newStringBuilder.ToString(); } </code></pre> <hr> <p>To expand a bit on the answer, this method uses <a href="http://msdn.microsoft.com/en-us/library/ebza6ck1.aspx" rel="noreferrer">String.Normalize</a> which:</p> <blockquote> <p>Returns a new string whose textual value is the same as this string, but whose binary representation is in the specified Unicode normalization form.</p> </blockquote> <p>Specifically in this case we use the <a href="http://msdn.microsoft.com/en-us/library/system.text.normalizationform.aspx" rel="noreferrer">NormalizationForm</a> <code>FormKD</code>, described in those same MSDN docs as such:</p> <blockquote> <p>FormKD - Indicates that a Unicode string is normalized using full compatibility decomposition.</p> </blockquote> <p>For more information about unicode normalization forms, see <a href="http://www.unicode.org/reports/tr15/" rel="noreferrer">Unicode Annex #15</a>.</p>
<p>Try the <a href="http://billposer.org/Software/uni2ascii.html" rel="nofollow noreferrer">uni2ascii</a> program.</p>
16,981
<p>In one of the answers to <a href="https://stackoverflow.com/questions/31572/broadcast-like-udp-with-the-reliability-of-tcp#31629">Broadcast like UDP with the Reliability of TCP</a>, a user mentions the <a href="http://spread.org" rel="noreferrer">Spread</a> messaging API. I've also run across one called <a href="http://zeromq.org" rel="noreferrer">ØMQ</a>. I also have some familiarity with <a href="http://www-unix.mcs.anl.gov/mpi/" rel="noreferrer">MPI</a>. </p> <p>So, my main question is: why would I choose one over the other? More specifically, why would I choose to use Spread or ØMQ when there are mature implementations of MPI to be had?</p>
<p>MPI was deisgned tightly-coupled compute clusters with fast, reliable networks. Spread and ØMQ are designed for large distributed systems. If you're designing a parallel scientific application, go with MPI, but if you are designing a persistent distributed system that needs to be resilient to faults and network instability, use one of the others.</p> <p>MPI has very limited facilities for fault tolerance; the default error handling behavior in most implementations is a system-wide fail. Also, the semantics of MPI require that all messages sent eventually be consumed. This makes a lot of sense for simulations on a cluster, but not for a distributed application.</p>
<p>You're addressing very different APIs here, with different notions about the kind of services provided and infrastructure for each of them. I don't know enough about MPI and Spread to answer for them, but I can help a little more with ZeroMQ.</p> <p>ZeroMQ is a simple messaging communication library. It does nothing else than send a message to different peers (including local ones) based on a restricted set of common messaging patterns (PUSH/PULL, REQUEST/REPLY, PUB/SUB, etc.). It handles client connection, retrieval, and basic congestion strictly based on those patterns and you have to do the rest yourself. </p> <p>Although appearing very restricted, this simple behavior is mostly what you would need for the communication layer of your application. It lets you scale very quickly from a simple prototype, all in memory, to more complex distributed applications in various environments, using simple proxies and gateways between nodes. However, don't expect it to do node deployment, network discovery, or server monitoring; You will have to do it yourself.</p> <p>Briefly, use zeromq if you have an application that you want to scale from the simple multithread process to a distributed and variable environment, or that you want to experiment and prototype quickly and that no solutions seems to fit with your model. Expect however to have to put some effort on the deployment and monitoring of your network if you want to scale to a very large cluster.</p>
5,598
<p>What is the proper way for an MFC application to cleanly close itself?</p>
<p>Programatically Terminate an MFC Application</p> <pre><code> void ExitMFCApp() { // same as double-clicking on main window close box ASSERT(AfxGetMainWnd() != NULL); AfxGetMainWnd()-&gt;SendMessage(WM_CLOSE); } </code></pre> <p><a href="http://support.microsoft.com/kb/117320">http://support.microsoft.com/kb/117320</a></p>
<p>If it is a dialog based application you can do it by calling EndDialog() function.</p> <p>If it is an SDI/MDI based application you can call DestroyWindow. But before which you will need to do the cleanup yourself (closing documents, deallocating memory and resources, destroying any additional windows created etc).</p>
3,530
<p>Was just wondering if there was a way to edit the CPU registers (i.e. EAX, EBX, ECX, etc) or flags (OV, UP, erc) from within the Visual Studio IDE. I know you can <strong>view</strong> them using the Registers pane (ctrl-shift-G) and you can cycle through them with TAB or ENTER, but I don't seem to be able to change any of them while debugging (yes, program execution is halted :)).</p> <p>I don't really have a strong need to do so, it's just that: I can see the assembly... I used to be able to do this (VC++6)... why can't I now, kind'a thing!</p> <p>Thanks!</p>
<p>yes, you can....</p> <p>from the help (you know...the f1 key)</p> <p>To change the value of a register </p> <ul> <li>In the Registers window, use the TAB key or the mouse to move the insertion point to the value you want to change. When you start to type, the cursor must be located in front of the value you want to overwrite. </li> <li>Type the new value. </li> <li>Press ENTER. </li> </ul>
<p>No you can't. That awful thing doesn't work in managed mode or mixed mode.</p>
30,387
<p>In VB6, I have a DTPicker control on a form. (The DTPicker is the calendar date/time selector, included in Microsoft Windows Common Controls-2 6.0, available from the Components dialog.)</p> <p>While there are many properties to affect the colors of the calendar when it's dropped down, there is no property that allows changing the color of the date that's displayed in the textbox. I'm looking for something like the standard TextBox's ForeColor property.</p> <p>Does anyone have a little API magic to allow me to simulate that property?</p>
<p>Pipes aren't a particular security risk in Windows. If you're worried about security, make sure you set the security descriptor on the pipe to an appropriate DACL. If your usage requires that the pipe is open for anyone to connect to, then you have to treat the incoming data as suspicious, just like any file or network input.</p>
<p>If you are concerned about network sniffing, I suppose they could be since I don't think that pipes between systems are encrypted. I don't know exactly how they are implemented in Windows, but I would expect that pipes between processes/threads on the same machine would be implemented with shared memory and not let traffic leak outside the box. If you need secure communication between systems, I'd go with secure sockets.</p>
28,992
<p>I am trying to use reflector.InvokeMethod to invoke a function with an optional parameter. The function looks like this: </p> <pre><code>Private Function DoSomeStuff(ByVal blah1 as string, ByVal blah2 as string, Optional ByVal blah3 as string = "45") as boolean 'stuff end function </code></pre> <p>and I'm Invoking it like this:</p> <pre><code>Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2, Param3) </code></pre> <p>This works fine, other than when I don't pass the third (optional) parameter, it dosn't hit the function.</p> <pre><code>Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2) </code></pre> <p>Is there a way I can use Reflector.invokeMethod to call this function without passing the optional parameter? or another way to achieve this?</p>
<p>The Visual Basic compiler actually substitutes the optional parameter values into the calling code. So if your actual code was:</p> <pre><code>DoSomeStuff(blah1, blah2)</code></pre> <p>Visual Basic would have emitted IL code equivalent to:</p> <pre><code>DoSomeStuff(blah1, blah2, "45")</code></pre> <p>To know what that last parameter is, you'll need to get a reference to the parameter's object (I'm not sure what that is in Reflector - in .NET you'd get access to the MethodInfo and then to the ParameterInfo), then get its custom attributes, looking for an attribute marked with OptionalAttribute and DefaultParameterValueAttribute. Then, you'll need to call it with the third parameter, supplying the value from DefaultParameterValueAttribute. </p>
<p>I would overload the <strong>DoSomeStuff</strong> method rather than use an optional parameter...</p> <pre><code>Private Overloads Function DoSomeStuff(ByVal blah1 As String, ByVal blah2 As String) As Boolean Return DoSomeStuff(blah1, blah2, "45") End Function Private Overloads Function DoSomeStuff(ByVal blah1 As String, ByVal blah2 As String, ByVal blah3 As String) As Boolean 'stuff End Function </code></pre>
31,433
<p>We're trying to track down some .Net assembly dependency problems.</p> <p>On Windows XP, does the .Net 3.5 installer include 3.0 SP2 automatically?</p>
<p>.NET 3.5 contains .NET 3.0 SP1</p> <p>.NET 3.5 SP1 contains .NET 3.0 SP2</p>
<p>I'm not sure but I believe that Microsoft is building on top of each version of .NET. This leads me to <em>believe</em> the answer to your question is '<strong>Yes</strong>'. Hopefully someone can confirm this.</p>
37,122
<p>I created an <code>ObjectInputSteam</code> and <code>ObjectOutputStream</code> on a blocking <code>SocketChannel</code> and am trying to read and write concurrently. My code is something like this:</p> <pre><code>socketChannel = SocketChannel.open(destNode); objectOutputStream = new ObjectOutputStream(Channels.newOutputStream(socketChannel)); objectInputStream = new ObjectInputStream(Channels.newInputStream(socketChannel)); Thread replyThread = new Thread("SendRunnable-ReplyThread") { @Override public void run() { try { byte reply = objectInputStream.readByte();//(A) //..process reply } catch (Throwable e) { logger.warn("Problem reading receive reply.", e); } } }; replyThread.start(); objectOutputStream.writeObject(someObject);//(B) //..more writing </code></pre> <p>Problem is the write at line (B) blocks until the read at line (A) completes (blocks on the object returned by <code>SelectableChannel#blockingLock()</code> ). But app logic dictates that the read will not complete until all the writes complete, so we have an effective deadlock.</p> <p><code>SocketChannel</code> javadocs say that concurrent reads and writes are supported.</p> <p>I experienced no such problem when I tried a regular Socket solution:</p> <pre><code>Socket socket = new Socket(); socket.connect(destNode); final OutputStream outputStream = socket.getOutputStream(); objectOutputStream = new ObjectOutputStream(outputStream); objectInputStream = new ObjectInputStream(socket.getInputStream()); </code></pre> <p>However, then I cannot take advantage of the performance benefits of <code>FileChannel#transferTo(...)</code></p>
<p>This seems to be a bug in <code>java.nio.channels.Channels</code> (thanks to Tom Hawtin; post it as an answer next time). A good description and workaround are described <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4774871" rel="noreferrer">here</a> (actually a duplicate of the bug Tom listed):</p> <p>I tested the workaround and it works.</p>
<p>Interesting bug! You say though that you can't use FileChannel#transferTo. How about wrapping the I/O streams of the non-NIO socket into channels using Channesl#newChannel before passing to FileChannel#transferTo?</p>
21,069
<p>This is probably a no brainer but... </p> <p>I've just opened a solution in VS2008 and for some reason the compiler doesn't recognised previously compiled errors.</p> <p>I hit build and I get 100s of errors :</p> <p><code>Name 'IIf' is not declared.<br> Name 'IsNumeric' is not declared.<br> Name HttpUtility is not declared</code></p> <p>etc..</p> <p>Think this must be something to do with VS2008 going wrong as it builds on my colleagues machine and some of the files have not changed since in source control. The Imports were not in the previous version. </p> <p>How can I make this build without adding the imports in manually?</p>
<p>Check your references. Sometimes they seem to break if you have been messing around at all.</p>
<p>Those appear to be in the VisualBasic namespace.</p> <p>Right Click on Project Choose Properties-->References Try adding the import Microsoft.VisualBasic.</p>
33,315
<p>I know that -applicationWillResignActive gets called upon an incoming call, but is there a standard method that gets called if the user hits the "exit" button (the only button on the front of the iPhone)? </p>
<p><code>- (void)applicationWillTerminate:(UIApplication *)application</code>, in UIApplicationDelegate protocol.</p>
<p>I made some try and i'm using iPhone SDK 4, and when you press the "exit" button the app called two methods:</p> <pre><code>(void)applicationWillResignActive:(UIApplication *)application (void)applicationDidEnterBackground:(UIApplication *)application </code></pre>
47,590
<p>I have some really complicated legacy code I've been working on that crashes when collecting big chunks of data. I've been unable to find the exact reason for the crashes and am trying different ways to solve it or at least recover nicely. The last thing I did was enclose the crashing code in a</p> <pre><code>try ... except cleanup(); end; </code></pre> <p>just to make it behave. But the cleanup never gets done. Under what circumstances does an exception not get caught? This might be due to some memory overflow or something since the app is collecting quite a bit of data.</p> <p>Oh and the exception I got before adding the <code>try</code> was "Access violation" (what else?) and the CPU window points to very low addresses. Any ideas or pointers would be much appreciated!</p>
<p>"Very low address" probably means that somebody tried to call a virtual method on an object that was not really there (i.e. was 'nil'). For example:</p> <p>TStringList(nil).Clear;</p> <p>The first part is very mysterious, though. I have no idea how that can happen.</p> <p>I think you should try to catch that exception with <a href="http://www.madshi.net/madExceptDescription.htm" rel="nofollow noreferrer">madExcept</a>. It has never failed me yet. (Disclaimer: I am not using D7.)</p>
<p>Is this perhaps a DLL or a COM object? If so, it is possible that the FPUExcpetion mask is being set by the host application to something different than Delphi is used to. An overflow, by default in Delphi produces an exception, but the FPUExcpetionmask can be set so that it doesn't, and the value is set to NAN. See the math.pas unit for more information on FPUExceptionmask </p>
22,600
<p>I really like Entity Framework, but there are some key pieces that are a challenge to me. Can anyone tell me how to filter an EntityDataSource on an Association column? EF hides the FK values and instead has an Association property. Given an Entity, Person, with a PersonType association, I would have expected something like this to work if I want to filter my Person Entity by Type:</p> <pre><code>GridDataSource.EntityTypeFilter = "it.PersonType.PersonTypeID = 1"; </code></pre> <p>or</p> <pre><code>GridDataSource.Where = "it.PersonType.PersonTypeID = '1'"; </code></pre> <p>or even</p> <pre><code>GridDataSource.WhereParameters.Add(new Parameter("it.PersonType.PersonTypeID", DbType.Object, "1")); </code></pre> <p>but none of those work. Anybody know how to do this?</p>
<p>I think the answer you're looking for involves using the Include method, such as:</p> <pre><code>entities.it.Include("PersonType").Where(a =&gt; a.PersonType.PersonTypeID = '1'); </code></pre>
<p>Have you tried applying the filter in memory using LINQ? (or Perhaps against the database?)</p> <pre><code>var personType = new PersonType { Id = 1 }; var query = PersonDataSource.Where(p =&gt; p.PersonType.Equals(personType)); // use this query as the DataSource for your GridView </code></pre> <p>I must admit I haven't done anything like this, but I have used this trick to update/create an entity without loading the associated entities first. </p>
26,311
<p>My printer stopped printing during a few prints, and i found that the extruder had stopped heating, and the motors had stopped running. I checked the code, and nothing was wrong. My 5A fuse though, was extremely hot. I wanted to verify whether it was my fuse that had turned bad or there was some kind of short in my circuitry. With the power switched on, none of my appliances drew any current. However, the RAMPS board drew about 0.16 amps. Is that normal? If that is normal, does it mean that my fuse needs replacement? Because none of my loads seemed to draw unnecessary current. Thanks in advance.</p>
<p>As @Mikhail Z commented, it does sound like the fuse may be bad.</p> <p>The first thing to do is put an ohmmeter across the fuse (with power off!) -- if you get high resistance the fuse is definitely bad. However, if you get low resistance that does not prove the fuse is good -- see @Tom's comments below re. polyfuses in particular, and how to disconnect from the rest of the circuit.</p> <p>If you don't get lucky testing a fuse in-line, remove it and put the ohmmeter on it in isolation. Whether good or bad, it's good to put in a fuse-holder or socket, so you never have to de-solder the fuse again. </p> <p>Some boards use auto-resetting fuses or circuit breakers, which might have more complicated ways of failing (you can always replace the part to be sure). I personally avoid auto-resetting for anything that supplies heaters; if there's a problem I want to intervene rather than letting it try again endlessly.</p> <p>Since the heaters and the motors are both down, it's a good bet it's the fuse or something very early (that is, "near" the power supply). If it were a single motor or single heater, then the output control (typically a solid-state relay, or perhaps the logic controlling it) would be a better bet. Though unlikely, it's possible for two or more such controls to fail at once, so don't rule that out <em>completely</em>.</p> <p>Let us know what you discover.</p>
<p>Its very likely the polyfuse is bad. In an ideal printer, given the heater cores and great deal of power, polyfuses are some of the worst things you can use. Polyfuses have a tendency to fail in "interesting" ways, especially around their trigger amperage. Fire is one of those failure modes.</p> <p>Not only that, but if this is a noname chinese RAMPS 1.4, then you're also looking at 1/2 oz pour (it should be 1 oz or more for power traces) for the circuit board and cheaping on everything possible. I've a few boards like this that are a firetrap, along with a badly poured PCB heated bed. In that case, I would consider getting a better controller. If that's outside of your budget there is another way to do this.</p> <p>Unsolder the polyfuses and put wire between them. Normally, this is <strong>unprotecting</strong> yourself. But we're going to fix that. Head to the local automotive shop and get yourself inline fuses (think of 2 wires with a fuse in a pill shaped device). You want a 5A and a 11A fuse. Or if you did the math and know better, get the fuses you calculated for. Now, make sure they're inline with the + side of the power.</p> <p>You now have external fuses that you know are rated for the appropriate amperage, unlike polyfuses.</p>
676
<p>Duplicate Of : <a href="https://stackoverflow.com/questions/2527/c-treeview-context-menus">Find node clicked under context menu</a></p> <p>I've got a context menu on a Treeview, when the user right clicks it supposed to change based on the currently right clicked node's tag object.</p> <p>Currently I'm updating the context menu in after_select event, however this doesn't work when user right clicks to another node without selecting it.</p> <p>How can I detect which node right clicked and change the context menu? Or am I doing it wrong?</p>
<p>By far the easiest solution is to manually tag your links with Google Analytics campaign tracking parameters (utm_source, utm_campaign, utm_medium, etc.) and then pull out that data. </p> <p>The gclid is dependent on more than just the adwords account/campaign/etc. If you click on the same adwords ad twice, it could give you different gclids, because there's all sorts of session and cost data associated with that particular click as well.</p> <p>Gclid is probably not 100% random, true, but I'd be very surprised and concerned if it were possible to extract all your Adwords data from that number. That would be a HUGE security flaw (i.e. an arbitrary user could view your Adwords data). More likely, a pseudo-random gclid is generated with every impression, and if that ad is clicked on, the gclid is logged in Adwords (otherwise it's thrown out). Analytics then uses that number to reconcile the data with Adwords after the fact. Other than that, there's no intrinsic value in the gclid number itself. </p> <p>In regards to your last point, attempting to crack or reverse-engineer this information is explicitly forbidden in both the Google Analytics and Google Adwords Terms of Service, and is grounds for a permanent ban. Additionally, the TOS that you agreed to when signing up for these services says that it is not your data to use in any way you feel like. Google is providing a free service, so there are strings attached. If you don't like not having complete control over your data, then there are plenty of other solutions out there. However, you will pay a premium for that kind of control.</p> <p>Google makes nearly all their money from selling ads. Adwords is their biggest money-making product. They're not going to give you confidential information about how it works. They don't know who you are, or what you're going to do with that information. It doesn't matter if you sign an NDA and they have legal recourse to sue you; if you give away that information to a competitor, your life isn't worth enough to pay back the money you will have lost them.</p> <p>Sorry to break it to you, but "Don't be Evil" or not, Google is a business, not a charity. They didn't become one of the most successful companies in the world by giving away their search algorithm to the first guy who asked for it. </p>
<p>I agree with Ophir and Chris. My feeling is that it is purely a serial number / unique click ID, which only opens up its secrets when the Analytics and Adwords systems talk to each other behind the scenes.</p> <p>Knowing this, I'd recommend looking at the referring URL and pulling as much as possible from this to use in your back end click tracking setup.</p> <p>For example, I live in NZ, and am using Firefox. This is a search from the Firefox Google toolbar for "stack overflow": <a href="http://www.google.co.nz/search?q=stack+overflow&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;client=firefox-a&amp;rlz=1R1GGLL_en-GB" rel="nofollow noreferrer">http://www.google.co.nz/search?q=stack+overflow&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;client=firefox-a&amp;rlz=1R1GGLL_en-GB</a></p> <p>You can see that: a) im using .NZ domain, b) my keyword "stack+overflow", c) im running firefox.</p> <p>Finally, if you also stash the full landing page URL, you can store the GCLID, which will tell you the visitor came from paid, whereas if it doesn't have a GCLID, then the user must have come from natural search (if URL tagging is enabled of course).</p> <p>This would theoretically allow you to then search for the keyword in your campaign, and figure out which adgroup them came from. Knowing the creative would probably be impossible though, unless you split test your landing URLs or tag them somehow.</p>
47,766
<p>I have the following problem:</p> <p>I have an HTML textbox (<code>&lt;input type="text"&gt;</code>) whose contents are modified by a script I cannot touch (it is my page, but i'm using external components).</p> <p>I want to be notified in my script every time the value of that textbox changes, so I can react to it.</p> <p>I've tried this:</p> <pre><code>txtStartDate.observe('change', function() { alert('change' + txtStartDate.value) }); </code></pre> <p>which (predictably) doesn't work. It only gets executed if I myself change the textbox value with the keyboard and then move the focus elsewhere, but it doesn't get executed if the script changes the value.</p> <p>Is there another event I can listen to, that i'm not aware of?</p> <p><br /><br /></p> <p>I'm using the Prototype library, and in case it's relevant, the external component modifying the textbox value is Basic Date Picker (www.basicdatepicker.com) </p>
<p>As you've implied, change (and other events) only fire when the user takes some action. A script modifying things won't fire any events. Your only solution is to find some hook into the control that you can hook up to your listener.</p> <p>Here is how I would do it:</p> <pre><code>basicDatePicker.selectDate = basicDatePicker.selectDate.wrap(function(orig,year,month,day,hide) { myListener(year,month,day); return orig(year,month,day,hide); }); </code></pre> <p>That's based on a cursory look with Firebug (I'm not familiar with the component). If there are other ways of selecting a date, then you'll need to wrap those methods as well.</p>
<p>Aside from getting around the problem like how noah explained, you could also just create a timer that checks the value every few hundred milliseconds.</p>
17,688
<p>So for the second day in a row, someone has wiped out an entire table of data as opposed to the one row they were trying to delete because they didn't have the qualified where clause.</p> <p>I've been all up and down the mgmt studio options, but can't find a confirm option. I know other tools for other databases have it.</p>
<p>Under Tools>Options>Query Execution>SQL Server>ANSI, you can enable the Implicit Transactions option which means that you don't need to explicitly include the Begin Transaction command.</p> <p>The obvious downside of this is that you might forget to add a Commit (or Rollback) at the end, or worse still, your colleagues will add Commit at the end of every script by default.</p> <p>You can lead the horse to water...</p> <p>You might suggest that they always take an ad-hoc backup before they do <em>anything</em> (depending on the size of your DB) just in case.</p>
<p>Isn't there a way to give users the results they need without providing raw access to SQL? If you at least had a separate entry box for "WHERE", you could default it to "WHERE 1 = 0" or something.</p> <p>I think there must be a way to back these out of the transaction journaling, too. But probably not without rolling everything back, and then selectively reapplying whatever came after the fatal mistake.</p> <p>Another ugly option is to create a trigger to write all DELETEs (maybe over some minimum number of records) to a log table.</p>
35,592
<p>I've been thinking of ways of providing syntactic sugar for a framework I have been working on. I want to deal with Immitable objects exclusively.</p> <h3>Say I have an immutable object and wish to create a modified version of it. Would, in your view, a non-instantiable class with a single static factory method break OO principles ?</h3> <br> <blockquote> <p>As an example using a String:</p> <pre><code>public final class LOWERCASE { private LOWERCASE() {} public static String string( final String STRING ) { return STRING.toLowerCase(); } } </code></pre> <p>Therefore from this example I could write:</p> <pre><code>String lowercaseString = LOWERCASE.string( targetString ); </code></pre> <p>Which I find very readable.</p> </blockquote> <br> <h3>Any provisos against such an approach?</h3>
<p>I don't think it's a good idea to create one class per method. You could instead create a static only methods class, named e.g StringUtils and implement the methods. This way you would call:</p> <p>String lowerCaseString = StringUtils.lowercase( targetString );</p> <p>This would also offer you intellisense help while you are typing. The list of your classes will go otherwise too big. Even for this simple example, you should implement more than one Lowercase classes, so that you could also cater for circumstances that the CulutureInfo must be taken into consideration.</p> <p>I don't think this breaks OO principles in any way or that is bad design. In other languages, Ruby for example, you could add your methods directly to String class. Methods that end with ! denote that the original object is modified. All other methods return a modified copy. Ruby on Rails framework adds some methods to the String class and there is some debate about whether this is a good technique or not. It is definitely handy though.</p>
<p>Usually on immutable objects, I would have a method returning a modified version of the object. So if you have some immutable collection, it can have a sort() method, that returns a new collection that is sorted. However, in your String example this is not possible, since you cannot touch the String class.</p> <p>Your approach is quite readable, and I think for edge cases like this, is perfectly fine. For immutable objects you write yourself, I'd have the method on the object itself.</p> <p><a href="http://blogs.msdn.com/ericlippert/archive/tags/Immutability/default.aspx" rel="nofollow noreferrer">Eric Lippert's series on immutable objects in C#</a> is quite good, by the way.</p>
35,502
<p>I see in richfaces that there is a single slider, wondering if anyone has created a dual slider like in Scriptaculous for it.</p> <p>Is there any concerns in mixing JSF, Richfaces and Scriptaculous in an application?</p>
<p>I can't answer your question with precision, but here's what I know.</p> <blockquote> <p>Is there any concerns in mixing JSF, Richfaces and Scriptaculous in an application?</p> </blockquote> <p>Yes. About 50% of the problems people have with JSF are because they try to treat it like a another taglib library rather than a UI framework like Swing or SWT. The world envisaged by the JSF designers was more akin to the pluggable COM/ActiveX/VB controls than the HTML mashups currently in vogue.</p> <p>That said, it is possible to use Scriptaculous with JSF (see below). Note that the JSF control that takes the value needs some other mechanism to get its <em>clientId</em> to the JavaScript (in this case, a regular HTML hidden field that is bound to the managed bean). This is a bit messy.</p> <p>One way to clean it up would be to move everything into a JSF renderer and have the control emit all the appropriate HTML and JavaScript. I imagine this is the rationale behind RichFaces. Unfortunately, I've never used it, so only experimentation will tell whether its JavaScript library and Scriptaculous will coexist. A good indicator of whether JavaScript library authors have been thinking about interoperability is to check if the library has been namespaced.</p> <hr> <p>This code uses a slider to update a text field with a numeric value:</p> <p>View:</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1" ?&gt; &lt;jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"&gt; &lt;jsp:directive.page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" /&gt; &lt;jsp:text&gt; &lt;![CDATA[ &lt;?xml version="1.0" encoding="ISO-8859-1" ?&gt; ]]&gt; &lt;/jsp:text&gt; &lt;jsp:text&gt; &lt;![CDATA[ &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; ]]&gt; &lt;/jsp:text&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /&gt; &lt;title&gt;Script Test&lt;/title&gt; &lt;script src="javascripts/prototype.js" type="text/javascript"&gt;/**/&lt;/script&gt; &lt;script src="javascripts/scriptaculous.js" type="text/javascript"&gt;/**/&lt;/script&gt; &lt;style type="text/css"&gt; div.slider { width: 256px; margin: 10px 0; background-color: #ccc; height: 10px; position: relative; } div.slider div.handle { width: 10px; height: 15px; background-color: #f00; cursor: move; position: absolute; } div#zoom_element { width: 50px; height: 50px; background: #2d86bd; position: relative; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="demo"&gt; &lt;p&gt;Use the slider to change the value&lt;/p&gt; &lt;div id="zoom_slider" class="slider"&gt; &lt;div class="handle"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;f:view&gt; &lt;h:form&gt; &lt;h:inputText binding="#{sliderIdBean.mycontrol}" value="#{sliderIdBean.value}" onchange="updateSlider()"&gt; &lt;f:validateLongRange minimum="0" maximum="10" /&gt; &lt;/h:inputText&gt; &lt;h:commandButton value="Submit" action="#{sliderIdBean.action}" /&gt; &lt;/h:form&gt; &lt;h:messages /&gt; &lt;/f:view&gt; &lt;script type="text/javascript"&gt; var zoom_slider = $('zoom_slider'), mycontrol = $('${sliderIdBean.clientId}'); var ctrl = new Control.Slider(zoom_slider.down('.handle'), zoom_slider, { range: $R(0, 10), sliderValue: mycontrol.getValue(), onSlide: function(value) { value = Math.ceil(value); mycontrol.setValue(value); }, onChange: function(value) { value = Math.ceil(value); mycontrol.setStyle(value); } }); function updateSlider() { ctrl.setValue(mycontrol.value); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; &lt;/jsp:root&gt; </code></pre> <p>Session bean:</p> <pre><code>public class SliderIdBean { private long value = 0; private UIComponent mycontrol; public long getValue() { return value; } public void setValue(long value) { this.value = value; } public UIComponent getMycontrol() { return mycontrol; } public void setMycontrol(UIComponent mycontrol) { this.mycontrol = mycontrol; } public String getClientId() { FacesContext context = FacesContext .getCurrentInstance(); return mycontrol.getClientId(context); } public String action() { System.out.println("Submitted value was: " + value); return null; } } </code></pre> <p>faces-config.xml:</p> <pre><code>&lt;managed-bean&gt; &lt;managed-bean-name&gt;sliderIdBean&lt;/managed-bean-name&gt; &lt;managed-bean-class&gt;scripty.SliderIdBean&lt;/managed-bean-class&gt; &lt;managed-bean-scope&gt;session&lt;/managed-bean-scope&gt; &lt;/managed-bean&gt; </code></pre> <p>That JavaScript might be a little scrappy.</p>
<p>The code contains four tabs with 4 images ( you can include images, pages, etc., ) with sliding default time is 5 sec for every image change and tab clicking is provided for user. Slide begins whenever the user click on anyone of 4 tabs.</p> <pre><code>&lt;%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%&gt; &lt;%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%&gt; &lt;%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%&gt; &lt;%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%&gt; &lt;f:view&gt; &lt;body&gt; &lt;h:form id="signup"&gt; &lt;table class="logo_background"&gt; &lt;tr&gt; &lt;td valign="top"&gt; &lt;table style="margin-left: 55px; background:#FFCC00" class="tab_background"&gt; &lt;tr&gt; &lt;td width="145px" style="padding-left: 25px;"&gt; &lt;a4j:commandLink id="linkHowToPlayId" onclick="retTabClick(this.id);" value="howtoplay"&gt;&lt;/a4j:commandLink&gt; &lt;/td&gt; &lt;td width="100px" align="center" style="padding-left: 5px;"&gt; &lt;a4j:commandLink id="linkRulesId" onclick="retTabClick(this.id);" value="rules"/&gt; &lt;/td&gt; &lt;td width="5px"&gt; &lt;/td&gt; &lt;td width="130px" align="center" style="padding-left: 5px;"&gt; &lt;a4j:commandLink id="linkChallengesId" onclick="retTabClick(this.id);" value="challenges"&gt;&lt;/a4j:commandLink&gt; &lt;/td&gt; &lt;td width="5px"&gt; &lt;/td&gt; &lt;td width="130px" align="center" style="padding-left: 5px; padding-right: 15px;"&gt; &lt;a4j:commandLink id="linkPickATeamId" onclick="retTabClick(this.id);" value="pickateam"/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table&gt; &lt;tr&gt; &lt;td width="100px"&gt;&lt;/td&gt; &lt;td valign="top"&gt; &lt;table class="signup_background" style="width: 565px; height: 390px; border: solid 1px #5F8CC2;"&gt; &lt;tr&gt; &lt;td id="content" style="width: 100%;" valign="top"&gt; &lt;a4j:region&gt; &lt;a4j:poll id="poll1" interval="2000" enabled="true" reRender="signup:howtoplay,signup:rules,signup:challenges,signup:pickateam" oncomplete="javascript:loopIt();"&gt;&lt;/a4j:poll&gt; &lt;/a4j:region&gt; &lt;a4j:outputPanel id="howtoplay" layout="block" style="display:none;"&gt; &lt;h:graphicImage value="http://connectnigeria.com/articles/wp-content/uploads/2012/12/Google.jpg"&gt;&lt;/h:graphicImage&gt; &lt;/a4j:outputPanel&gt; &lt;a4j:outputPanel id="rules" layout="block" style="display:none;"&gt; &lt;h:graphicImage value="http://good-wallpapers.com/pictures/4528/1280_countryside_landscape_wallpaper.jpg"&gt;&lt;/h:graphicImage&gt; &lt;/a4j:outputPanel&gt; &lt;a4j:outputPanel id="challenges" layout="block" style="display:none;"&gt; &lt;h:graphicImage value="http://www.hdwallpapers.in/walls/windows_8_official-wide.jpg"&gt;&lt;/h:graphicImage&gt; &lt;/a4j:outputPanel&gt; &lt;a4j:outputPanel id="pickateam" layout="block" style="display:none;"&gt; &lt;h:graphicImage value="../../images/87643.jpg"&gt;&lt;/h:graphicImage&gt; &lt;/a4j:outputPanel&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/h:form&gt; &lt;script type="text/javascript"&gt; var first= 1; if( first == 1) { document.getElementById("signup:howtoplay").style.display = 'block'; document.getElementById("signup:rules").style.display = 'none'; document.getElementById("signup:challenges").style.display = 'none'; document.getElementById("signup:pickateam").style.display = 'none'; } function retTabClick(tabId) { if (tabId == "signup:linkHowToPlayId") { first = "1"; } else if (tabId == "signup:linkRulesId") { first = "2"; } else if (tabId == "signup:linkChallengesId") { first = "3"; } else if (tabId == "signup:linkPickATeamId") { first = "4"; } } function loopIt() { if( first == 1) { document.getElementById("signup:howtoplay").style.display = 'block'; document.getElementById("signup:rules").style.display = 'none'; document.getElementById("signup:challenges").style.display = 'none'; document.getElementById("signup:pickateam").style.display = 'none'; first = 2; } else if (first == 2) { document.getElementById("signup:howtoplay").style.display = 'none'; document.getElementById("signup:rules").style.display = 'block'; document.getElementById("signup:challenges").style.display = 'none'; document.getElementById("signup:pickateam").style.display = 'none'; first = 3; } else if (first == 3) { document.getElementById("signup:howtoplay").style.display = 'none'; document.getElementById("signup:rules").style.display = 'none'; document.getElementById("signup:challenges").style.display = 'block'; document.getElementById("signup:pickateam").style.display = 'none'; first = 4; } else if (first == 4) { document.getElementById("signup:howtoplay").style.display = 'none'; document.getElementById("signup:rules").style.display = 'none'; document.getElementById("signup:challenges").style.display = 'none'; document.getElementById("signup:pickateam").style.display = 'block'; first = 1; } } &lt;/script&gt; &lt;/body&gt; </code></pre> <p></p>
46,269
<p>In the course of your software development lifecycle, what essential design artifacts do you produce? What makes them essential to your practice?</p> <p>The project I'm currently on has been in production for 8+ years. This web application has been actively enhanced and maintained over that time. While we have CMMI based policies and processes in place, with portions of our practice being well defined, the design phase has been largely overlooked. Best practices, anyone? </p>
<p>Having worked on a lot of waterfall projects in the past and a lot of adhoc and agile projects more recently, there's a number of design artifacts I like to create although I can't state enough that it really depends on the details of the project (methodology/team structure/timescale/tools etc).</p> <p>For a generic, server-based 'enterprise application' I'd want the bare minimum to be something along these lines:</p> <ul> <li>A detailed functional design document (aka spec). Generally something along the lines of Joel s' <a href="http://www.joelonsoftware.com/articles/WhatTimeIsIt.html" rel="nofollow noreferrer">WhatsTimeIsIt example spec</a>, although probably with some UML use-case diagrams.</li> <li>A software techical design document. Not necessarily detailed for 100% system coverage but detailed in all the key areas and containing all the design decisions. Being a bit of an UML freak it'd be nice to see lots of pictures along the lines of package diagrams, component diagrams, key feature class diagrams, and probably some sequence diagrams thrown in for good measure.</li> <li>An infrastructure design document. Probably with UML deployment diagram for the conceptual deisng and perhaps a network diagram for something more physical.</li> </ul> <p>When I say document any of the above might be broken down into multiple documents, or perhaps stored on a wiki/some other tool. </p> <p>As for their usefulness, my philosophy has always been that a development team should always be able to hand over an application to a support team without having to hand over their phone numbers. If the design artifacts don't clealry indicate what the application does, how it does it, and where it does it then you know the support team are going to give the app the same care and attention they would a rabid dog. </p> <p>I should mention I'm not vindicating the practice of handing software over from a dev team to a support team once it's <em>finished</em>, which raises all manner of interesting issues, I'm just saying it should be possible if the management so desired.</p>
<p>I don't think anything can take the place of a good old fashioned design spec for the following reasons: </p> <ul> <li>It serves as a means of communicating how you will build an application to others. </li> <li>It lets you get ideas out of your head so you don't worry about tracking a million things at the same time.</li> <li>If you have to pause a project and return to it later you're not starting your thought process over again.</li> </ul> <p>I like to see various bits of info in a design spec:</p> <ul> <li>General explanation of your approach to the challenge at hand</li> <li>How will you monitor your application?</li> <li>What are the security concerns and how are they addressed?</li> <li>Flowcharts / sequence diagrams</li> <li>Open issues</li> <li>Known limitations</li> </ul> <p>Unit tests, while a fantastic and arguably critical item to include in your application development, don't cover all of these topics.</p>
6,667
<p>I'm writing a config file and I need to define if the process expects a windows format file or a unix format file. I've got a copy of the expected file - is there a way I can check if it uses \n or \r\n without exiting emacs?</p>
<p>If it says (DOS) on the modeline when you open the file on Unix, the line endings are Windows-style. If it says (Unix) when you open the file on Windows, the line endings are Unix-style.</p> <p>From the Emacs 22.2 manual (Node: Mode Line):</p> <blockquote> <p>If the buffer's file uses carriage-return linefeed, the colon changes to either a backslash ('\') or '(DOS)', depending on the operating system. If the file uses just carriage-return, the colon indicator changes to either a forward slash ('/') or '(Mac)'. On some systems, Emacs displays '(Unix)' instead of the colon for files that use newline as the line separator.</p> </blockquote> <p>Here's a function that &ndash; I think &ndash; shows how to check from elisp what Emacs has determined to be the type of line endings. If it looks inordinately complicated, perhaps it is.</p> <pre><code>(defun describe-eol () (interactive) (let ((eol-type (coding-system-eol-type buffer-file-coding-system))) (when (vectorp eol-type) (setq eol-type (coding-system-eol-type (aref eol-type 0)))) (message "Line endings are of type: %s" (case eol-type (0 "Unix") (1 "DOS") (2 "Mac") (t "Unknown"))))) </code></pre>
<p>Open the file in emacs using find-file-literally. If lines have ^M symbols at the end, it expects a windows format text file.</p>
29,023
<p>The most common method for corrupting compressed files is to inadvertently do an ASCII-mode FTP transfer, which causes a many-to-one trashing of CR and/or LF characters.</p> <p>Obviously, there is information loss, and the best way to fix this problem is to transfer again, in FTP binary mode.</p> <p>However, if the original is lost, and it's important, how recoverable is the data?</p> <p>[Actually, I already know what I think is the best answer (it's very difficult but sometimes possible - I'll post more later), and the common non-answers (lots of off-the-shelf programs for repairing CRCs without repairing data), but I thought it would be interesting to try out this question during the stackoverflow beta period, and see if anyone else has gone down the successful-recovery path or discovered tools I don't know about.]</p>
<p>From <a href="http://wayback.archive.org/web/jsp/Interstitial.jsp?seconds=5&amp;date=1195189396000&amp;url=http%3A%2F%2Fwww.bukys.com%2Fservices%2Frecovery%2Fexamples%2F&amp;target=http%3A%2F%2Fweb.archive.org%2Fweb%2F20071116050316%2Fhttp%3A%2F%2Fwww.bukys.com%2Fservices%2Frecovery%2Fexamples%2F" rel="nofollow noreferrer">Bukys Software</a></p> <blockquote> <p>Approximately 1 in 256 bytes is known to be corrupted, and the corruption is known to occur only in bytes with the value '\012'. So the byte error rate is 1/256 (0.39% of input), and 2/256 bytes (0.78% of input) are suspect. But since only three bits per smashed byte are affected, the bit error rate is only 3/(256*8): 0.15% is bad, 0.29% is suspect.</p> <p>...</p> <p>An error in the compressed input disrupts the decompression process for all subsequent bytes...The fact that the decompressed output is recognizably bad so quickly is cause for hope -- a search for the correct answer can identify wrong answers quickly.</p> <p>Ultimately, several techniques were combined to successfully extract reasonable data from these files:</p> <ul> <li>Domain-specific parsing of fields and quoted strings</li> <li>Machine learning from previous data with low probability of damage</li> <li>Tolerance for file damage due to other causes (e.g. disk full while logging)</li> <li>Lookahead for guiding the search along the highest-probability paths</li> </ul> <p>These techniques identify 75% of the necessary repairs with certainty, and the remainder are explored highest-probability-first, so that plausible reconstructions are identified immediately.</p> </blockquote>
<p>You could try writing a little script to replace all of the CRs with CRLFs (assuming the direction of trashing was CRLF to CR), swapping them randomly per block until you had the correct crc. Assuming that the data wasn't particularly large, I guess that might not use all of your CPU until the heat death of the universe to complete.</p> <p>As there is definite information loss, I don't know that there is a better way. Loss in the CR to CRLF direction might be slightly easier to roll back.</p>
8,442
<p>We use SAX to parse XML because it does not require the entire XML document to be read into memory in order to parse a single value. I read many articles that insisted SAX can only be used to parse/decode XML and not create it. Is this true?</p>
<p>No, it isn't true, you can encode XML to any Writer in Java using something similar to:</p> <pre><code>char[] ch; AttributesImpl atts = new AttributesImpl(); Writer writer = new StringWriter(); StreamResult streamResult = new StreamResult(writer); SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); // SAX2.0 ContentHandler TransformerHandler transformerHandler = tf.newTransformerHandler(); Transformer serializer = transformerHandler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "nodes.dtd"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); transformerHandler.setResult(streamResult); transformerHandler.startDocument(); atts.clear(); // atts.addAttribute("", "", "xmlns", "CDATA", "http://www.example.com/nodes"); // atts.addAttribute("", "", "xmlns:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance"); // atts.addAttribute("", "", "xsi:schemaLocation", "CDATA", "/nodes.xsd"); transformerHandler.startElement("", "", "node_list", atts); // displayName element if (displayName != null) { transformerHandler.startElement("", "", "display_name", null); ch = displayName.toCharArray(); transformerHandler.characters(ch, 0, ch.length); transformerHandler.endElement("", "", "display_name"); } // nodes element transformerHandler.startElement("", "", "nodes", null); atts.clear(); atts.addAttribute("", "", "node_type", "CDATA", "sometype"); transformerHandler.startElement("", "", "node", atts); ch = node.getValue().toCharArray(); transformerHandler.startElement("", "", "value", null); transformerHandler.characters(ch, 0, ch.length); transformerHandler.endElement("", "", "value"); transformerHandler.endElement("", "", "node"); transformerHandler.endElement("", "", "nodes"); transformerHandler.endElement("", "", "node_list"); transformerHandler.endDocument(); String xml = writer.toString(); </code></pre>
<p>The SAX handler interfaces were designed to be easy to implement. It's easy to write a class with similar (perhaps wrapping a SAX interface) to make it easy to call - chaining, remembering which element to close, easier attributes, etc.</p>
9,915
<p>I'd like to use two view engines in my asp.net mvc web application. The first one is the Brail view engine from MVCContrib project, and another one is my custom view engine for generating javascript code. However, I can't configure the application to use both engines. I'd like to use view file extension to discern which engine should handle the request - .brail for Brail engine - .json - for my custom engine</p> <p>When I add two engines to the ViewEngines collection in global.asax.cs, the system is always looking for *.brail views and throws exception if it doesn't find one. It never looks for my *.json views... Is it a problem with the ASP.Net mvc framework, with Brail view engine or with my code? How should it be handled?</p>
<p>I believe you can change your view engine in the controller. So I would extend your controller to select a view engine by extension.</p>
<p>I believe you can change your view engine in the controller. So I would extend your controller to select a view engine by extension.</p>
46,534
<p>I have one thread that writes results into a Queue.</p> <p>In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this:</p> <pre><code>def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break return items </code></pre> <p>Is this a good way to do it ? </p> <p><strong>Edit:</strong></p> <blockquote> <p>I'm asking because sometimes the waiting thread gets stuck for a few seconds without taking out new results.</p> </blockquote> <p>The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling <code>wx.WakeUpIdle</code>, as is recommended.</p>
<p>If you're always pulling all available items off the queue, is there any real point in using a queue, rather than just a list with a lock? ie:</p> <pre><code>from __future__ import with_statement import threading class ItemStore(object): def __init__(self): self.lock = threading.Lock() self.items = [] def add(self, item): with self.lock: self.items.append(item) def getAll(self): with self.lock: items, self.items = self.items, [] return items </code></pre> <p>If you're also pulling them individually, and making use of the blocking behaviour for empty queues, then you should use Queue, but your use case looks much simpler, and might be better served by the above approach.</p> <p><strong>[Edit2]</strong> I'd missed the fact that you're polling the queue from an idle loop, and from your update, I see that the problem isn't related to contention, so the below approach isn't really relevant to your problem. I've left it in in case anyone finds a blocking variant of this useful:</p> <p>For cases where you do want to block until you get at least one result, you can modify the above code to wait for data to become available through being signalled by the producer thread. Eg.</p> <pre><code>class ItemStore(object): def __init__(self): self.cond = threading.Condition() self.items = [] def add(self, item): with self.cond: self.items.append(item) self.cond.notify() # Wake 1 thread waiting on cond (if any) def getAll(self, blocking=False): with self.cond: # If blocking is true, always return at least 1 item while blocking and len(self.items) == 0: self.cond.wait() items, self.items = self.items, [] return items </code></pre>
<p>I see you are using get_nowait() which according to the documentation, "return[s] an item if one is immediately available, else raise the Empty exception"</p> <p>Now, you happen to break out of the loop when an Empty exception is thrown. Thus, if there is no result immediately available in the queue, your function returns an empty items list.</p> <p>Is there a reason why you are not using the get() method instead? It may be the case that the get_nowait() fails because the queue is servicing a put() request at that same moment. </p>
18,913
<p>How flexible should a programmer be if a client requests requirements that is not in the project scope?</p>
<p>General perspective:</p> <p>You need to earn a living; the client needs a computing solution: the client has the right to make sure that the solution you will supply fits his needs. Changes and additions after and agreement has been reached, reflects on your ability to analyze the user's requirements into a system design, in that failed to investigate those requirements to sufficient depth and detail: you need to do this meticulously and obtain a written sign-off agreement on your system design from the client.</p> <p>Legal perspective:</p> <p>You should pin the scope of the project down, and get the client to sign an agreement of that scope. Once you have that agreement, anything not covered by it constitutes a new project.</p> <p>Business perspective:</p> <p>Do you want to continue doing business (with the current as well as future clients)? You need to do an evaluation of the impact adding the new required functionality will have on the current project: if the impact is small, then do it, but tell the client - in writing - that you are doing him a favor; if the impact is larger then you must negotiate with the client, outlining the issues, and either adapt your current agreement, or make a new one. What you do not want to do is to antagonize your client.</p> <p>Lastly: "The client is always right." - (up to the point where you have to give up and just go away.)</p>
<p>This question cannot be given a blanket answer. It depends project to project.</p> <p>Examples:</p> <p>Client has money to burn, long timeline, no other projects on the go, I am very flexible.</p> <p>Client is tight with $$, short timeline, other projects on the go, I am hardly flexible at all.</p> <p>Other factors come into play as well, such as the process that has been chosen for the project. For example, you will be more flexible in an agile process, less flexible in a waterfall approach.</p>
23,570
<p><a href="http://en.wikipedia.org/wiki/Progressive_enhancement" rel="nofollow noreferrer">Progressive Enhancement</a> is a web development methodology that not only allows greater portability and accessibility but in my opinion, makes the development process easier.</p> <p>What I want is to know what the rest of the community think of this approach.</p> <p>In particular: What do you believe is the minimum set of technologies that a web application should support?</p>
<p>If it remains usable in a text-only browser (without CSS and Javascript, of course) and also in a screen-reader, you're on the right track. But these are about the highest standards that you'll find :)</p>
<p>So "Progressive Enhancement" is just another term for "Graceful Degradation"?</p> <p>In which case, it's the way all websites <em>should</em> be done.</p> <p>Web Apps should be built in HTML (4 or later), semantically and against the standards.</p> <p>All CSS should be optional - content &amp; forms should work without it, but look prettier with it.<br/> All JavaScript should be optional - pages &amp; forms should work without, but work easier with it.</p> <p>All code should be written according to the standards &amp; checked in each major rendering engine - but don't work around flaws in browsers unless absolutely necessary; it's up to the browsers to respect standards, not developers to grovel after bad rendering engines.</p>
12,495
<p>Is there a way to select which TestMethods you want to execute in Visual Studio 2008 Unit Test project while debugging? I want to debug one particular test without having my other TestMethods execute during each debug session.</p>
<p>Click on a test method name, then press Ctrl+R, Ctrl+T. (Or go to Test / Debug / Tests in Current Context.)</p>
<p>If you want to debug while running your tests under an ASP.NET solution, check out the MSDN article "How to: Debug while Running a Test in an ASP.NET Solution" at <a href="http://msdn.microsoft.com/en-us/library/ms243172.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms243172.aspx</a>.</p> <p>I had to do this tonight and partially followed the instructions for "Debugging While Running on ASP.NET Development Server", setting in web.config and the System.Diagnostics.Debugger.Break() statement at the start of the method. However, I executed with the "Debug Checked Tests" command (Ctrl+R, Ctrl+T) which produced a Just-in-time debugger prompts and ran up a new instance of Visual Studio (I'm using VS2010 Beta2). It worked well.</p>
33,439
<p>1) I have a ReportViewer control on a page that's linked to a ServerReport (I'm using ASP.NET 2.0). The report displays fine, but the 'Export' link is present but disabled and the 'Select a format' drop down list (that's normally visible when you view the report in Reporting Services) isn't there. Any ideas? The ShowExportControls property is set to true.</p> <p>2) Also, when I click the print icon in the ReportViewer control, IE asks me if I want to install 'Microsoft SQL Server'. I click Install and then it displays a messagebox saying 'Unable to load client print control'. I'm using IE7 and Vista.</p>
<p><a href="http://commons.apache.org/cli/" rel="nofollow noreferrer">Commons CLI</a></p>
<p><a href="https://github.com/kohsuke/args4j" rel="nofollow noreferrer">https://github.com/kohsuke/args4j</a> -- has pretty good features PLUS MIT license</p>
25,475
<p>In several cases I want to add a toolbar to the top of the iPhone keyboard (as in iPhone Safari when you're navigating form elements, for example). </p> <p>Currently I am specifying the toolbar's rectangle with constants but because other elements of the interface are in flux - toolbars and nav bars at the top of the screen - every time we make a minor interface change, the toolbar goes out of alignment.</p> <p>Is there a way to programmatically determine the position of the keyboard in relation to the current view?</p>
<p>As of iOS 3.2 there's a new way to achieve this effect:</p> <p><code>UITextFields</code> and <code>UITextViews</code> have an <code>inputAccessoryView</code> property, which you can set to any view, that is automatically displayed above and animated with the keyboard.</p> <p>Note that the view you use should neither be in the view hierarchy elsewhere, nor should you add it to some superview, this is done for you.</p>
<p>There's no way (AFAIK) to get the dimensions of the keyboard view. It is however constant, at least in every iPhone version so far.</p> <p>If you calculate the toolbar position as an offset from the BOTTOM of your view, and take the size of your view into account, then you should not have to worry whether a navbar is present or not.</p> <p>E.g.</p> <pre><code>#define KEYBOARD_HEIGHT 240 // example - can't remember the exact size #define TOOLBAR_HEIGHT 30 toolBarRect.origin.y = viewRect.size.height - KEYBOARD_HEIGHT - TOOLBAR_HEIGHT; // move toolbar either directly or with an animation </code></pre> <p>Instead of a define, you could easily create a <code>keyboardHeight</code> function that returns the size based on whether the keyboard is being displayed, and move this toolbar positioning into a separate function that reorganizes your layout.</p> <p>Also it can depend on where you do this positioning as it's possible the size of your view may change between being loaded and shown based on your navbar setup. I believe the best place to do it would be in viewWillAppear.</p>
19,183
<p>In C# Is there a way of getting a finer granularity with SQL exceptions?</p> <p>I'm aware that an aweful lot can go wrong but I want to deal with certain cases differently and parsing the Error message doesn't seem to be very elegant.</p> <p>Also Are the error messages created by the framework or are they db specific?</p> <p>For example If i have a primary key violation on INSERT is the error message going to always be:</p> <p>Violation of PRIMARY KEY constraint 'PK_tblProduct'. Cannot insert duplicate key in object 'dbo.tblProduct'.</p> <p>or is that SQLServer specific.</p> <p><strong>Update</strong></p> <p>I looks like I'm after the error number, any idea where I can get the various error numbers?</p> <p>best I can do with a quick google is: 18456: Logon Failed 18488: Password Expired</p>
<p>If you are catching a <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlexception.aspx" rel="nofollow noreferrer"><code>SqlException</code></a>, you should have access to <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlexception.number.aspx" rel="nofollow noreferrer"><code>.Number</code></a>, which gives you the SQL error number; this is probably your best approach... (you can get the same from the <code>InfoMessage</code> event as well for non-fatal errors).</p> <p>Of course, this won't distinguish between tables - you could argue that if you need this level of granularity, you should check first (in a serializable isolation level, ideally with UPDLOCK), raising your own error if there is conflicting data.</p>
<p>In SQL Server you can use various error functions which returns various information about the errors encountered from sys.messages</p> <p>You can retrieve more information from <a href="http://msdn.microsoft.com/en-us/library/ms179495(SQL.90).aspx" rel="nofollow noreferrer">BOL</a>.</p>
32,720
<p>I have three models:</p> <pre><code>class ReleaseItem &lt; ActiveRecord::Base has_many :pack_release_items has_one :pack, :through =&gt; :pack_release_items end class Pack &lt; ActiveRecord::Base has_many :pack_release_items has_many :release_items, :through=&gt;:pack_release_items end class PackReleaseItem &lt; ActiveRecord::Base belongs_to :pack belongs_to :release_item end </code></pre> <p>The problem is that, during execution, if I add a pack to a release_item it is not aware that the pack is a pack. For instance:</p> <pre><code>Loading development environment (Rails 2.1.0) &gt;&gt; item = ReleaseItem.new(:filename=&gt;'MAESTRO.TXT') =&gt; #&lt;ReleaseItem id: nil, filename: "MAESTRO.TXT", created_by: nil, title: nil, sauce_author: nil, sauce_group: nil, sauce_comment: nil, filedate: nil, filesize: nil, created_at: nil, updated_at: nil, content: nil&gt; &gt;&gt; pack = Pack.new(:filename=&gt;'legion01.zip', :year=&gt;1998) =&gt; #&lt;Pack id: nil, filename: "legion01.zip", created_by: nil, filesize: nil, items: nil, year: 1998, month: nil, filedate: nil, created_at: nil, updated_at: nil&gt; &gt;&gt; item.pack = pack =&gt; #&lt;Pack id: nil, filename: "legion01.zip", created_by: nil, filesize: nil, items: nil, year: 1998, month: nil, filedate: nil, created_at: nil, updated_at: nil&gt; &gt;&gt; item.pack.filename NoMethodError: undefined method `filename' for #&lt;Class:0x2196318&gt; from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1667:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/mislav-will_paginate-2.3.3/lib/will_paginate/finder.rb:164:in `method_missing' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:285:in `send' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:285:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1852:in `with_scope' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_proxy.rb:168:in `send' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_proxy.rb:168:in `with_scope' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:281:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/mislav-will_paginate-2.3.3/lib/will_paginate/finder.rb:164:in `method_missing' from (irb):5 &gt;&gt; </code></pre> <p>It seems that I should have access to item.pack, but it is unaware that the pack is a Pack item.</p>
<p>It appears that your usage of has_one :through is correct. The problem you're seeing has to do with saving objects. For an association to work, the object that is being referenced needs to have an id to populate the <code>model_id</code> field for the object. In this case, <code>PackReleaseItems</code> have a <code>pack_id</code> and a <code>release_item_id</code> field that need to be filled for the association to work correctly. Try saving before accessing objects through an association.</p>
<p>You want to save or create (instead of new) the item and pack. Otherwise, the database has not assigned id's for the association.</p>
11,535
<p>i'm using jdbc to work with my db. I want to store a HashMap directly in the db, oracle. i figure i need to serialize the Map, and its contents, which are only String. Map already implements Serializeable, but my question is how do i put the Map in the SQL using jdbc? for instance, i have a jdbcTemplate.update("insert into ....", new Object[]{....}, new int[]{....}) do i just put the Map in the Object array? Thanks</p>
<p>You need a table with key/value columns, and if you're storing multiple maps, an identity column (or a foreign key to another table holding data that the hashmap is a member of).</p> <p>Then in JDBC, create a prepared statement (insert into myhashmap (id, foreign_id, key, val) values (?, ?, ?, ?)) ONCE, and then loop over every element in the hashmap, setting the parameters on the statement and calling execute on the query.</p> <p>(sorry, not near any code to post code snippets and don't want to type in buggy examples).</p> <p>This is also trivially extendible to maps of String -> Object, where you wish to store every field in Object in the DB. I.e., it's basically like a standard table in a database, and a 'key' column. Lists are similar, but with a 'rank' column to indicate ordering.</p>
<p>The way I have done it in the past is to create one column in a table to store your serialized objects. The datatype should be "blob" or equivalent in Oracle.</p> <p>It can then be written/retrieved using ResultSet.setBytes() and ResultSet.getBytes()</p>
48,317
<p>I'm looking for a way to create an "it will look cool" effect for a full screen WPF application I'm working on - a "screen glint" effect that animates or moves across the whole screen to give off a shiny display experience. I'm thinking of creating a large rectangle with a highlighted-gradient and transparent background, which could be animated across the screen. Any ideas how this can be done effectively in XAML?</p>
<p>I came up with a solution that looks pretty good. Some sample XAML that I chalked up in Blend 2.0 SP1 looks like this:</p> <pre><code>&lt;Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="ScreenGlintApplication.Window1" x:Name="Window" Title="Window1" Width="500" Height="250" Background="#FF000000" Foreground="#FF3EE229" &gt; &lt;Grid x:Name="LayoutRoot"&gt; &lt;TextBlock TextWrapping="Wrap" FontSize="40" &gt; &lt;Run Text="This is some sample text to have something to work with. Have a nice day! /Johan"/&gt; &lt;/TextBlock&gt; &lt;Canvas Panel.ZIndex="99" &gt; &lt;Rectangle x:Name="ScreenGlintRect" Width="{Binding Path=ActualWidth, ElementName=Window, Mode=Default}" Height="{Binding Path=ActualHeight, ElementName=Window, Mode=Default}" Opacity="0.4" &gt; &lt;Rectangle.Triggers&gt; &lt;EventTrigger RoutedEvent="Rectangle.Loaded"&gt; &lt;BeginStoryboard&gt; &lt;Storyboard&gt; &lt;DoubleAnimation Storyboard.TargetName="ScreenGlintRect" Storyboard.TargetProperty="(Canvas.Left)" From="-500" To="1000" Duration="0:0:2" /&gt; &lt;/Storyboard&gt; &lt;/BeginStoryboard&gt; &lt;/EventTrigger&gt; &lt;/Rectangle.Triggers&gt; &lt;Rectangle.Fill&gt; &lt;LinearGradientBrush StartPoint="0,1" EndPoint="1,1"&gt; &lt;GradientStop Color="Transparent" Offset="0.0" /&gt; &lt;GradientStop x:Name="GlintColor" Color="LightGreen" Offset="0.50" /&gt; &lt;GradientStop Color="Transparent" Offset="1" /&gt; &lt;/LinearGradientBrush&gt; &lt;/Rectangle.Fill&gt; &lt;/Rectangle&gt; &lt;/Canvas&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>An option is to do this in code behind, which is pretty neat if you want to have granular control of the animation. For example:</p> <pre><code> ScreenGlintRect.Width = Width; ScreenGlintRect.Height = Height; var animation = new DoubleAnimation { Duration = new Duration(TimeSpan.FromSeconds(2)), From = (-Width), To = Width * 2 }; ScreenGlintRect.BeginAnimation(Canvas.LeftProperty, animation); </code></pre> <p>This is the code I'm using and it looks good enough for me. If you got HW acceleration you could try and add some blur to it. You may have to tweak the code and hide/show the rectangle, but basically this is it.</p>
<p>You can put a transparent panel on top like LBugnion said, but don't forget there are many ways you can do this:</p> <ol> <li>Change the visibility of the panel to Hidden. </li> <li>Change the opacity to 0.</li> <li>Change the Alpha of the color to 0.</li> </ol> <p>If you only change the Alpha it still is <em>clickable</em> even when you don't see the color.</p> <p>Off topic but: try to make the effect subtle and maybe have a on/off option. </p>
23,181
<p>Greetings,</p> <p>I'm trying to use pylucene in Python 2.6. Since there's no windows build for 2.6, I try to build the source code.</p> <p>First of all, I build JCC (windows, using cygwin)</p> <pre><code>python setup.py build running build running build_py [...] building 'jcc' extension error: None python setup.py install running install [...] copying jcc\config.py -&gt; build\lib.win32-2.6\jcc copying jcc\classes\org\osafoundation\jcc\PythonException.class -&gt; build\lib.win32-2.6\jcc\classes\org\osafoundation\jcc running build_ext building 'jcc' extension error: None </code></pre> <p>Notice that it won't copy anything on my "F:\Python26\Lib\site-packages" directory. I don't know why. So that, I don't know if it's really installed or not.</p> <p>Now, I'll make pylucene</p> <pre><code>make /cygdrive/f/Python26//python.exe -m jcc --shared --jar lucene-java-2.4.0/build/lucene-core-2.4.0.jar [...] 'doc:(I)Lorg/apache/lucene/document/Document;' --version 2.4.0 --files 2 --build f:\Python26\python.exe: No module named jcc make: *** [compile] Error 1 </code></pre> <p>So, it seems JCC wasn't installed at all.</p> <p>Then, I try to copy the "jcc build" under F:\Python26\Lib\site-packages, and I try to make pylucene again:</p> <pre><code>make [...] f:\Python26\python.exe: jcc is a package and cannot be directly executed make: *** [compile] Error 1 </code></pre> <p>Has anyone else seen this and found a workaround?</p>
<p>try:</p> <blockquote> <p>/cygdrive/f/Python26//python.exe setup.py build</p> </blockquote> <p>and</p> <blockquote> <p>/cygdrive/f/Python26//python.exe setup.py build setup.py install</p> </blockquote> <p>I believe you are using python from cygwin for instaling jcc and python from windows for running...</p>
<p>that just can build jcc and install,</p> <p>top full code.</p> <p>13998bytes</p> <p>when import,report error.</p> <pre><code>&gt;&gt;&gt; import jcc Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "D:\Python26\lib\site-packages\jcc-2.5.1-py2.6-win32.egg\jcc\__init__.py" , line 29, in &lt;module&gt; from _jcc import initVM ImportError: DLL load failed: 找不到指定的模块。(cant find appointed modules) &gt;&gt;&gt; </code></pre>
40,270
<pre><code>[hannel,192.168.0.46:40014] 15:08:03,642 - ERROR - org.jgroups.protocols.UDP - failed sending message to null (61 bytes) java.lang.Exception: dest=/225.1.2.46:30446 (64 bytes) at org.jgroups.protocols.UDP._send(UDP.java:333) at org.jgroups.protocols.UDP.sendToAllMembers(UDP.java:283) at org.jgroups.protocols.TP.doSend(TP.java:1327) at org.jgroups.protocols.TP.send(TP.java:1317) at org.jgroups.protocols.TP.down(TP.java:1038) at org.jgroups.protocols.PING.sendMcastDiscoveryRequest(PING.java:220) at org.jgroups.protocols.PING.sendGetMembersRequest(PING.java:214) at org.jgroups.protocols.Discovery$PingSenderTask$1.run(Discovery.java:385) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:417) at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:280) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:135) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:65) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(ScheduledThreadPoolExecutor.java:142) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:166) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675) at java.lang.Thread.run(Thread.java:595) Caused by: java.io.InterruptedIOException: operation interrupted at java.net.PlainDatagramSocketImpl.send(Native Method) at java.net.DatagramSocket.send(DatagramSocket.java:612) at org.jgroups.protocols.UDP._send(UDP.java:324) ... 16 more </code></pre> <p>This is happening during load testing on the server. Should I worry about it. Aside from getting that message in the log, everything seem to work OK.</p>
<p>In response to matt b, the "failed sending message to null" message is misleading. The true problem is the InterruptedIOException. This means that someone called interrupt() on the Thread that was sending UDP. Most likely, the interrupt is generated within JGroups. (Unless you started, and then stopped the JGroups channel.)</p> <p>Looking at the stack trace, the interrupted I/O was from a Discovery protocol. It was trying to discover other cluster members. Thus, no message of yours was lost from this Exception.</p> <p>We would have to know more to really figure this one out.</p>
<p>Is it possible you are getting an error because you are sending a message to "null"?</p> <blockquote> <p>ERROR - org.jgroups.protocols.UDP - failed sending message to null </p> </blockquote> <p>Otherwise this is probably pretty hard for anyone else to help you out with without code samples, information on your network, the specific situation where your problem occurs, etc.</p>
48,732
<p>In Eclipse, in the menu, I can go to Window -> Preferences -> Keys and set the Scheme to "Emacs." I can also click "Export" at the bottom-right hand side of the dialog to export a .CSV file containing a listing of my keyboard mappings.</p> <p>How do I re-import this configuration into a different installation of Eclipse? The File -> Import option seems to neither support .CSV files or a specific keyboard configuration file. </p>
<p>You could try exporting and importing all of your preferences</p> <p><strong>Export</strong> File->Export...->General->Preferences</p> <p><strong>Import</strong> File->Import...->General->Preferences</p>
<p>Something that should work is to export all preferences and then import them in the other install. But I know no way to do that for the keyboard prefs alone.</p> <p>I agree that it would make sense. I suggest you open a bug report against Eclipse. Maybe it really is a missing feature (or the solution is too simple and we don't see it).</p>
47,531
<p>I have been using PHP and JavaScript for building my dad's website. He wants to incorporate a login system into his website, and I have the design for the system using PHP. My problem is how do I show buttons if the person is logged in?­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p> <p><strong>For Example -</strong> You have <em>Home</em>, <em>Products</em>, <em>About Us</em>, and <em>Contact</em>. I want to have buttons for <em>Dealer</em>, <em>Distributor</em>, and maybe other information if the user is logged in. So I will have <em>Home</em>, <em>Products</em>, <em>About Us</em>, <em>Contacts</em>, Dealer (if dealer login), <em>Distributor</em> (if distributor login), and so forth. </p> <p>Would JavaScript be a good way to do this or would PHP, or maybe even both? Using JavaScript to show and hide buttons, and PHP to check to see which buttons to show. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
<p>Regarding security, <strong>you cannot trust what comes from the client</strong>:</p> <ul> <li>The visitor can see all your code (HTML and Javascript, not PHP) and try stuff</li> <li>The visitor may not even use a browser; it's trivially easy to send a request with a script</li> </ul> <p>This means hiding the buttons is good User Interface design (because you can't use them if you are not logged in). But it's not a security feature. The security feature is checking, on the server, that the visitor is logged in before each action that requires it.</p> <p>If you don't intend to show the buttons, it's not useful to send the HTML and images to the browser and then hide them with Javascript. I would check with PHP.</p>
<p>Basically where you have your menu in html, say as a list <code>&lt;ul&gt; &lt;li&gt;Home&lt;/li&gt; &lt;/ul&gt;</code> you add php after <code>&lt;/li&gt;</code> of the last item:</p> <pre><code>&lt;?php if($session-logged_in) { ?&gt; &lt;li&gt;My Account&lt;/li&gt; &lt;?php } ?&gt; </code></pre>
2,868
<p>I'm launching a Weblogic application inside Eclipse via the BEA Weblogic Server v9.2 runtime environment. If this were running straight from the command-line, I'd do a ctrl-BREAK to force a thread dump. Is there a way to do it in Eclipse?</p>
<p>Indeed (thanks VonC to point to the SO thread), Dustin, in a comment to his message, points to <a href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jstack.html" rel="noreferrer" title="jstack - Stack Trace">jstack</a>.</p> <p>I have run a little Java application (with GUI) in Eclipse, I can see the related javaw.exe in Windows' process manager and its PID, 7088 (it is even simpler in Unix, of course).</p> <p>If I type at a command prompt <code>jstack 7088</code>, I have the wanted stack dump per thread.<br> Cool.</p> <p>Would be better if we could do that directly from Eclipse, but that's already useful as is.</p>
<p>Did you try to launch your eclipse with java.exe instead of javaw.exe (in your <a href="https://stackoverflow.com/questions/142357/what-are-the-best-eclipse-34-jvm-settings#144349">eclipse.ini</a>) ?</p> <p>That might give you the console you need, as described in <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=13524" rel="nofollow noreferrer">this bug</a> and in <a href="http://dev.eclipse.org/mhonarc/newsLists/news.eclipse.platform/msg15120.html" rel="nofollow noreferrer">this message</a>.</p> <p>Other ideas (in term of java options) could be derived from this <a href="https://stackoverflow.com/questions/66104/why-does-tomcat-55-with-java-14-running-on-windows-xp-32-bit-suddenly-hang">other SO question</a>.</p>
30,142
<p>I have a series of Eclipse projects containing a number of plugins and features that are checked into CVS. I now need to run an automated build of these plugins. Ideally I'd like to do it without having to hardcode large numbers of Eclipse library locations by hand, which has been the problem with the automatically generated Ant files that Eclipse provides. The build also needs to run headlessly.</p> <p>Does anyone have experience of this sort of set-up with Eclipse, and recommendations for how to achieve it?</p>
<p>There are a few options for you to look at, depending on which build scripting language you're using:</p> <ul> <li>For <a href="http://books.sonatype.com/maven-book/reference/multimodule.html" rel="nofollow noreferrer">Maven2</a>, the way forward seems to be Spring Dynamic Modules. Other options are <a href="http://www.ops4j.org/projects/pax/maven/" rel="nofollow noreferrer">Pax Construct</a>, <a href="http://m2eclipse.codehaus.org/" rel="nofollow noreferrer">m2eclipse</a>, <a href="http://felix.apache.org/site/maven-bundle-plugin-bnd.html" rel="nofollow noreferrer">Maven BND</a></li> <li>For Ant/Gant, <a href="http://wiki.eclipse.org/index.php/PDEBuild" rel="nofollow noreferrer">Eclipse PDE Buil</a>d, <a href="http://ant4eclipse.sourceforge.net/" rel="nofollow noreferrer">Ant4Eclipse</a></li> <li>For command line or both the above, <a href="http://www.eclipse.org/buckminster/" rel="nofollow noreferrer">Buckminster</a>.</li> </ul> <p>At my current clients we use Buckminster, which wraps PDE-Build, and call it from Ant/CruiseControl. We've got code coming in from multiple repositories all being built into a single RCP product.</p> <p>Also, <a href="https://stackoverflow.com/questions/27818/how-can-i-manage-osgi-build-dependencies">these</a> <a href="https://stackoverflow.com/questions/121244/using-custombuildcallbacksxml-in-an-eclipse-rcp-headless-build">questions</a> may be of help. </p>
<p>You could write some sort of a script that finds those libraries for you and puts them into a format understandable by Ant.</p> <p>For example, it could build a eclipse.lirbaries.properties file, then you could read in that file using:</p> <pre><code>&lt;property file="eclipse.libraries.properties" /&gt; </code></pre> <p>You could also use the FileSet attribute:</p> <p><a href="http://ant.apache.org/manual/Types/fileset.html" rel="nofollow noreferrer"><a href="http://ant.apache.org/manual/Types/fileset.html" rel="nofollow noreferrer">http://ant.apache.org/manual/Types/fileset.html</a></a></p> <p>Or even a combination of both. </p> <p>1) Call Ant Script<br /> 2) Ant Script calls bash (or whatever scripting language) script which builds eclipse.libraries.properties<br/> 3) Ant loads eclipse.libraries.properties<br/> 4) Ant goes on with the build<br/></p>
39,336
<p>I printed a G1/8 thread in PLA where I can connect a compressor to have a small pressure container. Even though all measurements are correct and it screws in fine, it still leaks air.</p> <p>Is there a way to make 3D prints airtight?</p>
<p>Yes.</p> <p>The issue is, that there are small gaps between the layers. But you can coat the print in an airtight material. While epoxy and similar materials work very well, they are somewhat too viscous and take a long time to cure.</p> <p>My special recipe for coating PLA prints with a fast-curing airtight thin layer is:</p> <ol> <li>Dissolve 1 g Paraloid B-72 in 20 ml acetone.</li> <li>Dip or otherwise evenly coat the print and dry at room temperature for 10-20 minutes.</li> </ol>
<p>Yes.</p> <p>The issue is, that there are small gaps between the layers. But you can coat the print in an airtight material. While epoxy and similar materials work very well, they are somewhat too viscous and take a long time to cure.</p> <p>My special recipe for coating PLA prints with a fast-curing airtight thin layer is:</p> <ol> <li>Dissolve 1 g Paraloid B-72 in 20 ml acetone.</li> <li>Dip or otherwise evenly coat the print and dry at room temperature for 10-20 minutes.</li> </ol>
2,165
<p>We have a database that we are using to store test results for an embedded device. There's a table with columns for different types of failures (details not relevant), along with a primary key 'keynum' and a 'NUM_FAILURES' column that lists the number of failures. We store passes and failures, so a pass has a '0' in 'NUM_FAILURES'.</p> <p>In order to keep the database from growing without bounds, we want to keep the last 1000 results, plus any of the last 50 failures that fall outside of the 1000. So, worst case, the table could have 1050 entries in it. I'm trying to find the most efficient SQL insert trigger to remove extra entries. I'll give what I have so far as an answer, but I'm looking to see if anyone can come up with something better, since SQL isn't something I do very often.</p> <p>We are using SQLITE3 on a non-Windows platform, if it's relevant.</p> <p><strong>EDIT:</strong> To clarify, the part that I am having problems with is the DELETE, and specifically the part related to the last 50 failures.</p>
<p>The reason you want to remove these entries is to keep the database growing too big and not to keep it in some special state. For that i would really not use triggers and instead setup a job to run at some interval cleaning up the table.</p>
<p>So far, I have ended up using a View combined with a Trigger, but I'm not sure it's going to work for other reasons.</p> <pre><code>CREATE VIEW tablename_view AS SELECT keynum FROM tablename WHERE NUM_FAILURES!='0' ORDER BY keynum DESC LIMIT 50; CREATE TRIGGER tablename_trig AFTER INSERT ON tablename WHEN (((SELECT COUNT(*) FROM tablename) &gt;= 1000) or ((SELECT COUNT(NUM_FAILURES) FROM tablename WHERE NUM_FAILURES!='0') &gt;= 50)) BEGIN DELETE FROM tablename WHERE ((((SELECT MAX(keynum) FROM ibit) - keynum) &gt;= 1000) AND ((NUM_FAILURES=='0') OR ((SELECT MIN(keynum) FROM tablename_view) &gt; keynum))); END; </code></pre>
19,030
<p>Does anyone know a method to programmatically close the CD tray on Windows 2000 or higher? Open CD tray exists, but I can't seem to make it close especially under W2k. </p> <p>I am especially looking for a method to do this from a batch file, if possible, but API calls would be OK.</p>
<p>Here is an easy way using the Win32 API:</p> <pre><code> [DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi)] protected static extern int mciSendString(string lpstrCommand,StringBuilder lpstrReturnString,int uReturnLength,IntPtr hwndCallback); public void OpenCloseCD(bool Open) { if (Open) { mciSendString("set cdaudio door open", null, 0, IntPtr.Zero); } else { mciSendString("set cdaudio door closed", null, 0, IntPtr.Zero); } } </code></pre>
<p>To close the drive tray do as described <a href="https://stackoverflow.com/a/30512979/3969362">here</a> but instead of using DeviceIoControl with IOCTL_STORAGE_EJECT_MEDIA you need to call DeviceIoControl with IOCTL_STORAGE_LOAD_MEDIA.</p>
8,308
<p>How would one draw an oval in JS?</p>
<p><a href="http://www.w3.org/Graphics/SVG/" rel="nofollow noreferrer">SVG</a> .. or tiny divs and <a href="http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm" rel="nofollow noreferrer">bresenham</a> .. or check the <a href="http://www.walterzorn.com/jsgraphics/jsgraphics_e.htm" rel="nofollow noreferrer">Javascript VectorGraphics library</a></p>
<p>More-or-less crossplatform way to do vector graphics is to use <a href="http://docs.dojocampus.org/dojox/gfx" rel="nofollow noreferrer">Dojo GFX</a> (<a href="http://archive.dojotoolkit.org/nightly/dojotoolkit/dojox/gfx/tests/" rel="nofollow noreferrer">tests</a>, <a href="http://archive.dojotoolkit.org/nightly/dojotoolkit/dojox/gfx/demos/" rel="nofollow noreferrer">demos</a>, <a href="http://archive.dojotoolkit.org/nightly/dojotoolkit/dojox/gfx/tests/test_bezier.html" rel="nofollow noreferrer">ellipse example</a> &mdash; all those links point to the test/debug server, can be slow at times).</p>
44,827
<p>I use the <code>:e</code> and <code>:w</code> commands to edit and to write a file. I am not sure if there is "close" command to close the current file without leaving Vim?</p> <p>I know that the <code>:q</code> command can be used to close a file, but if it is the last file, Vim is closed as well; Actually on Mac OS MacVim does quit. Only the Vim window is closed and I could use <kbd>Control</kbd>-<kbd>N</kbd> to open a blank Vim window again. I would like Vim to remain open with a blank screen.</p>
<p>This deletes the buffer (which translates to close the file)</p> <pre><code>:bd </code></pre>
<p>I have the same issue so I made the plugin. This plugin replace :q and other commands and then prevent the window closed.</p> <p>if you still have issue, please try to use following plugin. <a href="https://github.com/taka-vagyok/prevent-win-closed.vim" rel="nofollow">https://github.com/taka-vagyok/prevent-win-closed.vim</a></p>
31,968
<p>In a C# Windows Forms application I want to detect if another instance of the application is already running. If so, activate the main form of the running instance and exit this instance.</p> <p>What is the best way to achieve this?</p>
<p>Scott Hanselman <a href="http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx" rel="noreferrer">answers</a> on you question in details.</p>
<p>Aku, that is a good resource. I answered a question similar to this one a while back. You can check my <a href="https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application#19326">answer here</a>. Even though this was for WPF, you can use the same logic in WinForms.</p>
7,512
<p>One of the PDC2008 presentations showed off the new VS2010 UI (not the same as the current beta) that was built with WPF. Some of the new code effects looked fairly nice (comment xml parsed and styled within the code editor).</p> <p>It got me wondering if Microsoft would ever change the VS UI to the Ribbon; like Office, the change could possibly be forced with no 'classic' mode.</p> <p>Would you embrace such a change?</p> <p>From what I gather</p> <p>Advanced programmers: minor change, hot keys are the same.</p> <p>Intermediate/Beginner programmers: considerable change, every button has moved!</p> <p>New programmers: Context sensitive ribbons help emphasize what they may do and where.</p>
<p>It all depends on how it would be implemented.<br>It could be a good thing, but just in case I would like it to be optional:)</p>
<p>I'm a huge fan of the ribbon, but it would be horrible if they implemented a ribbon-like UI on VS if it hogged too much screen real estate and kept me from seeing my code.</p>
32,232
<p>I need to create a midnight DateTime</p> <p>I've just done this:</p> <pre><code>DateTime endTime = DateTime.Now; endTime.Subtract(endTime.TimeOfDay); </code></pre> <p>Haven't test it yet, I'm assuming it works but is there a better/cleaner way?</p>
<p>Just use <code>foo.Date</code>, or <a href="https://learn.microsoft.com/en-us/dotnet/api/system.datetime.today" rel="noreferrer"><code>DateTime.Today</code></a> for today's date</p>
<pre><code> private bool IsServiceDatabaseProcessReadyToStart() { bool isGoodParms = true; DateTime currentTime = DateTime.Now; //24 Hour Clock string[] timeSpan = currentTime.ToString("HH:mm:ss").Split(':'); //Default to Noon int hr = 12; int mn = 0; int sc = 0; if (!string.IsNullOrEmpty(timeSpan[0])) { hr = Convert.ToInt32(timeSpan[0]); } else { isGoodParms = false; } if (!string.IsNullOrEmpty(timeSpan[1])) { mn = Convert.ToInt32(timeSpan[1]); } else { isGoodParms = false; } if (!string.IsNullOrEmpty(timeSpan[2])) { sc = Convert.ToInt32(timeSpan[2]); } else { isGoodParms = false; } if (isGoodParms == true ) { TimeSpan currentTimeSpan = new TimeSpan(hr, mn, sc); TimeSpan minTimeSpan = new TimeSpan(0, 0, 0); TimeSpan maxTimeSpan = new TimeSpan(0, 04, 59); if (currentTimeSpan &gt;= minTimeSpan &amp;&amp; currentTimeSpan &lt;= maxTimeSpan) { return true; } else { return false; } } else { return false; } } </code></pre>
30,553
<p>i've got a site with a lot of referenced .js-Files; those are rather small files, but I want to keep my methods separated by topic/functionality.</p> <p>Is it better to keep all the methods in one .js-File or is it no problem to have many (~ 20 - 30) small files all including only some lines?</p>
<p>By all means keep them separate for development, but you should consider bundling them together into one file for production.</p> <p>There is a nice discussion at <a href="http://www.sitepoint.com/blogs/2007/04/10/faster-page-loads-bundle-your-css-and-javascript/" rel="nofollow noreferrer">sitepoint.com</a></p> <blockquote> <p>For each of these files, an HTTP request is sent to the server, and then the browser awaits a response before requesting the next file. Limits (or limitations) of the browser generally prevent parallel downloads. This means that for each file, you wait for the request to reach the server, the server to process the request, and the reply (including the file content itself) to reach you. Put end to end, a few of these can make a big difference to page load times.</p> </blockquote>
<p>Does anyone have a clever nant script which can do this for you? I've written a custom nant task which uses the YUI compressor to minify my css and js, but it would be useful to add combining to it. How do you guys handle this?</p>
40,934
<p>I'm new in the 3D priting and I bought a BIQU B1 printer :-)</p> <p>I printed the Pokemon with the white filament that come as a sample with the printer (PLA) and after that I bought the Inland PLA+ and PETG+ from Microcenter. The first thing that my son asked me to print is the toaster. Well, I tried to print three times with the PETG+ filament and always I end up after one or two layers with oozie everywhere and I had to stop printing. I replaced the filament with the PLA+ and now it's printing correctly (It's 91% complete right now :-) )</p> <p>So, I set the correct temperator for both filaments:</p> <ul> <li>PLA+ 205/60</li> <li>PETG+ 230/70</li> </ul> <p>I'm thinking that for this type of object (torture toaster) it doesn't work with PETG because of the complexity.</p> <p>Is that correct? If not, what I could be doing wrong with PETG+ filament?</p>
<blockquote> <p>What is this called</p> </blockquote> <p>This is called <strong>warping</strong>.</p> <p>Warping of prints occurs frequently when you use a filament that shrinks. If the model would shrink uniformly, it will become smaller, like in a scaled version (unfortunately, the print is attached somewhere, which causes stresses in the first layers). But, if (due to the geometry of the print) some part of the model shrinks more, the model warps. It could then bend upwards from the build plate, deform at higher layers or sometimes even crack (e.g. in between layers).</p> <blockquote> <p>and how do I avoid it?</p> </blockquote> <ul> <li>A high(er) build plate temperature</li> <li>Not use a filament that is prone to shrink, e.g. ABS is frequently replaced by PETG/NGEN/some other Co-polymer nowadays</li> <li>Decent adhesion by using everything you can image to get the filament to stick to the build platform: <ul> <li>A rough build plate surface, like e.g. BuildTak or equivalent</li> <li>An adhesive like glue stick or specific sprays like Dimafix or equivalent</li> <li>A slurry of ABS and acetone</li> </ul> </li> <li>Use an enclosure to raise the temperature of the build volume</li> <li>If an enclosure is impossible, use a draft shied (basically a multi layer skirt which creates a sort of a mini enclosure)</li> <li>Use a raft</li> <li>Don't use part fan cooling</li> </ul>
<p>You are getting warping. It's unusual in this case, as your overall model is relatively low profile. It's the taller stuff that likes to warp.</p> <p>Consider to edit your post to include the layer heights and also the filament type and filament and bed temperatures. My first instinct is that your bed temperature is too low. There's little harm to be had by raising the temperature by ten degrees or so. Also if your slicer arbitrarily reduces the bed temperature after the first layers, disable that feature. There's no sense to set a good adhesion temperature on a print and later reduce it, yet I've seen slicer results that do just that.</p> <p>Too cold filament by a substantial amount can also reduce the adhesion in combination with a too low bed temperature.</p> <p>If you still run into adhesion problems, the Elmer's Purple Glue Stick works wonders.</p> <p>With the new information comes new responses:</p> <p>For ABS, 80 °C is on the low end for the bed, but may work. The extruder temp is really low for ABS. I run 250 °C for ABS. Also ensure some form of enclosure, even a cardboard box will help. I've accidentally fed ABS into a PLA profile. The results were surprisingly good, although warping was prevalent and some underextrusion was evident.</p> <p>If you have a glass bed, you will very much want to use glue stick, as a release agent, not as an adhesive. ABS sticks really well to clean glass, well enough that it will pull fragments of glass from the surface!</p>
2,206
<p>I have a win form (c#) with a datagridview. I set the grid's datasource to a datatable.</p> <p>The user wants to check if some data in the datatable exists in another source, so we loop through the table comparing rows to the other source and set the rowerror on the datatable to a short message. The datagridview is not showing these errors. The errortext on the datagridviewrows are set, but no error displayed.</p> <p>Am I just expecting too much for the errors to show and they only show in the context of editing the data in the grid? </p> <p>I have been tinkering with this for a day and searched for someone that has posted a simalar issue to no avail - help!</p>
<p>Check that <code>AutoSizeRowsMode</code> is set to <code>DataGridViewAutoSizeRowsMode.None</code>. I have found that the row <code>Errortext</code> preview icon is not displayed when <code>AutoSizeRowsMode</code> is not set to the default of none.</p> <pre><code>DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None </code></pre>
<p>I believe that the errors will only show on editing. What you could do is add a bool column to your DataTable, which drives the display of an image/custom column in the DataGridView, reflecting whether there is an error or not.</p>
37,174
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
<p>This works on Mac OS X 10.5.5. Note the capital <strong>-U</strong> option. Perhaps that's been your problem.</p> <pre><code>import subprocess ps = subprocess.Popen("ps -U 0", shell=True, stdout=subprocess.PIPE) print ps.stdout.read() ps.stdout.close() ps.wait() </code></pre> <p>Here's the Python version</p> <pre><code>Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin </code></pre>
<p>It works if you use os instead of commands:</p> <pre><code>import os print os.system("ps -u 0") </code></pre>
19,379
<p>I am trying to set the disabled font characteristics for a Label Control. I can set all of the Font characteristics (size, bold, etc), but the color is overridden by the default windows behavior which seems to be one of these two colors:</p> <ul> <li>If background color is transparent then ForeColor is same as TextBox disabled Color.</li> <li>If background color is set to anything else, ForeColor is a Dark Gray color.</li> </ul> <p>The image below demonstrates the behavior -- Column 1 is Labels, Column 2 is TextBoxs, and Column 3 is ComboBoxes.</p> <p><img src="https://i.stack.imgur.com/60viN.png" alt="alt text"></p> <p>Edit -- Explaining the image: The first two rows are default styles for a label, textbox, and combobox. In the second two rows, I set the Background color to Red and Foreground to White. The disabled font style handling by Microsoft is inconsistent.</p>
<p>Have you tried implementing the EnabledChanged event? Or are you looking for more of a "styles" property on the control (as far as I know, they don't exist)?</p>
<p>Why is this an issue?</p> <p>I would personally let windows handle it. People are used to disabled items looking a certain way, so if you start trying to change every aspect of the way they look, you might start confusing your users.</p>
16,477
<p>Today our virtual W2003 server storing our SVN repository (too) became very-very busy. It turned out that it had only 88KB free space left on the C: drive. Not that good. Due to access problems, the only way we could reboot it by killing the busy processes from task manager (McAffee, SqlServer, services.exe) and then gracefully reboot. We freed up some space, the machine is happy again, but our SVN repository is not available anymore.</p> <p>If I connect from the client, it gives the message "<em>No repository found in 'svn://[mymachine]/repos/[myapp]'</em> " However, from the server I can see the content using "<em>svnlook tree [rootFolder]</em>" command.</p> <p>If I navigate to the root folder using Windows Explorer, the following folders are empty (I have no clue if that is normal):</p> <ul> <li><em>[rootFolder]/trunk</em> </li> <li><em>[rootFolder]/tags</em></li> <li><em>[rootFolder]/branches</em></li> </ul> <p>However, the <em>[rootFolder]/db</em> contains many files with the corresponding revision name. The size of the head should be around 600MB but we have also a number of branches. The total size of the [rootFolder] is now ~600MB. Did we loose the branches? Tomorrow we will also know if our backup system worked well. Anyway, does anyone has any idea?</p> <p><em>[Update after solution found]</em></p> <p>Thanx for all who submitted answers, they were very useful in resolving the trouble. During the crash, the SVN service got corrupted, while the data remained intact. Reinstallation of the service has solved the problem.</p>
<p>Editing is implemented as a method on your UITableView’s delegate object. In your table controller, have whatever control activates editing call this:</p> <pre><code>[tableView setEditing: YES animated: YES]; </code></pre> <p>Then, make sure that your delegate object implements this:</p> <pre><code>- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Delete" message: @"Do you really want to delete “George W. Bush”?" delegate: self cancelButtonTitle: @"Cancel" otherButtonTitles: @"Of course!", nil]; } } </code></pre> <p>…or a more standard action might be:</p> <pre><code>[itemList removeObjectAtIndex:indexPath.row]; [table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; </code></pre>
<p>I would implement a subclass of UITableViewCell and handle touch events in there. You would likely have to do all the animation stuff yourself, but I think it's probably the easiest solution. There's not a "Supported" method for changing the delete button, I don't think</p>
46,983
<p>I'm trying to determine the reason for a stalled process on Linux. It's a telecom application, running under fairly heavy load. There is a separate process for each of 8 T1 spans. Every so often, one of the processes will get very unresponsive - up to maybe 50 seconds before an event is noted in the normally very busy process's log.</p> <p>It is likely some system resource that runs short. The obvious thing - CPU usage - looks to be OK. </p> <p>Which linux utilities might be best for catching and analyzing this sort of thing, and be as unobtrusive about it as possible, as this is a highly loaded system? It would need to be processes rather than system oriented, it would seem. Maybe ongoing monitoring of /proc/pid/XX? Top wouldn't seem to be too useful here.</p>
<p>If you are able to spot this "moment of unresponsiveness", then you might use strace to attach to the process in question during that time and try to figure out where it "sleeps":</p> <pre><code>strace -f -o LOG -p &lt;pid&gt; </code></pre> <p>More lightweight, but less reliable method:</p> <ol> <li><p>When process hangs, use top/ps/gdp/strace/ltrace to find out the state of the process (e.g. whether it waits in "select" or consumes 100% cpu in some library call)</p></li> <li><p>Knowing the general nature of the call in question, tailor the invocation of strace to log specific syscalls or groups of syscall. For example, to log only file access-related syscalls, use:</p> <pre><code>strace -e file -f -o LOG .... </code></pre></li> </ol> <p>If the strace is too heavy a tool for you, try monitoring:</p> <ol> <li><p>Memory usage with "vmstat 1 > /some/log" - maybe process is being swapped in (or out) during that time</p></li> <li><p>IO usage with vmstat/iotop - maybe some other process is thrashing the disks</p></li> <li><p>/proc/interrupts - maybe driver for your T1 card is experiencing problems?</p></li> </ol>
<p>Thanks - strace sounds useful. Catching the process at the right time will be part of the fun. I came up with a scheme to periodically write a time stamp into shared memory, then monitor with another process. Sending a SIGSTOP would then let me at least examine the application stack with gdb. I don't know if strace on a paused process will tell me much, but I could maybe then turn on strace and see what it will say. Or turn on strace and hit the process with a SIGCONT.</p>
27,577
<p>Last week I implemented a date validation in our front end, a combination of ASP.NET and heavily dependent on lots of JavaScript code to avoid server round-trips until a form is actually saved. I felt it clumsy that this rule check is not done on the server, but our current architecture and performance requirements prevent this. It's out of my hands for now.</p> <p>Ideally, this check should be done in both places, but then the server side check would be done with neat, typed, C#, and immediately visible to developers working on that BO, and the client side check is actually done by not even a copy, which is dodgy, but completely different code.</p> <p>What ways could there be to actually duplicate the server side check on the client side? Using a rule engine, and having an identical rule applied by two trusted rule engines on each side, actually delegating the server check to be done by JavaScript, which is then registered in the rendered client seems like another option, but seems challenging.</p> <p>Any ideas on this rather academic versus practical question? </p>
<p>ASP.NET's Validation Controls can do this.</p> <blockquote> <p>ASP.NET validation controls also provide two ways of validation: Server-side or Client-side. The nice thing about these Validation controls is that it will preform client-side validation when it detects the browser is able (unless client-side validation has been disabled). Thus reducing roundtrips. And it will preform server-side where necessary. This client-side/server-side detection and validation is done without extra work by the developer!</p> </blockquote> <p><a href="http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=46" rel="nofollow noreferrer">http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=46</a></p> <p>Otherwise, you would have to follow the same model. Create set rules, then implement each of them on both sides (in controls, if you can). Then, allow the developer to select which rule to apply to which html controls.</p>
<p>I think a simple rule engine is your best option. Depending on the validation you want to perform it needn't be too complex.</p> <p>Anything else will involve additional round trips to the server (to perform all validation in C#) or getting the server to execute the JavaScript (which is much harder, I believe, than implementing a rules engine).</p> <p>The only alternative is duplicating the code (just as Microsoft does).</p>
33,254
<p>We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database etc. Which language will be the easiest and fastest to work with? (It is a web-app)</p>
<p>A dynamic language rules for this. Why? The mappings are easy to code and change. You don't have to recompile and rebuild.</p> <p>Indeed, with a little cleverness, you can have your "XML XPATH to a Tag -> DB table-field" mappings as disjoint blocks of Python code that your main application imports.</p> <p>The block of Python code <strong>is</strong> your configuration file. It's not an <code>.ini</code> file or a <code>.properties</code> file that describes a configuration. It <strong>is</strong> the configuration.</p> <p>We use Python, xml.etree and the SQLAlchemy (to separate the SQL out of your programs) for this because we're up and running with very little effort and a great deal of flexibility.</p> <hr> <p><strong>source.py</strong></p> <pre><code>"""A particular XML parser. Formats change, so sometimes this changes, too.""" import xml.etree.ElementTree as xml class SSXML_Source( object ): ns0= "urn:schemas-microsoft-com:office:spreadsheet" ns1= "urn:schemas-microsoft-com:office:excel" def __init__( self, aFileName, *sheets ): """Initialize a XML source. XXX - Create better sheet filtering here, in the constructor. @param aFileName: the file name. """ super( SSXML_Source, self ).__init__( aFileName ) self.log= logging.getLogger( "source.PCIX_XLS" ) self.dom= etree.parse( aFileName ).getroot() def sheets( self ): for wb in self.dom.getiterator("{%s}Workbook" % ( self.ns0, ) ): for ws in wb.getiterator( "{%s}Worksheet" % ( self.ns0, ) ): yield ws def rows( self ): for s in self.sheets(): print s.attrib["{%s}Name" % ( self.ns0, ) ] for t in s.getiterator( "{%s}Table" % ( self.ns0, ) ): for r in t.getiterator( "{%s}Row" % ( self.ns0, ) ): # The XML may not be really useful. # In some cases, you may have to convert to something useful yield r </code></pre> <p><strong>model.py</strong></p> <pre><code>"""This is your target object. It's part of the problem domain; it rarely changes. """ class MyTargetObject( object ): def __init__( self ): self.someAttr= "" self.anotherAttr= "" self.this= 0 self.that= 3.14159 def aMethod( self ): """etc.""" pass </code></pre> <p><strong>builder_today.py</strong> One of many mapping configurations</p> <pre><code>"""One of many builders. This changes all the time to fit specific needs and situations. The goal is to keep this short and to-the-point so that it has the mapping and nothing but the mapping. """ import model class MyTargetBuilder( object ): def makeFromXML( self, element ): result= model.MyTargetObject() result.someAttr= element.findtext( "Some" ) result.anotherAttr= element.findtext( "Another" ) result.this= int( element.findtext( "This" ) ) result.that= float( element.findtext( "that" ) ) return result </code></pre> <p><strong>loader.py</strong></p> <pre><code>"""An application that maps from XML to the domain object using a configurable "builder". """ import model import source import builder_1 import builder_2 import builder_today # Configure this: pick a builder is appropriate for the data: b= builder_today.MyTargetBuilder() s= source.SSXML_Source( sys.argv[1] ) for r in s.rows(): data= b.makeFromXML( r ) # ... persist data with a DB save or file write </code></pre> <hr> <p>To make changes, you can correct a builder or create a new builder. You adjust the loader source to identify which builder will be used. You can, without too much trouble, make the selection of builder a command-line parameter. Dynamic imports in dynamic languages seem like overkill to me, but they are handy.</p>
<p>If you are well versed in Java, you can try out <a href="https://vtd-xml.sourceforge.io/" rel="nofollow noreferrer">VTD</a> XML Parser for parsing large volumes of XML data.</p>
38,684
<p>Is there any free software tool or combination that allows me to identify the pitch of a recorded singing session?</p> <p>The idea is to display some kind of graph with the current pitch in a time line along with markers for the standard notes (C3, C#3, D, etc). I don't need pitch correction and I don't need it to be done in real time, either.</p> <p>I know that once there was a plugin for Rosegarden that did that, but it has gone missing.</p>
<p>Checkout <a href="http://audacity.sourceforge.net/" rel="nofollow noreferrer">Audacity</a>. It came out of a project to do musical pitch analysis. </p>
<p>Not exactly what you are looking for, but the Singstar lookalike Ultrastar-NG at least does something like this. <a href="http://ultrastar-ng.sourceforge.net/" rel="nofollow noreferrer">http://ultrastar-ng.sourceforge.net/</a></p>
19,262
<p><a href="https://stackoverflow.com/questions/106597/why-are-fixnums-in-emacs-only-29-bits">The fixnum question</a> brought my mind to an other question I've wondered for a long time.</p> <p>Many online material about garbage collection does not tell about how runtime type information can be implemented. Therefore I know lots about all sorts of garbage collectors, but not really about how I can implement them.</p> <p>The fixnum solution is actually quite nice, it's very clear which value is a pointer and which isn't. What other commonly used solutions for storing type information there is?</p> <p>Also, I wonder about fixnum -thing. Doesn't that mean that you are being limited to fixnums on every array index? Or is there some sort of workaround for getting full 64-bit integers?</p>
<p>Basically to achieve accurate marking you need meta-data indicating which words are used as pointers and which are not.</p> <p>This meta-data could be stored per reference, as emacs does. If for your language/implementation you don't care much about memory use, you could even make references bigger than words (perhaps twice as big), so that every reference can carry type information as well as its one-word data. That way you could have a fixnum the full size of a 32 bit pointer, at the cost of references all being 64 bit.</p> <p>Alternatively, the meta-data could be stored along with other type information. So for example a class could contain, as well as the usual function pointer table, one bit per word of the data layout indicating whether or not the word contains a reference that should be followed by the garbage collector. If your language has virtual calls then you must already have a means of working out from an object what function addresses to use, so the same mechanism will allow you to work out what marking data to use - typically you add an extra, secret pointer at the start of every single object, pointing to the class which constitutes its runtime type. Obviously with certain dynamic languages the type data pointed to would need to be copy-on-write, since it is modifiable.</p> <p>The stack can do similar - store the accurate marking information in data sections of the code itself, and have the garbage collector examine the stored program counter, and/or link pointers on the stack, and/or other information placed on the stack by the code for the purpose, to determine which code each bit of stack relates to and hence which words are pointers. Lightweight exception mechanisms tend to do a similar thing to store information about where try/catch occurs in the code, and of course debuggers need to be able to interpret the stack too, so this can quite possibly be folded in with a bunch of other stuff you'd already be doing to implement any language, including ones with built-in garbage collection.</p> <p>Note that garbage collection doesn't necessarily need accurate marking. You could treat every word as a pointer, regardless of whether it really is or not, look it up in your garbage collector's "big list of everything" to decide whether it plausibly could refer to an object that has not yet been marked, and if so treat it as a reference to that object. This is simple, but the cost of course is that it's somewhere between "quite slow" and "very slow", depending on what data structures your gc uses for the lookup. Furthermore, sometimes an integer just so happens to have the same value as the address of an unreferenced object, and causes you to keep a whole bunch of objects which should have been collected. So such a garbage collector cannot offer strong guarantees about unreferenced objects ever being collected. This might be fine for a toy implementation or first working version, but is unlikely to be popular with users. </p> <p>A mixed approach might, say, do accurate marking of objects, but not of regions of the stack where things get particularly hairy. For example if you write a JIT which can create code where a referenced object address appears only in registers, not in your usual stack slots, then you might need to non-accurately follow the region of the stack where the OS stored the registers when it descheduled the thread in question to run the garbage collector. Which is probably quite fiddly, so a reasonable approach (potentially resulting in slower code) would be to require the JIT to always keep a copy of all pointer values it's using on the accurately marked stack.</p>
<p>In Squeak (also Scheme and many others dynamic languages I guess) you have <code>SmallInteger</code>, the class of signed 31-bit integers, and classes for arbitrarily big integers, e.g. <code>LargePositiveInteger</code>. There could very well be other representations, 64-something-bit integers either as full objects or with a couple bits as "I'm not a pointer" flags.</p> <p>But arithmetic methods are coded to handle over/under-flows, such that if you add one to <code>SmallInteger maxVal</code>, you get 2^30 + 1 as an instance of <code>LargePositiveInteger</code>, and if you subtract one back from it, you get back 2^30 as a <code>SmallInteger</code>.</p>
27,397
<p>We need to interface to 3rd party app, but company behind the app doesn't disclose message protocol and provides only Windows DLL to interface to.</p> <p>Our application is Linux-based so I cannot directly communicate with DLL. I couldn't find any existing solution so I'm considering writing socket-based bridge between Linux and Windows, however I'm sure it is not such a unique problem and somebody should have done it before.</p> <p>Are you aware of any solution that allows to call Windows DDL functions from C app on Linux? It can use Wine or separate Windows PC - doesn't matter.</p> <p>Many thanks in advance.</p>
<p>Any solution is going to need a TCP/IP-based "remoting" layer between the DLL which is running in a "windows-like" environment, and your linux app. </p> <p>You'll need to write a simple PC app to expose the DLL functions, either using a homebrew protocol, or maybe XML-RPC, SOAP or JSON protocols. The <a href="http://www.remobjectssdk.com" rel="noreferrer">RemObjects SDK</a> might help you - but could be overkill.</p> <p>I'd stick with a 'real' or virtualized PC. If you use Wine, the DLL developers are unlikely to offer any support.</p> <p>MONO is also unlikely to be any help, because your DLL is probably NOT a .NET assembly.</p>
<p>IMO, the best bet is to use Sockets. I have done this previously and it works like a charm. </p>
48,931