input
stringlengths
51
42.3k
output
stringlengths
18
55k
Changing tables from MyISAM to InnoDB make the system slow <p>Hi I am using Mysql 5.0.x</p> <p>I have just changed a lot of the tables from MyISAM to InnoDB </p> <p>With the MyISAM tables it took about <strong>1 minute</strong> to install our database With the InnoDB it takes about <strong>15 minute</strong> to install the same database</p> <p><strong>Why does the InnoDB take so long?</strong></p> <p><strong>What can I do to speed things up?</strong></p> <p>The Database install does the following steps </p> <p>1) Drops the schema</p> <p>2) Create the schema</p> <p>3) Create tables</p> <p>4) Create stored procedures</p> <p>5) Insert default data </p> <p>6) Insert data via stored procedure</p> <p>EDIT:</p> <p>The Inserting of default data takes most of the time</p>
<p>Modify the Insert Data step to start a transaction at the start and to commit it at the end. You will get an improvement, I guarantee it. (If you have a lot of data, you might want to break the transaction up to per table.)</p> <p>If you application does not use transactions at all, then you should set the paramater <code>innodb_flush_log_at_trx_commit</code> to 2. This will give you a lot of performance back because you will almost certainly have auto_commit enabled and this generates a lot more transactions than InnoDB's default parameters are configured for. This setting stops it unnecessarily flushing the disk buffers on every commit.</p>
How do I disable tabs for <a> tag <p>I am using tags for links on a web page. How do I disable tab key from selecting either of them. </p>
<p>Alternatively you could go for plain HTML solution.</p> <p><code> &lt;a href="http://foo.bar" tabindex="-1"&gt;inaccessible by tab link&lt;/a&gt; </code></p> <p>The <a href="http://www.w3.org/TR/html5/editing.html#attr-tabindex">HTML5 spec says</a>:</p> <blockquote> <p><strong>If the value is a negative integer</strong><br> The user agent must set the element's tabindex focus flag, but should not allow the element to be reached using sequential focus navigation.</p> </blockquote>
What's the difference between $(...) and `...` <p>The question is as simple as stated in the title: What's the difference between the following two expressions?</p> <pre><code>$(...) `...` </code></pre> <p>For example, are the two variables <code>test1</code> and <code>test2</code> different?</p> <pre><code>test1=$(ls) test2=`ls` </code></pre>
<p>The result is the same, but the newer $() syntax is far clearer and easier to read. At least doubly so when trying to nest. Nesting is not easy with the old syntax, but works fine with the new.</p> <p>Compare:</p> <pre><code>$ echo $(ls $(pwd)) </code></pre> <p>versus:</p> <pre><code>$ echo `ls \`pwd\`` </code></pre> <p>You need to escape the embedded backticks, so it's quite a lot more complicated to both type and read.</p> <p>According to <a href="http://tldp.org/LDP/abs/html/commandsub.html" rel="nofollow">this page</a>, there is at least one minor difference in how they treat embedded double backslashes.</p>
The Most Efficient Algorithm to Find First Prefix-Match From a Sorted String Array? <p>Input:</p> <p>1) A huge sorted array of string SA;</p> <p>2) A prefix string P;</p> <p>Output:</p> <p>The index of the first string matching the input prefix if any. If there is no such match, then output will be -1.</p> <p>Example: SA = {"ab", "abd", "abdf", "abz"} P = "abd" The output should be 1 (index starting from 0).</p> <p>What's the most algorithm way to do this kind of job?</p>
<p>If you only want to do this once, use <a href="http://en.wikipedia.org/wiki/Binary_search">binary search</a>, if on the other hand you need to do it for many different prefixes but on the same string array, building a <a href="http://en.wikipedia.org/wiki/Radix_tree">radix tree</a> can be a good idea, after you've built the tree each look up will be very fast.</p>
Symfony Propel criteria <p>Is there any possible way to convert the MySQL object into criteria object? I tried this query:</p> <pre><code>select p.disrepid, p.subject, p.body, c.disrepid as disrepid1, c.subject as subject1, c.body as body1 from discusreply as p, discusreply as c where p.distopid=' . $this-&gt;id . ' and (c.disrepid = p.parentid or c.parentid = p.distopid) order by p.disrepid ASC </code></pre> <p>I tried a lot for converting this query into a <code>Criteria</code>, But nothing happened. I want this criteria object for passing this into Pager class for completing the pagination. <code>$pager-&gt;setCriteria($c);</code>.</p>
<p>You can use your own SQL do perform a query, but there is no automated way to turn sql into a Criteria object. </p> <pre><code>$con = Propel::getConnection(DATABASE_NAME); $sql = "SELECT books.* FROM books WHERE NOT EXISTS (SELECT id FROM review WHERE book_id = book.id)"; $stmt = $con-&gt;createStatement(); $rs = $stmt-&gt;executeQuery($sql, ResultSet::FETCHMODE_NUM); $books = BookPeer::populateObjects($rs); </code></pre> <p>This bypasses Criterion objects all together. You mentioned wanting a criteria object so you could feed this into a pager. You can instead set a custom select method into your pager, which will then perform your custom query. If you need to pass a parameter into this, I would recommend extending sfPropel with your own pager class that can optionally pass parameters to your peer select methods so you don't have to use Criteria objects at all. As a quick alternative, you can do something like this, using your Criteria as a container for your select parameters:</p> <pre><code>$c = new Criteria(); $c-&gt;add(DiscussreplyPeer::ID, $myId); $pager = new sfPropelPager(); $pager-&gt;setCriteria($c); $pager-&gt;setPeerMethod('getReplies'); </code></pre> <p>And then in your peer class:</p> <pre><code>public static function getReplies(Criteria $c) { $map = $c-&gt;getMap(); $replyId = $map[DiscussreplyPeer::ID]-&gt;getValue(); $con = Propel::getConnection(DATABASE_NAME); $sql = "select p.disrepid, p.subject, p.body, c.disrepid as disrepid1, c.subject as subject1, c.body as body1 from discusreply as p, discusreply as c where p.distopid=? and (c.disrepid = p.parentid or c.parentid = p.distopid) order by p.disrepid ASC"; $stmt = $con-&gt;prepareStatement($sql); $stmt-&gt;setString(1, $replyId); $rs = $stmt-&gt;executeQuery(); $results = array(); while ($rs-&gt;next()) { // for example $results['disrepid'] = $rs-&gt;getInt('disrepid'); } return $results; } </code></pre> <p>More tips on propel and symfony can be found at: <a href="http://stereointeractive.com/blog/2007/06/12/propel-queries-using-custom-sql-peer-classes-and-criterion-objects/">http://stereointeractive.com/blog/2007/06/12/propel-queries-using-custom-sql-peer-classes-and-criterion-objects/</a></p>
Syntax Prob: Using Variables in Stored Procedures <p>Can anyone tell how correct the following code below. Iam tryin to create a stored procedure that returns the rowcount of a table whose name is passed to it.</p> <pre><code>CREATE PROCEDURE spROWCOUNTER ( @tablename nvarchar(20) @rowCountVal int OUTPUT ) AS DECLARE @strQuery nvarchar(300) SET @strQuery = 'SELECT @rowCountVal=COUNT(*) FROM '+@tablename EXEC(@strQuery) RETURN @rowCountVal </code></pre> <p>ERROR MESSAGE : </p> <ul> <li>Incorrect syntax near '@rowCountVal' </li> <li>Must declare scalar variable '@tablename' </li> <li>Must declare scalar variable '@rowCountVal'</li> </ul> <p><hr /></p> <p>whereas the code below works fine</p> <pre><code>ALTER PROCEDURE spROWCOUNTER ( @rowCountVal int OUTPUT ) AS SELECT @rowCountVal=COUNT(*) FROM DEFECT_LOG RETURN @rowCountVal </code></pre>
<pre><code>CREATE PROCEDURE spROWCOUNTER @tablename nvarchar(20), @rowCountVal int OUTPUT AS SELECT @rowCountVal = ISNULL(SUM(spart.rows), 0) FROM sys.partitions spart WHERE spart.object_id = object_id(@tablename) AND spart.index_id &lt; 2 RETURN @rowCountVal </code></pre>
C# How can I hide the cursor in a winforms app? <p>Im developing a touchscreen app and I need to hide the cursor whenever it is within the main Form. </p> <p>Any ideas?</p>
<p>I knew this was a stupid question! Simply put</p> <pre><code>Cursor.Hide(); </code></pre> <p>is all I needed in the forms constructor.</p>
C#: How to convert BITMAP byte array to JPEG format? <p>How can I convert a BITMAP in byte array format to JPEG format using .net 2.0?</p>
<p>What type of <code>byte[]</code> do you mean? The raw file-stream data? In which case, how about something like (using <code>System.Drawing.dll</code> in a client application):</p> <pre><code> using(Image img = Image.FromFile("foo.bmp")) { img.Save("foo.jpg", ImageFormat.Jpeg); } </code></pre> <p>Or use <code>FromStream</code> with a <code>new MemoryStream(arr)</code> if you really do have a <code>byte[]</code>:</p> <pre><code> byte[] raw = ...todo // File.ReadAllBytes("foo.bmp"); using(Image img = Image.FromStream(new MemoryStream(raw))) { img.Save("foo.jpg", ImageFormat.Jpeg); } </code></pre>
MovieClipLoader fails (has something to do with cache) <p>I have a small flash file that just loads and shows one image scaled to fit inside the content area. We use these with a javascript gallery so we have several instances on one html page (embedded with swfObject) I've been using MovieClipLoader to load the jpgs but it no longer works. </p> <p>We updated the server and as far as I know only relevant thing that has changed is cache related. Previously all images and swfs were always reloaded. Now they should be loaded from cache.</p> <p>I can see from firebug that the swf is actually loading the jpg it just doesn't display anything. This happens on many browser/os/flash plugin combinations. Sometimes some of the images show, sometimes none. </p> <p>The code inside moviecliploader event handlers (onloadinit, onloaderror) is never run. </p> <p>Any ideas on how to get this working would be appreciated.</p>
<p>I've had troubles in the past when using multiple instances of MovieClipLoader. Similar to you, some of the loaders seemed to timeout, never displaying the image they were supposed to load. I was told this is due to HTTP simultaneous thread limitations, supposedly two downloads at a time(but never got confirmation on that).</p> <p>This is especially true if you're using multiple swf files on the page, rather than one main flash that loads them all. </p> <p>I had resolved this by creating a simple queuing system in flash, where a maximum of two movieClipLoaders would be loading at the same time. Whenever one finished, it triggered the next download, and so on until all downloads were processed. That worked very well.</p>
Async Method Call <p>How can I call a method asynchronously ?</p>
<p>How to call a Visual C# method asynchronously:<br /> <a href="http://support.microsoft.com/kb/315582" rel="nofollow">http://support.microsoft.com/kb/315582</a></p>
How to generate a hash value in J2ME? <p>How can I generate hash value for a byte array, in J2ME?</p> <p>It doesn't have to be very very secure but it should be fast.</p>
<p>As suggested by Josh Bloch in his Effective Java book:</p> <pre><code>public int hashCode() { int result = 17; for (int i = 0; i &lt; array.length; i++) { result = 31*result + (int)array[i]; } return result; } </code></pre>
C# Is holding data in a delimited string bad practice <p>Is it bad practice to have a string like "name=Gina;postion= HouseMatriarch;id=1234" to hold state data in an application.I know that I could just as well have a struct , class or hashtable to hold this info. </p> <p>Is it acceptable practice to hold delimited key/value pairs in a database field– just for use in where the data type is not known at design time. </p> <p>Thanks...I am just trying to insure that I maintain good design practices</p>
<p>Yes, holding your data in a string like "name=Gina;postion= HouseMatriarch;id=1234" is very bad practice. This data structure should be stored in structs or objects, because it is hard to access, validate and process the data in a string. It will take you much more time to write the code to parse your string to get at your data than just using the language structures of C#.</p> <p>I would also advise against storing key/value pairs in database fields if the other option is just adding columns for those fields. If you don't know the type of your data at design time, you are probably not doing the design right. How will you be able to build an application when you don't know what data types your fields will have to hold? Or perhaps you should elaborate on the context of the application to make the intent clearer. It is not all black and white :-)</p>
Good example problems to solve with threading <p>I have used threads one or two times to try and boost the performance of my code, with varying degrees of success. It is obvious that I need some more experience working with multi thread code. Are there any good programming problems to solve which will help to get a grip on using multiple threads to improve performance?</p> <p>It would be nice if it is a known/well explored problem so that after I have botched a couple of attempts I can read some literature on how it should be done. </p> <p>-- edit</p> <p>I am interested in using parallelism to speed up applications in general, as I have heard/read a lot recently about processors increasing power through parallelism rather than speed. I know vaguely of barbers/philosophers but was looking for something a little more practical, to gain hands on experience. </p>
<p>The standard multithreaded problem is the <a href="http://en.wikipedia.org/wiki/Producer-consumer_problem" rel="nofollow">producer-consumer problem</a>. It exists in various flavors that highlight different problems with multithreaded applications. The link I referenced also has several other threading problems listed at the bottom of the page.</p>
How to throttle login attemps in Java webapp? <p>I want to implement an efficient mechanism to throttle login attemps in my Java web application, to prevent brute-force attacks on user accounts.</p> <p><a href="http://www.codinghorror.com/blog/archives/001206.html" rel="nofollow">Jeff explained the why, but not the how.</a></p> <p>Simon Willison showed an <a href="http://simonwillison.net/2009/Jan/7/ratelimitcache/" rel="nofollow">implementation in Python for Django</a>: That doesn't really help me along as I can't use memcached nor Django.</p> <p>Porting his ideas from scratch doesn't seem like a great either - I don't want to reinvent the wheel.</p> <p>I found one <a href="https://svn.igniterealtime.org/svn/repos/openfire/tags/openfire_3_6_0a/src/java/org/jivesoftware/admin/LoginLimitManager.java" rel="nofollow">Java implementation</a>, though it seems rather naiive: Instead of a LRU cache, it just clears all entries after 15 minutes.</p> <p>EHCache could be an alternative for memcached, but I don't have any experience with it and don't really want to intoduce yet another technology if there are better alternatives for this task.</p> <p>So, whats a good way to implement login throttling in Java?</p>
<p>I think even EHCache is killing a fly with a napalm bomb. The problem is simple and so is the implementation.</p> <p>I suggest using a servlet filter a the top level so that as little processing as possible is done.</p> <p>Create a class to store the following:</p> <ul> <li>The number of attempts (count)</li> <li>The time</li> </ul> <p>Now, the code is simple in a sunchronized block:</p> <pre><code>if userid not in attemptMap: attemptMap.add ( userid, new attemptItem ( userid, 1, now ) ) else tmp = attemptMap.get ( userid ) if (acquire lock for tmp) : if tmp.time + 30 &gt; now : tmp.count = 0 tmp.time = now tmp.count++ if tmp.count &gt; 3 : error=true release lock for tmp else : error=true </code></pre> <p>thats it man (as long as the code is synchronized).</p>
Which character set to choose when compiling a c++ dll <p>Could someone give some info regarding the different character sets within visual studio's project properties sheets.</p> <p>The options are:<br /> None<br /> Unicode<br /> Multi byte</p> <p>I would like to make an informed decision as to which to choose.<br /> Thanks.</p>
<p>All new software should be Unicode enabled. For Windows apps that means the UTF-16 character set, and for pretty much everyone else UTF-8 is often the best choice. The other character set choices in Windows programming should only be used for compatibility with older apps. They do not support the same range of characters as Unicode.</p>
Organization of many forms on many pages <p>I have a web app I'm building that has about 50 forms.</p> <p>I have a very nice form-building class that handles the creation and submission of these forms very nicely and it's wrapped with error handlers, etc. No help needed there.</p> <p>However, the forms are scattered through 120 pages. I could really use some weigh in from you guys about the ideal organization structure for these pages/forms. Here are some ideas. Both have pros and cons.</p> <ol> <li><p>Each page, in the header, creates the form there detects the presence of a $_POST['action'] variable and processes the forms there.</p></li> <li><p>Each form is built by a function in a form functions file and returns the form object when it's called in the header of the page, and when processing, since $_POST is a superglobal the processing functions is called in the header of the page as well.</p></li> <li><p>For each page such as profile.php include a file in the header that includes a profile.forms.php in which the method #1 or #2 above happens.</p></li> </ol> <p>Ideas?</p> <p><hr /></p> <p>Just a note, there will rarely be more than one form per page.</p>
<p>Go for 3. - it will be easier to maintain the code later than to change 120 pages one by one.</p>
PickupDirectoryFromIis, Sender property and SMTP MAIL FROM envelope <p>When you send an email using <code>System.Net.Mail</code> you can set the SMTP MAIL FROM envelope by using the <code>MailMessage.Sender</code> Property.</p> <p>If you set the smtp network <code>deliveryMethod</code> property to be "Network", the MAIL FROM envelope is set using the Sender value.</p> <p>If you set the smtp network <code>deliveryMethod</code> property to be "PickupDirectoryFromIis", the MAIL FROM envelope uses the <code>MailMessage.From</code> property instead of the Sender one.</p> <p>I need to keep PickupDirectoryFromIis as my <code>deliveryMethod</code> for performance concern.</p> <p>Any suggestion how to keep the value I need for the SMTP MAIL FROM envelope?</p> <p>Thanks in advance.</p>
<p>What about if you use:</p> <pre><code> &lt;smtp deliveryMethod="SpecifiedPickupDirectory" from="me@mydomain.com"&gt; &lt;specifiedPickupDirectory pickupDirectoryLocation="c:\Temp\Mail" /&gt; &lt;/smtp&gt; </code></pre> <p>??</p>
Is it possible to view all services/types registered to StructureMap? <p>I am just trying out structuremap and would like to be able to see which of my classes are registered for which service.</p> <p>For example with castle windsor I can bring up the debugger and view container.Kernel.GraphNodes to see a list of all currently registered service/type pairings.</p> <p>Is there a similar view into StructureMap internals? Again, this is only something I intend to use to help familiarize myself with its registry dsl.</p>
<p>ObjectFactory.WhatDoIHave() or container.WhatDoIHave() where container is a Container. A link might be useful : <a href="http://nhibernate.codebetter.com/blogs/jeremy.miller/archive/2008/11/30/a-gentle-quickstart-for-structuremap-2-5.aspx" rel="nofollow">http://nhibernate.codebetter.com/blogs/jeremy.miller/archive/2008/11/30/a-gentle-quickstart-for-structuremap-2-5.aspx</a></p>
Keep HTML tags in XML using LINQ to XML <p>I have an xml file from which I am extracting html using LINQ to XML. This is a sample of the file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;tips&gt; &lt;tip id="0"&gt; This is the first tip. &lt;/tip&gt; &lt;tip id="1"&gt; Use &lt;b&gt;Windows Live Writer&lt;/b&gt; or &lt;b&gt;Microsoft Word 2007&lt;/b&gt; to create and publish content. &lt;/tip&gt; &lt;tip id="2"&gt; Enter a &lt;b&gt;url&lt;/b&gt; into the box to automatically screenshot and index useful webpages. &lt;/tip&gt; &lt;tip id="3"&gt; Invite your &lt;b&gt;colleagues&lt;/b&gt; to the site by entering their email addresses. You can then share the content with them! &lt;/tip&gt; &lt;/tips&gt; </code></pre> <p>I am using the following query to extract a 'tip' from the file:</p> <pre><code>Tip tip = (from t in tipsXml.Descendants("tip") where t.Attribute("id").Value == nextTipId.ToString() select new Tip() { TipText= t.Value, TipId = nextTipId }).First(); </code></pre> <p>The problem I have is that the Html elements are being stripped out. I was hoping for something like InnerHtml to use instead of Value, but that doesn't seem to be there.</p> <p>Any ideas?</p> <p>Thanks all in advance,</p> <p>Dave</p>
<p>Call <code>t.ToString()</code> instead of <code>Value</code>. That will return the XML as a string. You may want to use the overload taking SaveOptions to disable formatting. I can't check right now, but I suspect it will include the element tag (and elements) so you would need to strip this off.</p> <p>Note that if your HTML isn't valid XML, you will end up with an invalid overall XML file.</p> <p>Is the format of the XML file completely out of your control? It would be nicer for any HTML inside to be XML-encoded.</p> <p>EDIT: One way of avoiding getting the outer part might be to do something like this (in a separate method called from your query, of course):</p> <pre><code>StringBuilder builder = new StringBuilder(); foreach (XNode node in element.Nodes()) { builder.Append(node.ToString()); } </code></pre> <p>That way you'll get HTML elements with their descendants and interspersed text nodes. Basically it's the equivalent of InnerXml, I strongly suspect.</p>
Needed: Wrappable Counter where < and > do "the right thing", language C <p>I need the code to a couter that is allowed to overflow and where &lt; > continue to tell earlier values from later values, for some defined interval. </p> <p>To clarify, one possible implementation would be:</p> <p>Consider two such counters <code>cur</code> and <code>dut</code> (device under test), consider two functions:</p> <pre><code>bool isEarlier(cur, dut) // Is dut earlier than cur? bool isLater(cur, dut) </code></pre> <p><code>cur</code> and <code>dut</code> are 16 bit, <code>cur</code> has just overflowed, its current value is, lets say <code>5</code>. Depending on the value of <code>dut</code>, the functions would return </p> <ul> <li>0 to 16384: isEarlier -> <code>(cur &lt; dut)</code>, isLater -> <code>(cur &gt; dut)</code></li> <li>16384 to 32768: isEarlier -> false, isLater -> true </li> <li>32768 to 49152: invalid, log error</li> <li>49152 to 65536: isEarlier -> true, isLater -> false</li> </ul> <p><strong>Update</strong>: I can write the code myself, no problem. I'm just lazy. I know for fact that there is something like that in PostgreSQL (transaction ids wrap), I just couldn't locate the function that actually does it. I am pretty sure there is something like that in the Linux kernel, probably a macro. But neighther google codesearch, nor grep over /usr/include/linux could turn it up. Any ideas where it is?</p> <p><strong>Update</strong>: Clarified role of cur and dut. The "invalid" is there as a safeguard. As the differences between cur and dut become bigger, the function eventually complains.</p>
<p>I think you're talking about handling the wraparound of the number circle correctly. It's quite easy, actually.</p> <p>This doesn't do precisely what you said (not sure why you have that "exception" interval), but:</p> <pre><code>typedef unsigned short uint16_t; typedef signed short int16_t; // abstract out 16-bit types in case "short" doesn't correspond to 16bits bool isEarlier(uint16_t a, uint16_t b) { int16_t diff = a-b; return diff &lt; 0; } bool isLater(uint16_t a, uint16_t b) { int16_t diff = a-b; return diff &gt; 0; } </code></pre> <p><strong>edit</strong>: this has a "branch point" at diff=-32768, so that if a=5 and b=32772, diff=-32767 which is less than 0 and hence 5 is "earlier" than 32772. If a=5 and b=32774, diff=-32769=32767 which is greater than 0 and hence 5 is "later" than 32774. This defines "earlier" and "later" in the sense of (a) the simplest math, and (b) because wraparound counters can be interpreted as having multiple solutions mod 65536, it picks the solution of a and b that are "closest" to each other with respect to the number circle. </p> <p>If a and b differ by 32768 then they are equally far apart and the simple math is used to pick easiest... this "violates" the antisymmetric property of "earlier" and "later" in the sense that isLater(5,32773) is true and isLater(32773,5) is also true. But how do you know whether "5" represents a count of 5, or "5" represents a count of 65541? (just as abs(-32768) == -32768 gives an odd nonsensical answer) If you wish to maintain antisymmetry e.g. isLater(b,a) == isEarlier(a,b), then you can always do this:</p> <pre><code>bool isLater(uint16_t a, uint16_t b) { int16_t diff = b-a; return diff &lt; 0; } </code></pre> <p>If you wish to bias the branch point in one direction to happen at -32768+K, then use this instead:</p> <pre><code>bool isEarlier(uint16_t a, uint16_t b) { int16_t diff = a-b-K; return diff &lt; -K; } bool isLater(uint16_t a, uint16_t b) { int16_t diff = b-a-K; return diff &lt; -K; } </code></pre> <p>This no longer uses closest; if, for example, K=12768, and a=5, then for b=6,7,8,9,... 20005, isEarlier(a,b) and isLater(b,a) will be true, and for b=20006, 20007, ... 65534, 65535, 0, 1, 2, 3, 4, 5 isEarlier(a,b) and isLater(b,a) will be false.</p> <p>You have a particular choice of intervals which is different from the rationale I use with wraparound numbers. The functions defined here would not meet your needs as stated, but I find those choices of interval a little peculiar. Perhaps you could explain how you determined them?</p>
ICallBackEventHandler does not update controls with form values <p>I want to use ICallBackEventHandler however when I use it to call back to the server I find that my form control objects don't have the latest form values. Is there a way to force populate the values with the form data?</p> <p>Thanks.</p>
<p>Have a look at <a href="http://msdn.microsoft.com/en-us/magazine/cc163863.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/magazine/cc163863.aspx</a>.</p> <p>In short, you have to clear the variable '__theFormPostData', and call the 'WebForm_InitCallback()' before the 'CallbackEventReference' script. This updates the form values with the user input values. Something like this:</p> <pre><code>// from the above link string js = String.Format("javascript:{0};{1};{2}; return false;", "__theFormPostData = ''", "WebForm_InitCallback()", Page.GetCallbackEventReference(this, args, "CallbackValidator_UpdateUI", "null")); </code></pre>
Intercepting Method Access on the Host Program of IronPython <p>Greetings,</p> <p>Most of the information I see around concerning the construction of Proxies for objects assume that there exists a Type somewhere which defines the members to be proxied. My problem is: I can't have any such type.</p> <p>To make the problem simpler, what I have is a dictionary that maps strings to objects. I also have getters and setters to deal with this dictionary.</p> <p>My goal then is to provide transparent access inside IronPython to this getters and setters as if they were real properties of a class. For example, the following code in a python script:</p> <pre><code>x.result = x.input * x.percentage; </code></pre> <p>...would actually represent something like in the host language:</p> <pre><code>x.SetProperty("result", x.GetProperty("input") * x.GetProperty("percentage")); </code></pre> <p>Also, 'x' here is given by the host program. Any ideas? Please remember that I cannot afford the creation of a typed stub... Ideally, I would be happy if somehow I could intercept every call to an attribute/method of a specific object in the script language onto the host program.</p>
<p><a href="http://blogs.msdn.com/srivatsn/archive/2008/04/12/turning-your-net-object-models-dynamic-for-ironpython.aspx" rel="nofollow">This post</a> might be useful.</p>
Is there a better layout language than HTML for printing? <p>I'm using Python and Qt 4.4 and I have to print some pages. Initially I thought I'd use HTML with CSS to produce those pages. But HTML has some limitations.</p> <p>Now the question is: is there anything that's better than HTML but just (or almost) as easy to use? Additionally, it should be GPL-compatible.</p> <p><strong>Edit:</strong></p> <p><em>kdgregory &amp; Mark G:</em> The most obvious limitation is that I can't specify the printer margins. There is another problem: How do I add page numbers?</p> <p><em>Jeremy French:</em> One thing I have to print is a list of all the products someone ordered which can spread over a few pages.</p>
<p>I have been fighting with printed (or PDF) output from Python for 8 years now and so far I came across the following approaches (in order of personal preference):</p> <ul> <li>Using <a href="http://www.jaspersoft.com/JasperSoft_JasperReports.html?utm_source=google&amp;utm_medium=cpc&amp;utm_content=JasperReports&amp;utm_campaign=JasperReportsSearchjasperreports">JasperReports</a> via <a href="https://github.com/hudora/pyJasper">pyJasper</a> (written by me) or <a href="http://blogs.23.nu/c0re/2008/07/antville-18473/">JasperServer</a>. You can use the WYSIWYG design tool <a href="http://www.jaspersoft.com/JasperSoft_iReport.html">iReport</a> to define your layout. Your Python code will contact the Java based Jasper engine via HTTP and make it render a PDF (pyJasper handles that). We use that for a few thousand pages a day.</li> <li>Use plain text output. You can't get any faster. We use that for a few hundred pages per day.</li> <li>Use XSLT-FO. You also have to call a Java based rendering engine like FOB. Might result in performance issues but can be mitigated by having a long running Java server process - same approach than with Jasper. We use that for a few hundred pages per day but writing XSLT-FO documents made my head hurt. Not used for new code.</li> <li>Generate <a href="http://www.latex-project.org/">LaTeX</a> source and use a latex software package to render to PDF. Getting LaTeX to look like <strong>you</strong> like is quite difficult. But as long as you go with the provided LaTeX styles, you are fine. Not used in production at my shop.</li> <li>PDF generation with the <a href="http://www.reportlab.org/rl_toolkit.html">ReportLab Toolkit</a>. Somewhat low level. Even more low level: <a href="http://pypi.python.org/pypi/pyFPDF/">FPDF</a>. We use FPDF-Ruby for a few hundred pages a day. Took a lot of fiddeling to get the layout we wanted.</li> <li>Directly generate Postscript. Strange but you nearly can't get more in terms of speed and control. We used that to generate contact sheets with a few hundred thousand Jpegs per day. Takes fiddling but is fun.</li> <li>use <a href="http://www.troff.org/">troff</a>/groff to generate Postscript/PDF. Very low level bute nice to do simple, high volume things. Never used it thus in production.</li> </ul> <p>For orders, invoices and the like I highly recommend JasperReports. The ability to use a visual editor to define the layout is a huge time saver.</p>
What is the best way to implement 'Excel like column sizing' for an HTML table? <p>I want to allow the user to resize columns in an HTML table, using the same method as you would in Excel. Drag the space between columns and size.</p> <p>I did some research on this last year, and found a few hacks and kludges. Most were pretty bad, and I didn't find anything really good. Now, it looks like I need to implement this functionality, and want to do it right, so before I start this again, I just thought I'd ask if anybody else has done this, and how they did it.</p> <p>I believe I've seen a FogBugz demo video where they had this implemented. So I know it can be done well.</p> <p>BTW-I'd prefer not to use any open source frameworks, since my client may sell this app in the future.</p>
<p>I've built a html grid myself in the past and having done so my best advice would be: use someone else's. </p> <p>I've looked at this jquery grid control in the past but have never got around to trying it out: <a href="http://www.trirand.com/blog/" rel="nofollow">http://www.trirand.com/blog/</a></p>
XmlDocument dropping encoded characters <p>My C# application loads XML documents using the following code:</p> <pre><code>XmlDocument doc = new XmlDocument(); doc.Load(path); </code></pre> <p>Some of these documents contain encoded characters, for example:</p> <pre><code>&lt;xsl:text&gt;&amp;#10;&lt;/xsl:text&gt; </code></pre> <p>I notice that when these documents are loaded, <code>&amp;#10;</code> gets dropped.</p> <p>My question: How can I preserve <code>&lt;xsl:text&gt;&amp;#10;&lt;/xsl:text&gt;</code>?</p> <p>FYI - The XML declaration used for these documents:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; </code></pre>
<p>Are you sure the character is dropped? character 10 is just a line feed- it wouldn't exactly show up in your debugger window. It could also be treated as whitespace. Have you tried playing with the whitespace settings on your xmldocument?</p> <p><hr /></p> <p>If you need to preserve the encoding you only have two choices: a CDATA section or reading as plain text rather than Xml. I suspect you have absolutely 0 control over the documents that come into the system, therefore eliminating the CDATA option. </p> <p>Plain-text rather than Xml is probably distasteful as well, but it's all you have left. If you need to do validation or other processing you could first load and verify the xml, and then concatenate your files using simple file streams as a separate step. Again: not ideal, but it's all that's left.</p>
Standard way to embed version into python package? <p>Is there a standard way to associate version string with a python package in such way that I could do the following?</p> <pre><code>import foo print foo.version </code></pre> <p>I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in <code>setup.py</code> already. Alternative solution that I found was to have <code>import __version__</code> in my <code>foo/__init__.py</code> and then have <code>__version__.py</code> generated by <code>setup.py</code>.</p>
<p>Here is how I do this. Advantages of the following method:</p> <ol> <li><p>It provides a <code>__version__</code> attribute.</p></li> <li><p>It provides the standard metadata version. Therefore it will be detected by <code>pkg_resources</code> or other tools that parse the package metadata (EGG-INFO and/or PKG-INFO, PEP 0345).</p></li> <li><p>It doesn't import your package (or anything else) when building your package, which can cause problems in some situations. (See the comments below about what problems this can cause.)</p></li> <li><p>There is only one place that the version number is written down, so there is only one place to change it when the version number changes, and there is less chance of inconsistent versions.</p></li> </ol> <p>Here is how it works: the "one canonical place" to store the version number is a .py file, named "_version.py" which is in your Python package, for example in <code>myniftyapp/_version.py</code>. This file is a Python module, but your setup.py doesn't import it! (That would defeat feature 3.) Instead your setup.py knows that the contents of this file is very simple, something like:</p> <pre><code>__version__ = "3.6.5" </code></pre> <p>And so your setup.py opens the file and parses it, with code like:</p> <pre><code>import re VERSIONFILE="myniftyapp/_version.py" verstrline = open(VERSIONFILE, "rt").read() VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]" mo = re.search(VSRE, verstrline, re.M) if mo: verstr = mo.group(1) else: raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,)) </code></pre> <p>Then your setup.py passes that string as the value of the "version" argument to <code>setup()</code>, thus satisfying feature 2.</p> <p>To satisfy feature 1, you can have your package (at run-time, not at setup time!) import the _version file from <code>myniftyapp/__init__.py</code> like this:</p> <pre><code>from _version import __version__ </code></pre> <p>Here is <a href="https://tahoe-lafs.org/trac/zfec/browser/trunk/zfec/setup.py?rev=390#L84">an example of this technique</a> that I've been using for years.</p> <p>The code in that example is a bit more complicated, but the simplified example that I wrote into this comment should be a complete implementation.</p> <p>Here is <a href="https://tahoe-lafs.org/trac/zfec/browser/trunk/zfec/zfec/__init__.py?rev=363">example code of importing the version</a>.</p> <p>If you see anything wrong with this approach, please let me know: zooko at zooko dot com. If you don't see anything wrong with this approach then use it! Because the more packages come with their version numbers in the expected places the better!</p>
How to get proxy definitions from within an activeX <p>Ok, so here is the scenario:</p> <p>I have an activeX that uploads files using HttpWebRequest class. My problem is that I have to specify the network credentials in order to get the activeX to work properly behind a proxy server.</p> <p>Here is the code:</p> <pre><code>HttpWebRequest req = (HttpWebRequest)WebRequest.Create(m_url); req.Proxy = new WebProxy("http://myProxyServer:8080"); req.Proxy.Credentials = new NetworkCredential("user", "password", "domain"); </code></pre> <p>How can i get this information from iExplorer with no (or minimal) user interface?</p> <p>Thank You :)</p>
<p>I managed to do it ;)</p> <pre><code> private static WebProxy QueryIEProxySettings(string strFileURL) { HttpWebRequest WebReqt = (HttpWebRequest)HttpWebRequest.Create(strFileURL); WebProxy WP = new WebProxy(WebReqt.Proxy.GetProxy(new Uri(strFileURL))); WP.Credentials = CredentialCache.DefaultCredentials; return WP; } </code></pre>
Can IntelliJ create hyperlinks to the source code from log4j output? <p>In the IntelliJ console, stack traces automatically contain hyperlinks that bring you to the relevant source files. The links appear at the end of each line in the format (Log4jLoggerTest.java:25). I can configure log4j to output text in a similar format.</p> <pre><code>log4j.appender.Console.layout.ConversionPattern=%d{ABSOLUTE} (%F:%L) - %m%n </code></pre> <p>In eclipse, the console automatically turned text like this into links. In IntelliJ, the stack traces are links but my own output in the same form remains un-linked. Is there any way to get IntelliJ to do the same?</p>
<p>Yes you can, try this pattern:</p> <pre> <code>&lt;param name="ConversionPattern" value="%-5p - [%-80m] - at %c.%M(%F:%L)%n"/></code> </pre>
Free software for Windows installers: NSIS vs. WiX? <p>I'm need to choose a software package for installing software. NSIS and WiX seem promising. Which one would you recommend over the other and why?</p> <p>Feel free to offer something else if you think it's better than these two.</p>
<p>If you want to get an installer done <strong>today</strong>, with the minimum amount of overhead, use NSIS. Simple scripting language, good documentation, fast.</p> <p>If you want to build MSI files, integrate with the Windows Installer transactional system, and have plenty of time to devote to learning the declarative model used by Windows Installer, then check out WiX.</p>
Can I assign keyboard shortcut to the Microsoft Intellitype keyboard? <p>Anyone know if I can assign a keyboard shortcut such as <kbd>Ctrl</kbd> + <kbd>F4</kbd> (for closing the current tab in IE/Firefix etc) to the Microsoft Keyboard favourite keys 1-5.</p> <p>I have Microsoft Keyboard software installed and I can only browse to applications I want to run and cant seem to see anywhere else where I can assign shortcuts.</p>
<p>Unlock the Function button on top of the Numkey pad, then use the F6/Close key ;)</p>
Visual Studio 2005 stopped adding code-behind files <p>This morning, when I tried to add a new ASPX page to my project, Visual Studio decided that I no longer needed any .CS files associated with it. Trying to add a web control produced same results: .ascx file with no .cs. I've got two questions so far:</p> <ol> <li>Considering that no changes have been made to the system over the weekend, what could be the cause of this?</li> <li>Is re-installing VS the only option right now?</li> </ol> <p>I'm running Visual Studio 2005 SP1 on Windows XP SP3.</p> <p>Thanks!</p> <p>EDIT: Thank you all. The checkbox DID get unchecked at some point and I simply did not see it. I will blame this one on Monday...</p>
<p>there is a check box you may have accidentaly un-checked: Place code in separate file<br /> <img src="http://blogs.msdn.com/blogfiles/mikeormond/WindowsLiveWriter/NewWebItemTemplatesinVisualStudioOrcasBe_CC5B/image%5B9%5D.png" alt="dialog" /></p>
Managing Wireless Network Connections with C# and the Compact Framework <p>The title kinda sums it up--I need to be able to pro grammatically connect to a known access point (the SSID and credentials will be loaded during device provisioning). I understand that both the Compact Framework SDK and the OpenNETCF SDK offer some helper methods, but I can't seem to find a good tutorial on how to use them.</p>
<p>OpenNETCF's <a href="http://www.smartdeviceframework.com" rel="nofollow">Smart Device Framework</a> is probably the simplest mechanism to do this. The chanllenge with wireless is that the radio OEM (whether is was the device oem or not) can choose any number of ways to advertise the interface. Maybe as a plain NDIS device with proprietary controls (a real pain to interface with) or at the other end using <a href="http://msdn.microsoft.com/en-us/library/aa448301.aspx" rel="nofollow">Wireless Zero Config (WZC)</a>. The SDF tries to handle any scenario, providing more and more capability depending on what the hardware interface advertises.</p> <p>So, if you want to add a preferred network using a WZC-enabled interface (really the only way to connect is for the network to be in the preferred list) and that netowork is open (not WEP, WPA, etc), it's a pretty simple task. In fact WPA and even TKIP are pretty straightforward. You simply call <a href="http://www.opennetcf.com/library/sdf/html/616b978f-5bd6-51bb-62f8-3d2fa9dd681f.htm" rel="nofollow">AddPreferredNetwork</a>. So you'd call <a href="http://www.opennetcf.com/library/sdf/html/2dc21eda-47c6-fde5-e569-1781b1b44feb.htm" rel="nofollow">NetworkInterface.GetAllNetworkInterfaces</a>, then iterate the result (or filter with LINQ) to get an adapter that is of the WirelessZeroConfigNetworkInterface type (yes, long name) and then call AddPreferredNetwork on that with your SSID and any added info like the key material.</p> <p>Of course you can do all of this without the SDF as well - the amount of work required through P/Invoke is just a lot higher. But it's still all "documented" in some form. Most of what we did was a "translation" of the network dialog in Windows CE, which the full source for ships in Platform Builder.</p>
Rotating flash movie clip <p>I would like to do a flash menu similar to <a href="http://accuval.net" rel="nofollow">this company's</a>, I have the rotation down, I just cannot figure out how to make it rotate to the top. For example, if you click "Financing" on their menu, the word financing rotates to the top. If someone could just give me the theory behind how to do that, that would be awesome.</p> <p><strong>EDIT:</strong></p> <p>I guess the problem I have is that I don't have any x and y position to get the difference from in order to rotate it. If that makes sense?</p>
<p>The simplest way to do that, is figure out the angles at which each button would be straight (i mean, by hand or on paper). There's 360degrees in a circle, however be careful as flash angle ranges from -180 to +180 degrees (not from 0 to 360 like you would expect).</p> <p>For the rotation, you need to group all the buttons within one circular wheel movieclip, and rotate that wheel to the angles you've discovered on paper. </p> <p>I made a quick flash example for you, <strong><a href="http://haroldg.com/tutes/rotation_wheel/" rel="nofollow">you can see here</a></strong>. It includes a tweened version, that moves in a very similar way as the link you provided. Good luck !</p>
Can .Net custom controls be used in VB6 form? <p>I am doing some maintenance on a VB6 Windows application. I have a .Net custom control component that I would like to use on a VB6 form. Is this possible? I know how to access non-visual .Net components from VB6 by generating a COM type library for the .Net DLL, but can a .Net custom control be used like a .OCX from VB6? If so, how is the control instantiated in VB6, added to the form, etc.</p> <p>Thanks in advance for any replies.</p>
<p>The Interop Forms toolkit will give you what you need:</p> <p><a href="http://msdn.microsoft.com/en-us/vbasic/bb419144.aspx">http://msdn.microsoft.com/en-us/vbasic/bb419144.aspx</a></p> <p>It lets you create UserControls in VB.net which you can then add to VB6. It also lets you display .net forms from your VB6 code.</p> <p>I've used it successfully to give my old VB6 code the .net toolbars - much nicer!</p>
Equations for 2 variable Linear Regression <p>We are using a programming language that does not have a linear regression function in it. We have already implemented a single variable linear equation:</p> <blockquote> <p>y = Ax + B</p> </blockquote> <p>and have simply calculated the A and B coefficents from the data using a solution similar to <a href="http://stackoverflow.com/questions/364558/find-a-best-fit-equation#364585">this Stack Overflow answer</a>.</p> <p>I know this problem gets geometrically harder as variables are added, but for our purposes, we only need to add one more:</p> <blockquote> <p>z = Ax + By + C</p> </blockquote> <p>Does anyone have the closed form equations, or code in any language that can solve for A, B and C given an array of x, y, and z's?</p>
<p>so you have three linear equations</p> <pre><code>k = aX1 + bY1 + cZ1 k = aX2 + bY2 + cZ2 k = aX3 + bY3 + cZ3 </code></pre> <p>What you can do is rewrite it as matriz</p> <pre><code>| x1 y1 z1 | | a | | k | | x2 y2 z2 | | b | = | k | | x3 y3 y3 | | c | | k | </code></pre> <p>to work out <code>[a b c ]</code> do the following matrix operation</p> <pre><code>| a | | x1 y1 z1 | | k | | b | = inverse( | x2 y2 z2 | ) | k | | c | | x3 y3 y3 | | k | </code></pre> <p>The formula for a 3x3 matrix inverse can be found <a href="http://www.dr-lex.be/random/matrix_inv.html" rel="nofollow">here</a> </p>
Objective-C error: initializer element is not constant <p>Why does the compiler give me the following error message on the provided code: "initializer element is not constant". The corresponding C/C++ code compiles perfectly under gcc.</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; const float a = 1; const float b = a + a; // &lt;- error here int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // insert code here... NSLog(@"Hello, World!"); [pool drain]; return 0; } </code></pre>
<p>That code will only compile correctly if the <code>const float</code> statements appear somewhere other than the file scope.</p> <p>It is part of the standard, apparently. It is important that all file-scope declared variables are initialised with constant expressions, not expressions involving constant variables.</p> <p>You are initialising the float 'b' with the value of another object. The value of any object, even if it is a const qualified, is not a constant expression in C.</p>
Initialize library on Assembly load <p>I have a .net library dll that acts like a functional library. There are a bunch of static types along with static methods.</p> <p>There is some initialization code that I need to run to set up the library ready for use.</p> <p>When the assembly gets loaded is there a way to ensure that a particular method is run? Something like AppDomain.AssemblyLoad but called automatically from the assembly itself. I was thinking that maybe there is something like an AssemblyAttribute that could be used?</p> <p>At the moment I have this initialization code in a static constructor but as this is a library with many entry points there is no guarantee that this particular type will be used.</p> <p>Thanks!</p>
<p>Yes there is - sort of.</p> <p>Use the excellent little utility by by Einar Egilsson, <a href="https://github.com/einaregilsson/InjectModuleInitializer">InjectModuleInitializer</a>.</p> <p>Run this executable as a post build step to create a small .cctor function (the module initializer function) that calls a static void function of yours that takes no parameters. It would be nice if compiler gave us the ability to create .cctor(), luckily we rarely need this capability.</p> <p>This is not a complete DllMain replacement, however. The CLR only calls this .cctor function prior to any methods called in your assembly, not upon assembly load. So, if you need something to happen upon assembly load, you need to have the loading code call a method directly or use the hack I detailed <a href="http://stackoverflow.com/a/9745422/240845">http://stackoverflow.com/a/9745422/240845</a></p>
Call C# Web Service with using PHP <p>I would like to call C# service with using PHP, anyone know how to do it? Thanks</p>
<p>Create an SOAP XML document that matches up with the WSDL and send it via HTTP POST. See <a href="http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit" rel="nofollow">here for an example</a>.</p> <p>You send this:</p> <pre><code>POST /webservices/tempconvert.asmx HTTP/1.1 Host: www.w3schools.com Content-Type: application/soap+xml; charset=utf-8 Content-Length: length &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"&gt; &lt;soap12:Body&gt; &lt;CelsiusToFahrenheit xmlns="http://tempuri.org/"&gt; &lt;Celsius&gt;string&lt;/Celsius&gt; &lt;/CelsiusToFahrenheit&gt; &lt;/soap12:Body&gt; &lt;/soap12:Envelope&gt; </code></pre> <p>And get this back:</p> <pre><code>HTTP/1.1 200 OK Content-Type: application/soap+xml; charset=utf-8 Content-Length: length &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"&gt; &lt;soap12:Body&gt; &lt;CelsiusToFahrenheitResponse xmlns="http://tempuri.org/"&gt; &lt;CelsiusToFahrenheitResult&gt;string&lt;/CelsiusToFahrenheitResult&gt; &lt;/CelsiusToFahrenheitResponse&gt; &lt;/soap12:Body&gt; &lt;/soap12:Envelope&gt; </code></pre>
What is the difference betwen including modules and embedding modules? <pre><code>module Superpower # instance method def turn_invisible ... end # module method def Superpower.turn_into_toad ... end module Fly def flap_wings ... end end end Class Superman include Superpower ... def run_away # how to call flap_wings? # how to call turn_invisible? end def see_bad_guys(bad_guy = lex_luthor) #is this correct? Superpower.turn_into_toad(bad_guy) end end </code></pre> <p>Hi I saw some ruby code which I couldn't understand. How do you call flap_wings from within the Superman class? Is it possible to call an instance method from within the class? What is the difference between including modules and embedding modules? Why and when should you do that?</p>
<p>I'm assuming that when you say embedding a module you mean the "Fly" module from your example is embedded in "Superpower".</p> <p>If that is the case, I would call it a nested module. The only time I would use a Nested Module is when the nested module deals specifically with the main module, such that the code in Fly is directly correlated to Superpower, but are separated for convenience and readability.</p> <p>You can use the nested module's methods simply by including superpower first, then fly second, like so:</p> <pre><code>Class Superman include Superpower include Fly # ... end </code></pre> <p>The details are described further on <a href="http://rubyonrailswin.wordpress.com/2007/03/08/nested-modules/" rel="nofollow">this blog</a>.</p>
How do I provide two default templates for a Custom Control in WPF? <p>In Charles Petzold's "Using Templates to Customize WPF Controls" article in the Jan 2007 edition of MSDN Magazine (<a href="http://msdn.microsoft.com/en-us/magazine/cc163497.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/magazine/cc163497.aspx</a>), he says,</p> <blockquote> <p>The ProgressBar control actually has two default templates for the two orientations. (This is true of ScrollBar and Slider, as well.) If you want your new ProgressBar to support both orientations, you should write two separate templates and select them in the Triggers section of a Style element that you also define for the ProgressBar.</p> </blockquote> <p>I am currently writing a custom control that requires this functionality, but can't work out how to do as he says - not in any way that works, anyhow. Does anybody have a sample of this?</p> <p>Thanks in advance.</p>
<p>You can see how its done in the scrollbar sample control template <a href="http://msdn.microsoft.com/en-us/library/ms742173.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms742173.aspx</a></p> <p>I copied only the relevant parts of the sample here.</p> <p>In short there are two templates in the resource dictionary:</p> <pre><code>&lt;ControlTemplate x:Key="VerticalScrollBar" TargetType="{x:Type ScrollBar}"&gt; ... &lt;ControlTemplate x:Key="HorizontalScrollBar" TargetType="{x:Type ScrollBar}"&gt; ... </code></pre> <p>And a trigger in the style to switch between them :</p> <pre><code>&lt;Style x:Key="{x:Type ScrollBar}" TargetType="{x:Type ScrollBar}"&gt; &lt;Style.Triggers&gt; &lt;Trigger Property="Orientation" Value="Horizontal"&gt; &lt;Setter Property="Template" Value="{StaticResource HorizontalScrollBar}" /&gt; &lt;/Trigger&gt; &lt;Trigger Property="Orientation" Value="Vertical"&gt; &lt;Setter Property="Template" Value="{StaticResource VerticalScrollBar}" /&gt; &lt;/Trigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; </code></pre>
Should I explicitly release? <p>I currently have an array of strings, I'm getting a NSString object from this array by calling the <code>-componentsJoinedByString:</code> method. Example:</p> <pre><code>NSString *someString = [[NSString alloc] initWithString: [myStrings componentsJoinedByString:@","]; </code></pre> <p>Since <code>-componentsJoinedByString:</code> returns me an NSString, I'm assuming that it is not "owned" by me, therefore what I just did should be ok? or do I have to do this:</p> <pre><code>NSString *toDelete = [myStrings componentsJoinedByString:@","]; NSString *someString = [[NSString alloc] initWithString:toDelete]; [toDelete release]; </code></pre> <p>Help with clarifying this is much appreciated!</p>
<p>The first example you wrote is correct, although in practice it would be clearer just to write <code>NSString *someString = [[myStrings componentsJoinedByString:@","] copy];</code> (note that this will be retained, so you will have to release it at some point in the future.</p> <p>If you're having trouble with memory management, <a href="http://www.cocoadev.com/index.pl?MemoryManagement" rel="nofollow">this page</a> might help. It's not too hard to learn the rules, but you're going to run into a lot of problems until you do.</p>
ASP.NET Membership provider with SQL schema's <p>I would like to use the ASP.NET Membership Provider security framework but would like it to use SQL Server schema's. So instead of having tables such as aspnet_Membership I would prefer it to be something like sec.Membership. Has anyone tried this and got it to work?</p>
<p>I believe the table names are hard-coded into the default SQL providers for ASP.NET. You'll have to implement custom providers to do the same things as the default providers, but using an alternate table name instead. <a href="http://www.devx.com/asp/Article/29256" rel="nofollow">This article</a> can help you figure out how to write custom providers.</p>
Work-around for PHP5's PDO rowCount MySQL issue <p>I've recently started work on a new project using PHP5 and want to use their PDO classes for it. The problem is that the MySQL PDO Driver doesn't support rowCount() so there's no way to run a query and then get the number of affected rows, or rows returned, which is a pretty big issue as far as I'm concerned. I was wondering if anyone else has dealt with this before and what you've done to work around it. Having to do a fetch() or fetchAll() to check if any rows were affected or returned seems like a hack to me, I'd rather just do $stmt->numRows() or something similar.</p>
<p>You can issue a <code>SELECT FOUND_ROWS()</code> query right after the original <code>SELECT</code> query to get row count.</p> <pre><code>$pdo-&gt;query("SELECT * FROM users"); $foundRows = $pdo-&gt;query("SELECT FOUND_ROWS()")-&gt;fetchColumn(); </code></pre> <p>See also: <a href="http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function%5Ffound-rows">MySQL Docs on FOUND_ROWS()</a></p>
ASP execute stored procedure with Null <p>In asp.net can use dbnull.value to send Null value to db. How to use in ASP?</p> <p>Thanks a lot!!</p>
<p>In ASP, you need to use the keyword <strong>NULL</strong> as the null value for the stored procedure.</p> <p>Note: don't use vbNull as this evaluates to 1 rather than null.</p>
detecting mistyped email addresses in javascript <p>I notice sometimes users mistype their email address (in a contact-us form), for example, typing @yahho.com, @yhoo.com, or @yahoo.co instead of @yahoo.com</p> <p>I feel that this can be corrected on-the-spot with some javascript. Simply check the email address for possible mistakes, such as the ones listed above, so that if the user types his_email@yhoo.com, a non-obtrusive message can be displayed, or something like that, suggesting that he probably means @yahoo.com, and asking to double check he typed his email correctly.</p> <p><strong>The Question is:</strong><br /> How can I detect -in java script- that a string is very similar to "yahoo" or "yahoo.com"? or in general, how can I detect the level of similarity between two strings?</p> <p>P.S. (this is a side note) In my specific case, the users are not native English speakers, and most of them are no where near fluent, the site itself is not in English.</p>
<p>Here's a dirty implementation that could kind of get you some simple checks using the <a href="http://en.wikipedia.org/wiki/Levenshtein_distance"><code>Levenshtein distance</code></a>. Credit for the "levenshteinenator" goes to <a href="http://andrew.hedges.name/experiments/levenshtein/"><code>this link</code></a>. You would add whatever popular domains you want to the domains array and it would check to see if the distance of the host part of the email entered is 1 or 2 which would be reasonably close to assume there's a typo somewhere.</p> <pre><code>levenshteinenator = function(a, b) { var cost; // get values var m = a.length; var n = b.length; // make sure a.length &gt;= b.length to use O(min(n,m)) space, whatever that is if (m &lt; n) { var c=a;a=b;b=c; var o=m;m=n;n=o; } var r = new Array(); r[0] = new Array(); for (var c = 0; c &lt; n+1; c++) { r[0][c] = c; } for (var i = 1; i &lt; m+1; i++) { r[i] = new Array(); r[i][0] = i; for (var j = 1; j &lt; n+1; j++) { cost = (a.charAt(i-1) == b.charAt(j-1))? 0: 1; r[i][j] = minimator(r[i-1][j]+1,r[i][j-1]+1,r[i-1][j-1]+cost); } } return r[m][n]; } // return the smallest of the three values passed in minimator = function(x,y,z) { if (x &lt; y &amp;&amp; x &lt; z) return x; if (y &lt; x &amp;&amp; y &lt; z) return y; return z; } var domains = new Array('yahoo.com','google.com','hotmail.com'); var email = 'whatever@yahoo.om'; var parts = email.split('@'); var dist; for(var x=0; x &lt; domains.length; x++) { dist = levenshteinenator(domains[x], parts[1]); if(dist == 1 || dist == 2) { alert('did you mean ' + domains[x] + '?'); } } </code></pre>
Access 2007 integration with Sharepoint 2007 Tasks list <p>A customer of ours has an Access 2007 application with a form for creating tasks for upload to a Sharepoint Task List. The user fills in the form (title, status, priority, start date, due date). The user then places check marks next to the sharepoint user names that this task must be assigned to (one task per sp user selected). This data is aggregeated into a TaskQueue table and the tasks are added to the Sharepoint list successfully (through a linked list - i think). The problem is that we need to include zero or more attachments for each task item. Is there a way to do this through a macro, VBA, or some other built in functionality that I haven't learned about yet?</p> <p>My initial idea was to use a C# windows service that monitors this taskqueue table then uses the Lists.asmx Shareopint web service and the AddAttachment method when given the List item ID and NTFS path to the attached file to add the attachments to the task list item in Sharepoint. </p> <p>After playing around with Access and setting up a linked table to a Task List in Sharepoint, I found that you can add attachments through the Access 2007 datasheet view. The problem is that you can only select one user or SP group in the Assigned TO field. They have a lot of repetitive tasks to assign to a bunch of separate people.. That's why they developed this form. If anyone has an idea on how to solve this issue please let me know. Also does anyone know of any good Access 2007/Sharepoint integration resources?</p> <p>Thanks in advance!</p>
<ol> <li>have the attachments upload as part of the Access form. </li> <li>load attachments into a Document Library</li> <li>Check off users like they are currently being done</li> <li>Add hyperlinks to the attachments uploaded in step 2 to the Description (rich text) field. (maybe done automatically in steps 1-2)</li> <li>Leave TaskQueue table alone.</li> </ol> <p>This way, 0..n documents can be included. The task list just stores structured data, and the documents are stored in a document library once, and you don't have runaway growth when attaching 1 document to 5 different tasks (resulting in 5 copies of the document).</p>
Is there a decent way to inhibit screensavers in linux? <p>I'm looking for a decent, non-lame way to inhibit xscreensaver, kscreensaver, or gnome-screensaver, whichver might be running, preferably in a screensaver-agnostic manner, and it absolutely positively must execute <em>fast</em>.</p> <p>I've read the xscreensaver FAQ ( <a href="http://www.jwz.org/xscreensaver/faq.html">http://www.jwz.org/xscreensaver/faq.html</a> ).</p> <p>I have a gtk based game program that's cranking out 30 frames/second while mixing several channels of audio, and since it's controlled by a joystick, sometimes "the" screensaver will kick in. I put "the" in quotes, because there are at least three different popular screensavers, xscreensaver, gnome-screensaver, and kscreensaver, each with their own unique and klunky methods by which an application might inhibit them.</p> <p>Has anybody encapsulated the code to inhibit all of these into a <em>fast</em> chunk of code? Oh, and it has to be GPL compatible.</p> <p>Currently my code simply whines piteously about the uncooperating screensaver developers if any screensaver is detected and the joystick is in use, and doesn't actually try to do anything other than advise the user to manually disable the screensaver, as the only other thing I can think to do is so incredibly ugly that I simply refuse to do it.</p> <p>Just wondering if anybody else has run into this, and what they've done, and if they did anything, if it was as ugly as it seems to me it would have to be, or if there's some elegant solution out there... Seems like maybe synthesizing X events somehow to fool the screensaver into thinking there's some activity might do the trick in a universal way, but I'm really not sure how to do that (and hoping you wouldn't need to be root to do it.)</p> <p>Any ideas?</p> <p>Thanks,</p> <p>-- steve</p> <hr> <p>Hmm, unfortuanately, at least on Fedora core 8, this does not appear to work.</p> <p>The xdg-screensaver script is there, and seems to be intended to work, it just doesn't actually work.</p> <p>Once you do "xdg-screensaver suspend window-id", where window id is gotten from within the program via </p> <pre> xwindow_id = GDK_WINDOW_XWINDOW (GTK_WIDGET (widget)-&gt;window); </pre> <p>Or whether the window id is gotten via xprop, and xdg-screensaver run manually, two processes are created:</p> <pre> [scameron@zuul wordwarvi]$ ps -efa | grep xdg scameron 4218 1 0 20:12 pts/2 00:00:00 /bin/sh /usr/bin/xdg-screensaver suspend 0x3a00004 scameron 4223 1 0 20:12 pts/2 00:00:00 /bin/sh /usr/bin/xdg-screensaver suspend 0x3a00004 scameron 4313 3151 0 20:15 pts/1 00:00:00 grep xdg [scameron@zuul wordwarvi]$ </pre> <p>And they never die, even after the program they are supposedly waiting for dies, and the screensaver is never re-enabled.</p> <pre> [scameron@zuul wordwarvi]$ xdg-screensaver status disabled [scameron@zuul wordwarvi]$ ls -ltr /tmp | grep xdg -rw------- 1 scameron scameron 15 2009-01-20 20:12 xdg-screensaver-scameron--0.0 [scameron@zuul wordwarvi]$ </pre> <p>Running xdg-screensaver resume window-id does not resume the screensaver.</p> <p>To re-enable the screensaver, I have to manually kill them, and manually remove the files it leaves around in /tmp:</p> <pre> [scameron@zuul wordwarvi]$ kill 4218 4223 [scameron@zuul wordwarvi]$ rm /tmp/xdg-screensaver-scameron--0.0 [scameron@zuul wordwarvi]$ xdg-screensaver status enabled [scameron@zuul wordwarvi]$ </pre> <p>So, good intentions, but doesn't seem to actually work.</p> <hr> <p>No, of course not expecting to run it every frame, but don't want it causing hiccups when it does run, is all. With my thought of synthesizing X events, I was imagining it would be just often enough to make the screen saver think there was activity.</p> <p>Looking at xdg-screensaver (which seems to be a shell script that ultimately just does a "wait" for my process -- cool) it seems to be made to do just what I want. I knew I couldn't be the only or first one to face this problem. </p> <p>Thanks!</p> <p>-- steve</p>
<p>No, but yes...</p> <p>There's no nice clean way to do this. In my opinion there should be a mechanism administrated by the X server, which both screensavers and interested applications can voluntarily use to negotiate suppression of any screensaver during the runtime of one or more programs. But no such mechanism yet exists to my knowledge. GNOME and KDE look to be implementing a DBUS approach to this problem, but in my opinion even if it becomes widespread (it isn't yet widespread enough to rely on it in 3rd party code) it's not the right approach.</p> <p>However, xdg-screensaver is a FreeDesktop standardised shell script which you can run as a sub-process to control the screensaver. It controls most popular screensavers, and the OS vendor would be responsible for updating it/ maintaining it to work with newer screensavers or better ways of doing this in the future. Unlike many other kludges it will automatically re-enable the screensaver if your application crashes or exits via some route that forgets to call the re-enable code. See the manual page for details in how to use it.</p> <p>As a GTK+ user probably the trickiest aspects of this for you would be creating the sub-process to run the shell script (if you haven't done this before you will want to find a tutorial about using fork + exec) and getting the XWindow ID of your application's main window to give to xdg-screensaver.</p> <p>You ask that the code should be "fast". This makes me wonder if you're expecting to run it every frame - don't. The xdg-screensaver solution allows you to disable or renable the screensaver explicitly, rather than trying to suppress it once per frame or anything like that.</p>
Custom C# data transfer objects from javascript PageMethods <p>I've created a custom object that I'd like to return in JSON to a javascript method. This object was created as a class in C#. </p> <p>What's the best way to return this object from a PageMethod ([WebMethod] if you like) to a javascript onPageMethodCallback() function? I need to be able to access the properties of this object via javascript and update the DOM according (possibly using jQuery).</p> <p>Thank you StackOverflow! :)</p>
<p>ASP.NET AJAX on the server side will handle serializing the object for you. For example:</p> <pre><code>public class Name { public string FirstName; public string LastName; } [WebMethod] public Name GetName() { Name name = new Name(); name.FirstName = "Dave"; name.LastName = "Ward"; return name; } </code></pre> <p>You can then call the PageMethod directly from jQuery using basically the same method that JD linked to. More specifically, here's <a href="http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/">a post about calling PageMethods with jQuery</a>. </p> <p>The server will serialize your return type as JSON and you'll be able to access the properties of the Name class as expected. In this example, <strong>msg.d.FirstName</strong> and <strong>msg.d.LastName</strong>.</p> <p>Just watch out for the .d. <a href="http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/">It's a security feature added in 3.5</a>, and isn't present in 2.0.</p>
Storing Queries in C# or use Stored Functions in Postgres? <p>Should I be storing the raw SQL queries in my c# code, or should I be delegating them to stored functions in the Postgres Backend?</p> <p>If I should be storing them in code, since they can get quite long, what is the optimal way to store them (ie. as constants in a separate static class)?</p> <p>Does using stored functions have any impact on deployability/updatability of an application?</p> <p>Thanks</p>
<p>As a rule we do all of our database interactions via stored procedures instead of direct SQL statements; this allows a lot of flexibility for adjusting to schema changes and performance issues without having to rebuild or redeploy binary images or configuration files to all targets.</p>
PHP sessions for storing lots of data? <p>I'm developing a media bookmarking site and am looking for a way to remember whether a user has bookmarked an item (without having to go to the DB every page load to check).</p> <p>I haven't used PHP sessions before, but I'm thinking they would do the trick.</p> <p>Would it make sense to do an initial DB call when the user logs in, grab all the items that a user has bookmarked and save an array of all the item ids to the user session?</p> <p>Then when a page is loaded, for each of the 100 items on the page it would check whether that item's ID is in the session array (so we know whether to display the "bookmark" button or an indicator that they've already bookmarked it).</p> <p>Just want to make sure this is a right strategy, or if there is a better way. Would this work fine even if there are 10,000 ids in the array?</p>
<p>As well you can take a look at Memcached extension - it uses server's memory as data storage.</p>
serve postscript file with php script <p>I want to give a link to a postscript file, but first I want to make a script that will monitor the downloads of this file. The link has to be 'direct' so I added <code>.ps</code> extension to be interpreted by PHP. In the begining the script opens the text file, writes some information and then I don't know what to do.<br /> Basically I have something like this (file <code>apendix.ps</code>):</p> <pre><code>header('Content-type: application/postscript'); header('Location: appendix.ps'); </code></pre> <p>but then, the link to this file has to have different name, so eventually I'm serving different file than in 'direct' link.<br /> Is it possible to write a script <code>appendix.ps</code> which does something in the begining and then serves real <code>appendix.ps</code> file?<br /><br /> regards<br /> chriss</p>
<p>You can use <a href="http://nz2.php.net/readfile" rel="nofollow">readfile</a>:</p> <pre><code>header('Content-type: application/postscript'); readfile('appendix.ps'); </code></pre> <p>You also may want to send a "<a href="http://www.ietf.org/rfc/rfc2183.txt" rel="nofollow">Content-Disposition</a>" header to hint to the user agent how its intended to be displayed. </p> <p>If you want to suggest to open it in a new window, Ie: trigger a download action: </p> <pre><code>header('Content-Disposition: attachment'); </code></pre> <p>If you want to suggest to display it in the browser if it can: </p> <pre><code>header('Content-Disposition: inline'); </code></pre> <p>Noting of course these are just <em>suggestions</em> and the browser may not play ball or even be able to, but they're handy to have.</p>
How can I find out how many connections to my slapd LDAP server? <p>I have a slapd LDAP server which is critical to my application. I want to monitor it in order to detect when it has become over-loaded or if it fails.</p> <p>Unfortunately we are stuck with a very old edition of slapd which has a known bug: It cannot cope with more than 64 concurrent connections. If a client attempts to open any more connections slapd blocks, causing all kinds of problems.</p> <p>I have been asked to make a tool which will find the number of connections open at any given moment - this might be used in an automatic monitoring tool, but how can I find out the state of slapd? Is there a way to do it?</p>
<p>The best tool for that is <a href="http://people.freebsd.org/~abe/">lsof</a>.</p> <pre><code>lsof -i tcp:389 </code></pre> <p>will show you all TCP connections to your LDAP server.</p>
Delphi Personal Edition or Turbo Delphi- saving and searching for data <p>i'm interested if it is possible to make an application like an Address Book (Windows: Start->All Programs->Accessories->Address Book) in Delphi Personal Edition or in Turbo Delphi.</p> <p>If yes, how to make it? Which components to use?</p> <p>How to make an application to be used on some other computer, and that no files would be needed to install in that computer for the application to work? (saving data through some form and an option to search for particular entry (like Find People in Address Book))</p> <p>Regards</p> <hr> <p>I was away for some time, hope we can continue, i'll give some more information.</p> <p>What i'm doing is for school project, i'm trying to make an application which would actually be used by some electro-engineer. The purpose of an application is- to easily find a map in hard-disk, in which a certain project is saved (for example, in OS Windows, C:\Projects\2009\Project1), using some query.</p>
<p>To start with the first question, you can write (almost) any application in Delphi. Other version often implies a smaller library and possible limited use (as far as I know you can't sell comercial applications build with the free version, but maybe codegear changed this)</p> <p>An addressbook is a nice and simple (database) application. And with database applications you have basically two choices:</p> <ul> <li>use the data aware controls</li> <li>do it yourself</li> </ul> <p>Data aware controls are great if you want to build an application fast. If you have a life connection, you can show it (even at designtime). But In my opionion they are a bit limited.</p> <p>The do it yourself option is harder. You should write an infrastructure yourself.</p> <p><strong>Some remarks on general application development</strong></p> <p>First you need to decide what you want to build. Take some paper and draw some screens. For example:</p> <pre><code>+-------------------------------------------------+ | menu | +-------------------------------------------------+ | Toolbar | +------------+------------------------------------+ | -Friends |Name Mail | | &gt;Hers |Alice Alice1957@hotmail.com | | His |Bob Bob123@hotmail.com | | +Coworkers | | | + Us | | | +Them | | +------------+------------------------------------+ | statusbar | +-------------------------------------------------+ </code></pre> <p>We have the following controls:</p> <ul> <li>An action list (not visible) which contains the actions independent of the menu/toolbars.</li> <li>A main menu, linked to the action list. </li> <li>A toolbar, linked to the action list.</li> <li>A treeview to organize the groups.</li> <li>A listview to show the contacts.</li> <li>A statusbar to show the application status.</li> </ul> <p>With the action list, it is easy to use both a main menu, context menu's and toolbars.</p> <p>The listview has several view styles. You need to set the ViewStyle property to vsReport to get the expected behaviour. Within the listview, each item has a caption, which is shown on the first column. The other columns are filled with information in a stringlist (subitems).</p> <p>Then you need to decide on the actions:</p> <ul> <li>Add address</li> <li>Remove address</li> <li>Copy/Paste</li> <li>Move (drag &amp; drop is nice but can be hard to program)</li> <li>Print</li> </ul> <p>And there are lots of other questions (possibly for later) like:</p> <ul> <li>Do you want a single addressbook, or do you want multiple? In the later case you need a mechanism to connect to another database.</li> <li>Do you want to show one or multiple addresscards at once?</li> </ul> <p>If this is too much, I advice to start small (single database, single card, no printing). You can expand later.</p>
Skinning Google Maps To Look Like The Native Google Maps iPhone App <p>I could use a goog set of eyes on my project. I am designing a skin for the google maps API that resembles the native Google Maps App on the iPhone. Ive already got it:</p> <p>1) Displaying a custom info window</p> <p>2) Custom pins/markers</p> <p>3) Pins falling from the sky on load</p> <p>4) Pulling data from an XML file</p> <p>Unfortunately I can not get it working correctly on the iPhone and I think it is because my code is improperly formatted.</p> <p>The map and link to the source code is available here:</p> <p><a href="http://www.brainbackup.net/post/replicating-the-google-maps-iphone-app.html" rel="nofollow">http://www.brainbackup.net/post/replicating-the-google-maps-iphone-app.html</a></p> <p>Thanks for your help!</p>
<p>turns out this had to do with the version of google maps I was using. 2.0 allows for the custom infowindow, but does not allow the pins to fall from the sky. the opposite was true for v 2.123. go figure.</p>
How do I separate markup from application code when building a Java website? <p>I'm a .NET web developer who has just been asked to produce a small demo website using NetBeans IDE 5.5. I have no experience with Java up to this point.</p> <p>I've followed a couple of quick tutorials, one which just uses a JSP file and another which uses a servlet. My concern at this early stage is that it looks difficult to keep my application code away from my markup.</p> <p>Using JSP files looks quite similar to the old days of classic ASP. On the other hand, servlets look useful but seem to involve a lot of writing out markup to the output stream, which I'm not happy with either.</p> <p>Is there an equivalent to the ASP .NET code-behind model, or any other strategies for separating out markup and code? Is it possible to keep markup in the JSP and then use the servlet from the JSP?</p>
<p>You can't do something similar with ASP.NET code behind using pure Java EE technologies. You need to use an MVC framework like Spring MVC or Struts. The idea is that you create your controller (Java Class) and a JSP page and configure an action to tie the JSP page with the controller.</p> <p>It isn't a simple as the ASP.NET as it requires configuration and an external framework.</p> <p>Netbeans has JSF framework embedded. Have a look at this <a href="http://www.netbeans.org/kb/articles/jAstrologer-intro.html" rel="nofollow">tutorial</a>.</p>
SQL exception when trying make an prepared statement <p>I'm trying to pass the following <code>String</code> to a <code>PreparedStatement</code>:</p> <pre><code>private static final String QUICK_SEARCH = "select * from c where NAME like '% ? %'"; </code></pre> <p>However, I get an SQL exception that the bind variable is missing.</p> <p>Any suggestions?</p>
<p>You can't put binding variables inside a string like that.</p> <p>You need to use:</p> <pre><code>SELECT * FROM c WHERE name LIKE CONCAT('%', ?, '%') </code></pre> <p>or similar, depending on what functions are supported by your version of SQL.</p>
Where can I find the default icons used for folders and applications? <p>I'm trying to load the default HICON that explorer displays for: </p> <ul> <li>An open folder</li> <li>An exe that has no embedded default icon of its own. This can also be seen in 'Add/Remove Programs' or 'Programs and Features' as it's called on Vista.</li> </ul> <p>Do you know where these can be found? I think the folder icon might be in the resources of explorer.exe. But have no idea where the default application icon can be retrieved from.</p> <p>And additionally, do you have any sample code that could load them into HICONs.</p> <p>I really need this to work on multiple Windows OSs: 2000, XP, Vista, 2008</p> <p><hr /></p> <p>Thanks for the help so far. I'm on Vista and have looked through Shell32.dll. I don't see an icon in there that looks the same as the default one displayed by an application in explorer. I could be missing it - there are 278 icons to look through - is it definitely in there, or is there some other location I should look?</p>
<p>Use the <a href="http://msdn.microsoft.com/en-us/library/bb762179(VS.85).aspx">SHGetFileInfo</a> API.</p> <pre><code>SHFILEINFO sfi; SecureZeroMemory(&amp;sfi, sizeof sfi); SHGetFileInfo( _T("Doesn't matter"), FILE_ATTRIBUTE_DIRECTORY, &amp;sfi, sizeof sfi, SHGFI_ICON | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES); </code></pre> <p>will get you the icon handle to the folder icon.</p> <p>To get the 'open' icon (i.e., the icon where the folder is shown as open), also pass SHGFI_OPENICON in the last parameter to SHGetFileInfo().</p> <p>[edit]</p> <p>ignore all answers which tell you to poke around in the registry! Because that won't work reliably, will show the wrong icons if they're customized/skinned and might not work in future windows versions. Also, if you extract the icons from system dlls/exes you could get into legal troubles because they're copyrighted.</p>
Uploading data into remote database <p>What is the most secure and easier way to send approx. 1000 different records into database that is not directly accessible - MySQL database on Web provider's server - using Windows application . Data will be stored into different tables.</p> <p>Edited: The application will be distributed to users who have no idea what is database or putty or... They just install my application, open it, enter some data and press Submit.</p> <p>Currently I'm using php to upload the generated script into webserver and there process it. I think I should also include some signature to the file to avoid some "drop..." hacks.</p>
<p>If you can export the data as a sql script you can just run it against the remote server using your application of choice. 1000 records wont create that big a script.</p>
Mysterious EOF exception while reading a file with Java IO functions <p>I got following exception when I am trying to seek to some file. </p> <blockquote> <p>> Error while seeking to 38128 in myFile, File length: 85742 java.io.EOFException at java.io.RandomAccessFile.readInt(RandomAccessFile.java:725) at java.io.RandomAccessFile.readLong(RandomAccessFile.java:758) ></p> </blockquote> <p>But If you see I am trying to seek to '38128' where as file length is '85742'. It reported EOF exception. I wonder how it is possible? Another process appends contents to that file periodically and closes the file handler. It appends contents using DataOutputStream. My process is trying to seek to some locations and reading it. One more thing is I got this exception only once. I tried to reproduce it but it never happened again. The file is in local disk only. No filer.</p> <p>Thanks D. L. Kumar</p>
<p>I would be very careful when trying to do random access on a file that is concurrently being written to from another process. It might lead to all kinds of strange synchronisation problems, as you are experiencing right now. </p> <p>Do you determine the length of the file from the same process as the one doing the seek()? Has the other modifying processing done a flush()? </p>
How to center a mask in a Panel when rendering <p>I have a simple scenario where a panel needs a masked loading indicator over it while its loading the content. I have the mask working fine using the following code but the loading indicator appears at the top when calling it the first time. When calling it after the panel is shown, ie. on a button event, the mask appears correctly in the center of the panel. Any ideas?</p> <pre><code>var pnl = new Ext.Panel({ title: 'test', width: 500, height: 500, renderTo: 'controls', listeners: { render: function(comp) { comp.load(); } }, load: function() { this.el.mask('loading...', 'loadingMask'); } }); </code></pre>
<p>It appears the mask is applied to the panel before the html has been rendered completely. A simple solution was to delay the mask shortly before applying it.</p> <pre><code>render: function(comp) { setTimeout(function() { comp.loadPermissions(); }, 100); } </code></pre>
Need technology recommendation/suggestion <p>We (my company) is trying to develop a solution (application) for document management. We have considered using MS Sharepoint Server 2007 or Sharepoint Services, but we need recommendation or suggestion for this.</p> <p>We are planning to use windows workflow fundation for various tasks like(task assignment, document approval, information collection...). But we need suggestion on which product to choose, and/or witch technology.</p> <p>example: The user logs on a web portal to request a house building permit. He enters the required information in a form and submits the request. The request is then assigned to different persons or departments, depending in which stadium the request currently is. The user can anytime logs on to the web portal and see the state of his request and if required to enter some different information. </p>
<p>Well, I should just say that my one experience with Sharepoint is not great, and I am irritated by it's limitations every day, which is constantly adding to my frustration with it. I'm sure that it could be made more useful, but not as of yet.</p> <p>What you are looking for is a Business Process Management (Workflow) solution that is tied into Document Management. I did this work for the better part of a decade, so I know of a few companies that offer these products. (Some of these may be overkill, but then again, so is sharepoint)</p> <ul> <li><a href="http://en.wikipedia.org/wiki/FileNet" rel="nofollow">FileNet</a> - Offers both BPM and DM. pricey but 30 years experience doing the work and their products are Rock Solid. (Training is also in SoCal. Nice!) </li> <li><a href="http://epitomesystems.com/" rel="nofollow">Epitome</a> - Offers both BPM and DM (called it EPM - I hate marketing). licensing can run as a per seat or per transaction. (All .NET api's and can design or host the solution if you want)</li> <li><a href="http://www.opencms.org/en/" rel="nofollow">OpenCMS</a> - Just DM, free, but you will need to hook into BPM (WWFF).</li> <li><a href="http://www.otg.com/" rel="nofollow">OTG</a> - Offers both BPM and DM. No current idea on pricing, but very easy to understand product structure and is very easy to troubleshoot. </li> </ul> <p>Dont bother with </p> <ul> <li><a href="http://www.opencms.org/en/" rel="nofollow">OnBase</a> - Support is difficult and they are all COM components, .NET integration is difficult and they are not real willing to help integrators. </li> <li><a href="http://www.westbrooktech.com/" rel="nofollow">Fortis / FileMagic</a> - Just not mature enough last time I worked with them.</li> </ul> <p>If you are going to roll your own, make sure that you have at least these few things. </p> <ul> <li>Document versioning /change auditing. Each change should be recorded as a new separate document. (Even though you may be working with electronic forms, each time the data is changed, the old version should be preserved)</li> <li>Locks / checkout for a document. In much the same way source control works.</li> <li>Keep it simple. </li> </ul>
c# Read line from PDF <p>I want to be able to read line by line from a pdf, compare it to a string( a filename), and if the string appears in that line, write that line to a list.</p> <p>So far I had a quick look at ITextSharp and at PDFSharp, but it doesn't seem like these are the right tools for the job as they focus most on altering and printing pdfs.</p> <p>Does anyone know another way of reading lines from a pdf, or should I keep trying with ITextSharp &amp; PDFSharp?</p>
<p>I use <a href="http://www.pdfbox.org/userguide/dot_net.html" rel="nofollow">PDFBox</a> with Lucene. It was easy to find out how it works and it does the job. It's opensource and free.</p>
Is there a maximum number you can set Xmx to when trying to increase jvm memory? <p>Is there a max. size you can set Xmx to? I set it to 1024m and eclipse opens ok. When I set it above 1024, eclipse doesn't open and I get the error "jvm terminated. Exit code=-1"...</p> <p>I was doing this because I keep getting an "java.lang.OutOfMemoryError: Java heap space". I am reading in a 35.5Mb .txt file and this error occurs when it's just reading in the file using the "<code>while((line = reader.readLine()) != null)</code>" loop. I would have thought that 1024mb would have been enough. Can anyone help me?</p>
<p>Yes, there is a maximum, but it's system dependent. Try it and see, doubling until you hit a limit then searching down. At least with Sun JRE 1.6 on linux you get interesting if not always informative error messages (peregrino is netbook running 32 bit ubuntu with 2G RAM and no swap):</p> <pre><code>peregrino:$ java -Xmx4096M -cp bin WheelPrimes Invalid maximum heap size: -Xmx4096M The specified size exceeds the maximum representable size. Could not create the Java virtual machine. peregrino:$ java -Xmx4095M -cp bin WheelPrimes Error occurred during initialization of VM Incompatible minimum and maximum heap sizes specified peregrino:$ java -Xmx4092M -cp bin WheelPrimes Error occurred during initialization of VM The size of the object heap + VM data exceeds the maximum representable size peregrino:$ java -Xmx4000M -cp bin WheelPrimes Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine. (experiment reducing from 4000M until) peregrino:$ java -Xmx2686M -cp bin WheelPrimes (normal execution) </code></pre> <p>Most are self explanatory, except -Xmx4095M which is rather odd (maybe a signed/unsigned comparison?), and that it claims to reserve 2686M on a 2GB machine with no swap. But it does hint that the maximum size is 4G not 2G for a 32 bit VM, if the OS allows you to address that much.</p>
Are Transactions allowed by default in SQLServer? <p>I need to use DbTransactions (on a single db) but I am not sure about how to make sure it will keep working when I deploy to the production environment.</p> <p>What are the requirements for an application to be able to use SQL DbTransactions? Are they allowed by default in SQLServer (and what's the deal with MSDTC)?</p>
<p>Yes, transactions are enabled by default--I don't think this is something you can disable. Each time you run a query, it probably runs as an autocommit, implicit transaction, unless otherwise specified.</p> <p>MSDTC comes into play if you run distributed transactions. I'd avoid it if you can. That aspect <em>can</em> be disabled. If that's what you're using, then, you will need to make sure it's configured on the destination system.</p> <p>Just using the DBTransaction object for simple, successive queries or transactions within stored procedures won't need MSDTC.</p>
How to express the content referenced by the anchor tag <p>I'd like to express in an HTML document what kind of document is pointed by an anchor tag (<code>&lt;a&gt;</code>). For example, is it a list of dates, or a list of people, etc... All referenced documents will be Atom feeds, but the links will be displayed differently based on what the feed contains.</p> <p>I see 2 options :</p> <ol> <li><p><strong>using the "rel" attribute :</strong> this attribute is supposed to contains the <em>relation</em> between the current document and the referenced document. I don't think this is an optimal solution as this attribute is supposed to define the relation and not really the content. The referenced document will be a list of dates for all documents referencing it.</p></li> <li><p><strong>using the "type" attribute :</strong> this attribute is supposed to contains the content type of the referenced document. This solution seems closer to what I try to achieve, but this attribute should contains a content type and not a more generic description of the link.</p></li> </ol> <p>Which solution would you recommend ? Do you see a cleaner way to achieve the same result ?</p>
<p>Perhaps something like <a href="http://microformats.org/" rel="nofollow">microformats</a> will help?</p>
Persistence solutions for C++ (with a SQL database)? <p>I'm wondering what kind of persistence solutions are there for C++ with a SQL database? In addition to doing things with custom SQL (and encapsulating the data access to DAOs or something similar), are there some other (more general) solutions?</p> <p>Like some general libraries or frameworks (something like Hibernate &amp; co for Java and .NET) or something else? (Something that I haven't even thought of can also be welcome to be suggested)</p> <p>EDIT: Yep, I was searching more for an ORM solution or something similar to handle sql queries and the relationships between tables and objects than for the db engine itself. Thanks for all the answers anyway!</p>
<p><a href="http://www.sqlite.org/">SQLite</a> is great: it's fast, stable, proven, and easy to use and integrate. </p> <p>There is also <a href="http://www.equi4.com/metakit/">Metakit</a> although the learning curve is a bit steep. But I've used it with success in a professional project.</p>
ASP.NET - Trust Level = Full? <p>I recently joined a firm and when analyzing their environment I noticed that the SharePoint web.config had the trust level set to Full. I know this is an absolutely terrible practice and was hoping the stackoverflow community could help me outline the flaws in this decision. </p> <p>Oh, it appears this decision was made to allow the developers to deploy dlls to the Bin folder without creating CAS policies. Sigh.</p> <p>Just want to clarify and make matters worse, we are also deploying third party code to this web application.</p>
<p>Todd,</p> <p>The book, "<a href="http://www.google.com/search?sourceid=navclient&amp;ie=UTF-8&amp;rlz=1T4DMUS%5FenUS233US239&amp;q=Programming%2BMicrosoft%2BASP.Net%2B3.5" rel="nofollow">Programming Microsoft ASP.Net 3.5</a>", by Dino Espisito provides some sound reasoning for not allowing Full Trust in ASP.Net applications.</p> <p>Among other reasons, Dino states that web applications exposed to the internet are "one of the most hostile environments for computer security you can imagine." And:</p> <blockquote> <p>a publicly exposed fully trusted application is a potential platform for hackers to launch attacks. The less an application is trusted, the more secure that application happens to be.</p> </blockquote> <p>I'm surprised the StackOverflow community did not outline the problem with Full Trust better. I was hoping for the same thing so I didn't have to go digging through my pile of books to find the answer, lazy me.</p>
Finding out who is listening for PropertyChangedEventHandler in c# <p>I have a WPF form and I am working with databinding. I get the events raised from INotifyPropertyChanged, but I want to see how to get a list of what items are listening, which i fire up the connected handler.</p> <p>How can I do this?</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.delegate.getinvocationlist.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.delegate.getinvocationlist.aspx</a></p>
Automatic configuration reinitialization in Spring <p>In Log4j, there is a feature wherein the system can be initialized to do a configure and watch with an interval. This allows for the log4j system to reload its properties whenever the property file is changed. Does the spring framework have such a Configuration Observer facility wherein the Configuration is reloaded when it changed. The Configuration that needs reloading is not the Springs's applicationContext.xml but various other configuration files that are initialized using the Spring initialization beans. </p>
<p>I found a utility that does something similar to Log4J <a href="http://www.wuenschenswert.net/wunschdenken/archives/138">here</a>. It's basically an extension to PropertyPlaceholderConfigurer that reloads properties when they change.</p>
OracleDataReader loses results after examination <p>I have come across a quirky "feature" in Visual Studio and I was interested in seeing if anyone else had noticed this. Or if it is specific to myself.</p> <p>I have some methods that perform SQL queries on a database and then return an OracleDataReader</p> <pre><code>method() { OracleCommand cmd = new command(query, connection); OracleDataReader r = cmd.ExecuteReader(); return r; } </code></pre> <p>When I am debugging the code that uses this method. I can click on the non public members to view the rows in the results. However once I have viewed these results trying to perform a reader.Read() on the OracleDataReader does not contain any results. Checking the results in the debugger view shows the reader as Empty.</p> <p>Any time I do not check the results, the code that executes Read works without any problems.</p> <p>I've not found evidence of this via Google, but my search skills often leave a lot to be desired. If anyone could confirm this on a system of their own or shed some light on the causes I would greatly appreciate it.</p> <p>Thanks very much.</p>
<p>ADO.NET objects that derive from IDataReader (like your OracleDataReader) provide connected, forward-only access to the data returned by the query, so when you view the results in the debugging visualizer, you are actually stepping through the real data. When the program runs, the DataReader has iterated past the data and reports (correctly) that it is now empty.</p> <p>If you would like the flexibility to view the data in the debugger, you might consider using a disconnected, random-access data access class like the DataSet or DataTable.</p>
cruisecontrol config.xml special characters svnbootstrapper <p>I have a line like : </p> <pre><code> &lt;svnbootstrapper LocalWorkingCopy="${projects.dir}/${project.name}" Password="4udr=qudafe$h$&amp;e4Rub" Username="televic-education" /&gt; </code></pre> <p>in my config.xml. Because of special characters in the Password cruisecontrol service won't start. Is there a way to solve this?</p> <p>Maybe with setting a property? Or escaping characters?</p> <p>thx, Lieven Cardoen</p>
<p>Replace &amp; with &amp;amp; in the password attribute. I don't know if that's the problem, but it's definitely <em>a</em> problem.</p>
Multiple submit buttons/forms in Rails <p>I am trying to write a rails application which lets you go to a certain page, say /person/:id. On this page it shows a set of available resources. I want each resource to have a button next to it, which reserves that resource to that person (by creating a new instance of an Allocation model.) As an extension, I'd like several buttons by each resource, that cancel reservations and do other things. I'd also like to input data alongside some of the buttons, e.g. to allocate some % of a resource.</p> <p>My problem is I can't work out how to sensibly do this without repeating myself, or having a very hacky controller. How can I do this without matching on the value part of the submit buttons (the text on the buttons), or using any javascript?</p> <p>Additionally, if you have two forms on a page, how do you set it up so changes on both forms are saved when any submit button is clicked?</p>
<p>im using jQuery, and this is what i did :</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function() { $('#bulk_print').click(function(){ var target = '&lt;%= bulk_print_prepaid_vouchers_path(:format =&gt; :pdf) %&gt;'; $('#prepaidvoucher_bulk_print').attr('action', target); $('#prepaidvoucher_bulk_print').submit(); }); $('#bulk_destroy').click(function(){ var target = '&lt;%= bulk_destroy_prepaid_vouchers_path %&gt;'; $('#prepaidvoucher_bulk_print').attr('action', target); $('#prepaidvoucher_bulk_print').submit(); }); }); &lt;/script&gt; &lt;% form_tag '#', :method =&gt; :post, :id =&gt; 'prepaidvoucher_bulk_print' do %&gt; your form details &lt;button class="button" type="submit" id="bulk_print"&gt; &lt;%= image_tag("web-app-theme/printer.png", :alt =&gt; "Print Selected Vouchers") %&gt; Print Selected Vouchers &lt;/button&gt; &lt;button class="button" type="submit" id="bulk_destroy"&gt; &lt;%= image_tag("web-app-theme/cross.png", :alt =&gt; "Delete Selected Vouchers") %&gt; Delete Selected Vouchers &lt;/button&gt; &lt;% end %&gt; </code></pre> <p>The idea is to change the form action on the fly, based on which button is clicked</p>
Can you convert the output of php crypt() to valid MD5? <p>I have some strings that have been encrypted using the <a href="http://php.net/crypt" rel="nofollow">PHP function <code>crypt()</code></a>.</p> <p>The outputs look something like this:</p> <pre><code>$1$Vf/.4.1.$CgCo33ebiHVuFhpwS.kMI0 $1$84..vD4.$Ps1PdaLWRoaiWDKCfjLyV1 $1$or1.RY4.$v3xo04v1yfB7JxDj1sC/J/ </code></pre> <p>While I believe crypt() is using the MD5 algorithm, the outputs are not valid MD5 hashes.</p> <p>Is there a way of converting the produced hashes into valid MD5 hashes (16-byte hex values)?</p> <hr> <p><em>Update:</em></p> <p>Thanks for the replies so answers so far. I'm pretty sure the crypt function used is using some sort of MD5 algorithm. What I'm looking to do is convert the ouput that I have into an MD5 hash that looks something like the following:</p> <pre><code>9e107d9d372bb6826bd81d3542a419d6 e4d909c290d0fb1ca068ffaddf22cbd0 d41d8cd98f00b204e9800998ecf8427e </code></pre> <p><em>(taken from <a href="http://en.wikipedia.org/wiki/MD5" rel="nofollow">Wikipedia</a>)</em></p> <p>Is there a way of converting from the hashes I have to ones like the above?</p>
<p>OK, so maybe this answer is a year late, but I'll give it a shot. In your own answer, you note that <code>crypt()</code> is using the FreeBSD MD5, which also does some interesting transformations on the salt before running the hash, so the result of what I'm about to give you will never quite match up with the results of a call to <code>md5()</code>. That said, the only difference between the output you are seeing and the format you are used to is that the output you are seeing is encoded as follows</p> <pre><code>$1$ # this indicates that it is MD5 Vf/.4.1. # these eight characters are the significant portion of the salt $ # this character is technically part of the salt, but it is ignored CgCo33eb # the last 22 characters are the actual hash iHVuFhpw # they are base64 encoded (to be printable) using crypt's alphabet S.kMI0 # floor(22 * 6 / 8) = 16 (the length in bytes of a raw MD5 hash) </code></pre> <p>To my knowledge, the alphabet used by crypt looks like this:</p> <pre><code>./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz </code></pre> <p>So, with all of this borne in mind, here is how you can convert the 22 character crypt-base64 hash into a 32 character base16 (hexadecimal) hash:</p> <p>First, you need something to convert the base64 (with custom alphabet) into a raw 16-byte MD5 hash.</p> <pre><code>define('CRYPT_ALPHA','./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'); /** * Decodes a base64 string based on the alphabet set in constant CRYPT_ALPHA * Uses string functions rather than binary transformations, because said * transformations aren't really much faster in PHP * @params string $str The string to decode * @return string The raw output, which may include unprintable characters */ function base64_decode_ex($str) { // set up the array to feed numerical data using characters as keys $alpha = array_flip(str_split(CRYPT_ALPHA)); // split the input into single-character (6 bit) chunks $bitArray = str_split($str); $decodedStr = ''; foreach ($bitArray as &amp;$bits) { if ($bits == '$') { // $ indicates the end of the string, to stop processing here break; } if (!isset($alpha[$bits])) { // if we encounter a character not in the alphabet return false; // then break execution, the string is invalid } // decbin will only return significant digits, so use sprintf to pad to 6 bits $decodedStr .= sprintf('%06s', decbin($alpha[$bits])); } // there can be up to 6 unused bits at the end of a string, so discard them $decodedStr = substr($decodedStr, 0, strlen($decodedStr) - (strlen($decodedStr) % 8)); $byteArray = str_split($decodedStr, 8); foreach ($byteArray as &amp;$byte) { $byte = chr(bindec($byte)); } return join($byteArray); } </code></pre> <p>Now that you've got the raw data, you'll need a method to convert it to the base-16 format you're expecting, which couldn't be easier.</p> <pre><code>/** * Takes an input in base 256 and encodes it to base 16 using the Hex alphabet * This function will not be commented. For more info: * @see http://php.net/str-split * @see http://php.net/sprintf * * @param string $str The value to convert * @return string The base 16 rendering */ function base16_encode($str) { $byteArray = str_split($str); foreach ($byteArray as &amp;$byte) { $byte = sprintf('%02x', ord($byte)); } return join($byteArray); } </code></pre> <p>Finally, since the output of crypt includes a lot of data we don't need (and, in fact, cannot use) for this process, a short and sweet function to not only tie these two together but to allow for direct input of output from crypt.</p> <pre><code>/** * Takes a 22 byte crypt-base-64 hash and converts it to base 16 * If the input is longer than 22 chars (e.g., the entire output of crypt()), * then this function will strip all but the last 22. Fails if under 22 chars * * @param string $hash The hash to convert * @param string The equivalent base16 hash (therefore a number) */ function md5_b64tob16($hash) { if (strlen($hash) &lt; 22) { return false; } if (strlen($hash) &gt; 22) { $hash = substr($hash,-22); } return base16_encode(base64_decode_ex($hash)); } </code></pre> <p>Given these functions, the base16 representation of your three examples are:</p> <pre><code>3ac3b4145aa7b9387a46dd7c780c1850 6f80dba665e27749ae88f58eaef5fe84 ec5f74086ec3fab34957d3ef0f838154 </code></pre> <p>Of course, it is important to remember that they were always valid, just formatted differently.</p>
copy Word document contents without using clipboard (VBA) <p>I was wondering how to avoid using Windows clipboard, when you want to "replicate" multiple sections of a Word document (using VBA in macros)</p> <p>Why to avoid? Because we're using Word on a server, in a multiuser environment (I know that it is officially frowned upon)</p> <p>Otherwise, this would be easily accomplished with Selection.Copy and Selection.Paste methods.</p> <p>Thanks.</p>
<p>I finally resolved to copy word by word. FormattedText seemed to work fairly well, until the last word (some special (evidently) characters), where suddenly the cell that I just filled with copied content would go blank. When I increased the number of cells, other run-time errors would pop up, like Your table got corrupted, and other ambiguous ones. Somehow, the source cell that I was copying from always seemed to have these peculiar chars in the end with ASCII codes 13 and 7. I know what 13 means, but 7? Anyway, I decided to copy everything apart from this last character with code 7. It seems to work alright. Both formatting and fields are copied too. In any case, the whole story proved to me for one more time that programming in VBA is mostly trial-and-error occupation. You are never sure when something might break.. unless I am missing update on some crucial concepts..</p> <p>Here's the chunks of the code I used. The idea is that first we have a document with a single 1x1 cell table, with some rich text content. In the first piece of the code (inside a macro) I multiply the cells:</p> <p>(NOTE that I put // in front of each apostrophe-type VB comment so that the comment would be colored correctly)</p> <pre><code>Dim cur_width As Integer, i As Integer, max_cells As Integer, cur_row As Integer Dim origin_width As Integer If ActiveDocument.Tables.Count = 1 _ And ActiveDocument.Tables(1).Rows.Count = 1 _ And ActiveDocument.Tables(1).Columns.Count = 1 _ Then max_cells = 7 //' how many times we are going to "clone" the original content i = 2 //' current cell count - starting from 2 since the cell with the original content is cell number 1 cur_width = -1 //' current width cur_row = 1 //' current row count origin_width = ActiveDocument.Tables(1).Rows(1).Cells(1).Width //' loop for each row While i &lt;= max_cells //' adjust current width If cur_row = 1 Then cur_width = origin_width Else cur_width = 0 End If //' loop for each cell - as long as we have space, add cells horizontally While i &lt;= max_cells And cur_width + origin_width &lt; ActiveDocument.PageSetup.PageWidth Dim col As Integer //' \ returns floor() of the result col = i \ ActiveDocument.Tables(1).Rows.Count // 'add cell, if it is not already created (which happens when we add rows) If ActiveDocument.Tables(1).Rows(cur_row).Cells.Count &lt; col Then ActiveDocument.Tables(1).Rows(cur_row).Cells.Add End If // 'adjust new cell width (probably unnecessary With ActiveDocument.Tables(1).Rows(cur_row).Cells(col) .Width = origin_width End With // 'keep track of the current width cur_width = cur_width + origin_width i = i + 1 Wend //' when we don't have any horizontal space left, add row If i &lt;= max_cells Then ActiveDocument.Tables(1).Rows.Add cur_row = cur_row + 1 End If Wend End If </code></pre> <p>In the second part of the macro I populate each empty cell with the contents of the first cell:</p> <pre><code> //' duplicate the contents of the first cell to other cells Dim r As Row Dim c As Cell Dim b As Boolean Dim w As Range Dim rn As Range b = False i = 1 For Each r In ActiveDocument.Tables(1).Rows For Each c In r.Cells If i &lt;= max_cells Then // ' don't copy first cell to itself If b = True Then //' copy everything word by word For Each w In ActiveDocument.Tables(1).Rows(1).Cells(1).Range.Words //' get the last bit of formatted text in the destination cell, as range //' do it first by getting the whole range of the cell, then collapsing it //' so that it is now the very end of the cell, and moving it one character //' before (because collapsing moves the range actually beyond the last character of the range) Set rn = c.Range rn.Collapse Direction:=wdCollapseEnd rn.MoveEnd Unit:=wdCharacter, Count:=-1 //' somehow the last word of the contents of the cell is always Chr(13) &amp; Chr(7) //' and especially Chr(7) causes some very strange and murky problems //' I end up avoiding them by not copying the last character, and by setting as a rule //' that the contents of the first cell should always contain an empty line in the end If c.Range.Words.Count &lt;&gt; ActiveDocument.Tables(1).Rows(1).Cells(1).Range.Words.Count Then rn.FormattedText = w Else //'MsgBox "The strange text is: " &amp; w.Text //'the two byte values of this text (which obviously contains special characters with special //'meaning to Word can be found (and watched) with //'AscB(Mid(w.Text, 1, 1)) and AscB(Mid(w.Text, 2, 1)) w.MoveEnd Unit:=WdUnits.wdCharacter, Count:=-1 rn.FormattedText = w End If Next w End If b = True End If i = i + 1 Next c Next r </code></pre> <p>Here are the images of the Word document in question. First image is before running the macro, second is between the first chunk of code and the last, while the third image is the resulting document.</p> <p><a href="http://i41.photobucket.com/albums/e276/morninghalo/stackovfl/1.jpg" rel="nofollow">Image 1</a> <a href="http://i41.photobucket.com/albums/e276/morninghalo/stackovfl/2.jpg" rel="nofollow">Image 2</a> <a href="http://i41.photobucket.com/albums/e276/morninghalo/stackovfl/done.jpg" rel="nofollow">Image 3</a></p> <p>That's it.</p>
Internet Explorer CSS Line Height For MusiSync Font <p>I'm trying to use the MusiSync font to embed a sharp and flat symbol in a line of text. In order to keep these symbols from being tiny I have to make their point size twice the size of the rest of the text. Unfortunately, this messes up the line height in Internet Explorer and I cannot find a way to control it. You can download the MusiSync font at:</p> <p><a href="http://www.icogitate.com/~ergosum/fonts/musicfonts.htm" rel="nofollow">http://www.icogitate.com/~ergosum/fonts/musicfonts.htm</a> </p> <p>My attempt to use this font in a web page can be found at:</p> <p><a href="http://www.williamsportwebdeveloper.com/MusiSync.htm" rel="nofollow">http://www.williamsportwebdeveloper.com/MusiSync.htm</a></p>
<p>I opened up Photoshop and used the font you link to. There is a huge amount of white-space above each glyph in the font itself. The font is poorly designed.</p> <p>If you set your style to this, you'll see the issue:</p> <pre><code>.style2 { font-family: MusiSync; font-size: 24pt; border:1px solid #000000; } </code></pre> <p>The problem appears in FireFiox 3 as well, its just manifesting itself a little differently.</p> <p>You may be able to hack your way around this somehow, but it's going to be ugly. Unless you're using a lot of different font sizes, you may be better of using images.</p>
Selecting an index in a QListView <p>This might be a stupid question, but I can't for the life of me figure out how to select the row of a given index in a QListView.</p> <p>QAbstractItemView , QListView's parent has a setCurrentIndex(const QModelIndex &amp;index). The problem is, I can't construct a QModelIndex with the row number I want since the row and column field of the QModelIndex has no mutators.</p> <p>QTableView, which also inherits from QAbstractItemView has a selectRow(int row) function, why in the seven hells doesn't the QListView have this?</p> <p>Good ol' windows forms has the SelectedIndex property on it's listviews.</p>
<p><a href="http://doc.trolltech.com/4.4/model-view-selection.html">This</a> should help you get started</p> <pre><code>QModelIndex index = model-&gt;createIndex( row, column ); if ( index.isValid() ) model-&gt;selectionModel()-&gt;select( index, QItemSelectionModel::Select ); </code></pre>
Is there a method in PL/SQL to convert/encode text to XML compliant text? <p>I have a colleague who needs to convert text from a PL/SQL method into XML compliant text, as he is constructing a excel spreadsheet by updating a text template.</p> <p>Is there a method in PL/SQL to convert/encode text to XML compliant text?</p>
<p>Well, if you just want to convert XML characters, you'll want to do something like...</p> <pre><code> outgoing_text := DBMS_XMLGEN.CONVERT(incoming_text) </code></pre> <p>Where <code>outgoing_text</code> and <code>incoming_text</code> are both VARCHAR2 or CLOB.</p> <p>You can specify a second argument, but it defaults to <code>DBMS_XMLGEN.ENTITY_ENCODE</code>... it can also decode XML entities by passing <code>DBMS_XMLGEN.ENTITY_DECODE</code> as a second argument.</p>
Bash script to create symbolic links to shared libraries <p>I think this question is rather easy for you shell scripting monsters.</p> <p>I am looking for the most elegant and shortest way to create symbolic links to shared libraries for Unix by means of a bash shell script.</p> <p>What I need is starting out with a list of shared library files such as "libmythings.so.1.1, libotherthings.so.5.11", get the symbolic links created such as: </p> <pre><code>libmythings.so -&gt; libmythings.so.1 -&gt; libmythings.so.1.1 libotherthings.so -&gt; libotherthings.so.5 -&gt; libotherthings.so.5.11 </code></pre> <p>The library files are inside a directory which contains other files such as other shell scripts.</p> <p><strong>EDIT</strong>: Well, "ldconfig -nN ." could work OK, but I also need the link without the major number of the library appended after ".so", at least one of the libraries, since one or more libraries are the entry points of JNI calls from Java, so when a library is instanced by means of System.loadlibrary("libraryname") it expects a library called "libraryname.so", not "libraryname.so.X". </p> <p>The solution with just ldconfig -nN could work if there were a workaround for the Java part.</p>
<p>I believe <code>ldconfig</code> is the standard tool that does this. </p> <p>I recall somewhere it can generate symlinks based on internal version info, but can't find the source right now.</p> <p><strong>EDIT</strong> Yes, if you run </p> <pre><code>ldconfig -v </code></pre> <p>You'll see it generating all the links based on library internals. </p> <pre><code>ldconfig /path/to/dir </code></pre> <p>Will only create links for files in that dir </p> <p>A note though, I played with it and it doesn't seem to consistently create .so$, just .so.{major} </p> <p>I'm not sure how its internals work, but I do know: </p> <pre> lib # rm libmagic.so lib # rm libmagic.so.1 lib # ldconfig lib # file libmagic.so.1 libmagic.so.1: symbolic link to `libmagic.so.1.0.0' lib # file libmagic.so libmagic.so: cannot open `libmagic.so' (No such file or directory) </pre> <p>So what determines how this works is a mystery to me </p> <p><strong>Edit</strong> Upon Further Discetion, .la files have no influence on behaviour. </p> <p>The "SO" name field indicates what the symlink will be called. </p> <p>And there will only be one. </p> <p>0x000000000000000e (SONAME) Library soname: [libmagix.so ]</p> <p>This is after hacking the code and replacing the ".1" with spaces. </p> <p>ldconfig generated "libmagic.so " ( yes, spaces included ) </p>
Acquiring drive names (as opposed to drive letters) in Java <p>On my Windows machine, my main hard drive has the letter C: and the name "Local disk". </p> <p>To list the drive letters in Java on Windows, the File object has the static listRoots() method. But I can't find a way to acquire the drive names (as opposed to the drive letters) on Windows.</p> <p>Has anyone tried this before?</p>
<p>Ah yes, you need to get the FileSystemView object and use <a href="http://java.sun.com/javase/6/docs/api/javax/swing/filechooser/FileSystemView.html#getSystemDisplayName(java.io.File)" rel="nofollow">getSystemDisplayName</a>. (I once implemented a Filesystem browser in Java).</p> <p>It's not perfect though but it will get you the name. From the documentation:</p> <blockquote> <p>Name of a file, directory, or folder as it would be displayed in a system file browser. Example from Windows: the "M:\" directory displays as "CD-ROM (M:)" The default implementation gets information from the ShellFolder class. </p> </blockquote>
VB6: List available commands, then execute a random one of them <p>Hallo! I'm a n00b, and I'm looking for a few lines of code in VB6 to implement this: I want to list a certain number of commands to execute, then tell my program to chose a random one among them and execute it: strictly speaking, I'm dealing with a MSAgent character, and I want him to make a face every 5 minutes. How can I achieve this, please?</p>
<pre><code>Public Sub MakeFace() 'Reset random seed. Randomize 'Generate a random integer with the specified range. Dim Min As Integer, Max As Integer, N As Integer Min = 1 Max = 5 N = Min + Round(Rnd) * Max 'Select and call the desired function. Select Case N Case 1 Call MakeHappyFace Case 2 Call MakeSadFace Case 3 Call MakeAngryFace Case 4 Call MakeSmirkFace Case 5 Call MakeFunnyFace End Select End Sub </code></pre>
Launching a C++ executable from a C# app and keeping role based security context <p>First off I know this is probably a tall order but... :)</p> <p>We have some software that interacts with the hardware our company produces. This software loads a .NET assembly and this acts as our interface to the hardware. </p> <p>Currently we have a 'Launcher' application written in C# which provides role based security. This 'Launcher' launches the C++ executable with command line arguments (the .NET assembly to use) via a process. The C++ executable then loads the supplied .NET assembly and uses it to perform its actions.</p> <p>The problem is because I launch the C++ application in a process I lose the role based security context provided by the 'Launcher'.</p> <p>Is there any way I can launch the C++ application and keep the role based security context?</p> <p>Thanks for taking the time to read this. If you have any questions please let me know.</p> <p>Thank you,</p> <p>Adam </p>
<p>You would have to modify the C++ application to check the roles as well.</p> <p>If you can do that, you might consider breaking up part of your C# application into multiple assemblies. Specifically, take the roles part the C# application, and compile that as a dll with COM/ActiveX extensions.</p> <p>Then you can call the C# dll (via COM) to check permissions.</p>
Why doesn't C++ have a pointer to member function type? <p>I could be totally wrong here, but as I understand it, C++ doesn't really have a native "pointer to member function" type. I know you can do tricks with Boost and mem_fun etc. But why did the designers of C++ decide not to have a 64-bit pointer containing a pointer to the function and a pointer to the object, for example?</p> <p>What I mean specifically is a pointer to a member function of a <em>particular</em> object of <em>unknown type</em>. I.E. something you can use for a <strong>callback</strong>. This would be a type which contains <em>two</em> values. The first value being a pointer to the <em>function</em>, and the second value being a pointer to the <em>specific instance</em> of the object.</p> <p>What I do not mean is a pointer to a general member function of a class. E.G.</p> <pre><code>int (Fred::*)(char,float) </code></pre> <p>It would have been so useful and made my life easier.</p> <p>Hugo</p>
<p>@RocketMagnet - This is in response to your <a href="http://stackoverflow.com/questions/462491/again-why-doesnt-c-have-a-pointer-to-member-function-type">other question</a>, the one which was labeled a duplicate. I'm answering <em>that</em> question, not this one.</p> <p>In general, C++ pointer to member functions can't portably be cast across the class hierarchy. That said you can often get away with it. For instance:</p> <pre><code>#include &lt;iostream&gt; using std::cout; class A { public: int x; }; class B { public: int y; }; class C : public B, public A { public: void foo(){ cout &lt;&lt; "a.x == " &lt;&lt; x &lt;&lt; "\n";}}; int main() { typedef void (A::*pmf_t)(); C c; c.x = 42; c.y = -1; pmf_t mf = static_cast&lt;pmf_t&gt;(&amp;C::foo); (c.*mf)(); } </code></pre> <p>Compile this code, and the compiler <strong>rightly</strong> complains:</p> <pre><code>$ cl /EHsc /Zi /nologo pmf.cpp pmf.cpp pmf.cpp(15) : warning C4407: cast between different pointer to member representations, compiler may generate incorrect code $ </code></pre> <p>So to answer "why doesn't C++ have a pointer-to-member-function-on-void-class?" is that this imaginary base-class-of-everything has no members, so there's no value you could safely assign to it! "void (C::<em>)()" and "void (void::</em>)()" are mutually incompatible types.</p> <p>Now, I bet you're thinking "wait, i've cast member-function-pointers just fine before!" Yes, you may have, using reinterpret_cast and single inheritance. This is in the same category of other reinterpret casts:</p> <pre><code>#include &lt;iostream&gt; using std::cout; class A { public: int x; }; class B { public: int y; }; class C : public B, public A { public: void foo(){ cout &lt;&lt; "a.x == " &lt;&lt; x &lt;&lt; "\n";}}; class D { public: int z; }; int main() { C c; c.x = 42; c.y = -1; // this will print -1 D&amp; d = reinterpret_cast&lt;D&amp;&gt;(c); cout &lt;&lt; "d.z == " &lt;&lt; d.z &lt;&lt; "\n"; } </code></pre> <p>So if <code>void (void::*)()</code> did exist, but there is nothing you could safely/portably assign to it.</p> <p>Traditionally, you use functions of signature <code>void (*)(void*)</code> anywhere you'd thing of using <code>void (void::*)()</code>, because while member-function-pointers don't cast well up and down the inheritance heirarchy, void pointers do cast well. Instead:</p> <pre><code>#include &lt;iostream&gt; using std::cout; class A { public: int x; }; class B { public: int y; }; class C : public B, public A { public: void foo(){ cout &lt;&lt; "a.x == " &lt;&lt; x &lt;&lt; "\n";}}; void do_foo(void* ptrToC){ C* c = static_cast&lt;C*&gt;(ptrToC); c-&gt;foo(); } int main() { typedef void (*pf_t)(void*); C c; c.x = 42; c.y = -1; pf_t f = do_foo; f(&amp;c); } </code></pre> <p>So to your question. Why doesn't C++ support this sort of casting. Pointer-to-member-function types already have to deal with virtual vs non-virtual base classes, and virtual vs non-virtual member functions, all in the same type, inflating them to 4*sizeof(void*) on some platforms. I think because it would further complicate the implementation of pointer-to-member-function, and raw function pointers already solve this problem so well. </p> <p>Like others have commented, C++ gives library writers enough tools to get this done, and then 'normal' programmers like you and me should use those libraries instead of sweating these details.</p> <p>EDIT: marked community wiki. Please only edit to include relevant references to the C++ standard, and add in italic. (esp. add references to standard where my understanding was wrong! ^_^ )</p>
Get File Icon used by Shell <p>In .Net (C# or VB: don't care), given a file path string, FileInfo struct, or FileSystemInfo struct for a real existing file, how can I determine the icon(s) used by the shell (explorer) for that file?</p> <p>I'm not currently planning to use this for anything, but I became curious about how to do it when looking at <a href="http://stackoverflow.com/questions/462232/what-is-the-best-vb-net-control-standard-custom-for-displaying-list-of-files">this question</a> and I thought it would be useful to have archived here on SO.</p>
<pre><code>Imports System.Drawing Module Module1 Sub Main() Dim filePath As String = "C:\myfile.exe" Dim TheIcon As Icon = IconFromFilePath(filePath) If TheIcon IsNot Nothing Then ''#Save it to disk, or do whatever you want with it. Using stream As New System.IO.FileStream("c:\myfile.ico", IO.FileMode.CreateNew) TheIcon.Save(stream) End Using End If End Sub Public Function IconFromFilePath(filePath As String) As Icon Dim result As Icon = Nothing Try result = Icon.ExtractAssociatedIcon(filePath) Catch ''# swallow and return nothing. You could supply a default Icon here as well End Try Return result End Function End Module </code></pre>
Window-overflowing widget in wxWidgets <p>I'm looking for a way to implement this design in wxPython on Linux...<br /> I have a toolbar with a button, when the button is pressed a popup should appear, mimicking an extension of the toolbar (like a menu), and this popup should show two columns of radio buttons (say 2x5) and a text box... My main problem is that the toolbar is small in height, so the popup has to overflow the bounds of the window/client area..</p> <p>I thought of two possible implementations: </p> <ul> <li>by using a wxMenu, since a menu <em>can</em> be drawn outside the client area. I fear that the layout possibilities aren't flexible enough for my goal</li> <li>by using a shaped frame. Pressing the button would re-shape the frame and draw the needed widgets as requested.</li> </ul> <p>My question is: am I missing something / wrong on something? :) Is this doable at all?</p>
<p>Using a menu is a no-go, because <code>wxWidgets</code> can't put widgets on a menu. Using the shaped frame would be possible in principle, but the problem is then to get the position of the button you clicked, to display the window at the right position. I tried to do that back then, but didn't have luck (in C++ wxWidgets). Maybe this situation changed in between though, good luck. </p> <p>You can also try a <code>wxComboCtrl</code>, which allows you to have a custom popup window. That one could then display the radio boxes and the input control.</p>
Page refreshing after the parameter selection in SSRS report <p>I have couple of parameters in my SSRS report. some are multivalued and some are regular with drop down list. each time while selecting a different parameter value the page is getting refreshed. Is there any way to avoid this page refreshment on each parameter selection.</p> <p>Thanks in advance. Maria</p>
<p>I just encountered to this problem today, and the following post definitely helped me.</p> <p><a href="http://blog.summitcloud.com/2009/12/fix-refresh-of-parameters-in-ssrs/" rel="nofollow">http://blog.summitcloud.com/2009/12/fix-refresh-of-parameters-in-ssrs/</a></p> <p>quoting from the post:</p> <blockquote> <p>According to Microsoft, if a default value or valid values list is “too complex” (could be as simple as <code>=Year()</code> expression) for the RS engine to comprehend at runtime it will determine that it is dependent and therefore a candidate for refreshing.</p> </blockquote> <p>The post in the link shows a simple workaround example:</p> <blockquote> <p>If you can, take those VB expressions and turn them into datasets that return values based on an SQL statement. So <code>=Year()</code> in the expression would become something like <code>Select Year(getdate()) as CurYear</code></p> </blockquote> <p>Hope it helps.</p>
How to stretch in width a WPF user control to its window? <p>I have a Window with my user control and I would like to make usercontrol width equals window width. How to do that?</p> <p>The user control is a horizontal menu and contains a grid with three columns:</p> <pre><code>&lt;ColumnDefinition Name="LeftSideMenu" Width="433"/&gt; &lt;ColumnDefinition Name="Middle" Width="*"/&gt; &lt;ColumnDefinition Name="RightSideMenu" Width="90"/&gt; </code></pre> <p>That is the reason I want the window width, to stretch the user control to 100% width, with the second column relative.</p> <p>EDIT:</p> <p>I am using a grid, there is the code for Window:</p> <pre><code>&lt;Window x:Class="TCI.Indexer.UI.Operacao" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:tci="clr-namespace:TCI.Indexer.UI.Controles" Title=" " MinHeight="550" MinWidth="675" Loaded="Load" ResizeMode="NoResize" WindowStyle="None" WindowStartupLocation="CenterScreen" WindowState="Maximized" Focusable="True" x:Name="windowOperacao"&gt; &lt;Canvas x:Name="canv"&gt; &lt;Grid&gt; &lt;tci:Status x:Name="ucStatus"/&gt; &lt;!-- the control which I want to stretch in width --&gt; &lt;/Grid&gt; &lt;/Canvas&gt; &lt;/Window&gt; </code></pre>
<p>You need to make sure your usercontrol hasn't set it's width in the usercontrol's xaml file. Just delete the Width="..." from it and you're good to go!</p> <p><strong>EDIT:</strong> This is the code I tested it with:</p> <p><em>SOUserAnswerTest.xaml:</em></p> <pre><code>&lt;UserControl x:Class="WpfApplication1.SOAnswerTest" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="300"&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Name="LeftSideMenu" Width="100"/&gt; &lt;ColumnDefinition Name="Middle" Width="*"/&gt; &lt;ColumnDefinition Name="RightSideMenu" Width="90"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;TextBlock Grid.Column="0"&gt;a&lt;/TextBlock&gt; &lt;TextBlock Grid.Column="1"&gt;b&lt;/TextBlock&gt; &lt;TextBlock Grid.Column="2"&gt;c&lt;/TextBlock&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p><em>Window1.xaml:</em></p> <pre><code>&lt;Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="Window1" Height="300" Width="415"&gt; &lt;Grid&gt; &lt;local:SOAnswerTest Grid.Column="0" Grid.Row="5" Grid.ColumnSpan="2"/&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre>
Version of XSLT in iPhone <p>I plan to use XML/XSLT in my iPhone application. </p> <p>What version of XSLT is currently supported on the iPhone? Can I use XSLT 2.0 or just 1.0 ?</p>
<p>Using <code>libxslt</code> on the iPhone OS is actually quite easy:</p> <ol> <li><a href="http://xmlsoft.org/XSLT/downloads.html">Download the source-code of libxslt</a> and extract it.</li> <li>Add the "libxslt" dir to <strong>Header search paths</strong> in your build settings. Also, add the path to the libxml-headers there (usually <code>/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.0.sdk/usr/include/libxml2</code>).</li> <li>Add libxml2.2.dylib and libxslt.dylib to the <strong>linked frameworks</strong> (Xcode "Groups &amp; Files" panel: right click on "Frameworks" --> "Add" --> "Existing Frameworks...").</li> <li>Create a simple XML file and its XSL tranformation.</li> </ol> <p>And finally you can use a code similar to the sample above to get the tranformation result into an <code>NSString</code> (e.g. to display in in a <code>UIWebView</code>):</p> <pre><code>#import &lt;libxml/xmlmemory.h&gt; #import &lt;libxml/debugXML.h&gt; #import &lt;libxml/HTMLtree.h&gt; #import &lt;libxml/xmlIO.h&gt; #import &lt;libxml/xinclude.h&gt; #import &lt;libxml/catalog.h&gt; #import &lt;libxslt/xslt.h&gt; #import &lt;libxslt/xsltInternals.h&gt; #import &lt;libxslt/transform.h&gt; #import &lt;libxslt/xsltutils.h&gt; ... NSString* filePath = [[NSBundle mainBundle] pathForResource: @"article" ofType: @"xml"]; NSString* styleSheetPath = [[NSBundle mainBundle] pathForResource: @"article_transform" ofType:@"xml"]; xmlDocPtr doc, res; // tells the libxml2 parser to substitute entities as it parses your file xmlSubstituteEntitiesDefault(1); // This tells libxml to load external entity subsets xmlLoadExtDtdDefaultValue = 1; sty = xsltParseStylesheetFile((const xmlChar *)[styleSheetPath cStringUsingEncoding: NSUTF8StringEncoding]); doc = xmlParseFile([filePath cStringUsingEncoding: NSUTF8StringEncoding]); res = xsltApplyStylesheet(sty, doc, NULL); char* xmlResultBuffer = nil; int length = 0; xsltSaveResultToString(&amp;xmlResultBuffer, &amp;length, res, sty); NSString* result = [NSString stringWithCString: xmlResultBuffer encoding: NSUTF8StringEncoding]; NSLog(@"Result: %@", result); free(xmlResultBuffer); xsltFreeStylesheet(sty); xmlFreeDoc(res); xmlFreeDoc(doc); xsltCleanupGlobals(); xmlCleanupParser(); </code></pre>
Can I get the matrix determinant using Numpy? <p>I read in the manual of Numpy that there is function <code>det(M)</code> that can calculate the determinant. However, I can't find the <code>det()</code> method in Numpy.</p> <p>By the way, I use Python 2.5. There should be no compatibility problems with Numpy.</p>
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.det.html"><code>numpy.linalg.det</code></a> to compute the determinant of an array:</p> <pre><code>In [1]: import numpy In [2]: M = [[1, 2], [3, 4]] In [3]: print numpy.linalg.det(M) Out[3]: -2.0000000000000004 </code></pre>
String.Format for C++ <p>Looking for an implementation for C++ of a function like .NET's String.Format. Obviously there is printf and it's varieties, but I'm looking for something that is positional as in:</p> <blockquote> <p>String.Format("Hi there {0}. You are {1} years old. How does it feel to be {1}?", name, age);</p> </blockquote> <p>This is needed because we're going to try and make it easier to localize our app, and giving the translators {0} and {1} to position anywhere in the sentence is much easier than giving them a %s, %d, %d which must be positioned in that order in their translation.</p> <p>I suppose search and replace with variable inputs (va_start, va_end, etc) is what I'll end up building, but if there is already a solid solution, that would be preferrable.</p> <p>Thanks :)</p>
<p>Look at the <a href="http://www.boost.org/doc/libs/1_37_0/libs/format/index.html" rel="nofollow">boost format library.</a></p>
Tiny flash in safari - very strange bug! <p>We have a flash file that in every other browser displays at its correct size (which is something like 1600px) however, in safari it appears tiny. We have also noticed that sometimes when the flash file is not cached it appears at normal size, then after a soft refresh the flash goes tiny again.</p> <p>We are using mootools to include the flash but I've also tried just using flash's HTML/Javascript with the publish function, we still have the same problem with it being tiny in safari.</p> <p>Does anyone have any ideas as to what this could be?</p> <p>Thanks Tom</p>
<p>Here is a <a href="http://forums.macrumors.com/showthread.php?t=583623" rel="nofollow">discussion</a> about a similar problem with Safari and Flash Video, perhaps it helps.</p>
Best way to optimize dataset that contains linestrings. Some lines start and end at same coordinates <p><strong>THE SETUP</strong><br /> I have a table which contains linestrings. Linestrings are made up of multiple geographic points. Each point is made up of a latitude and longitude. Note: the linestring value is stored as TEXT in the database.</p> <p>So one row in the table might look like this:<br /> id: an integer<br /> linestring: x1, y2, x2, y2, x3, y3, x4, y4</p> <p><strong>THE PROBLEM</strong><br /> Google Maps only allows up to 1000 elements to be displayed at a time. In my case, I'm displaying 850 linestrings and will need to add many more in the future.</p> <p><strong>THE QUESTION</strong><br /> Quite a few of the linestrings connect with one or more other linestrings, meaning that they start and/or end at the same coordinates. What I'd look to do is find the best way to optimize the dataset so linestrings which connect at the ends are merged in the DB table. This will reduce the total element count when I parse the DB table and create the display file for google maps.</p> <p><strong>EXAMPLE</strong><br /> In this example, imagine, the alpha (A,B,C) values represent geographic points. The unoptimized table might look like this:</p> <p>before optimization:<br /> <strong>id linestring</strong><br /> 1 A, B, C<br /> 2 C, D<br /> 3 B, A<br /> 4 F, G, H<br /> 5 G, I<br /> 6 H, J <hr /></p> <p>After optimization:<br /> 1 A, B, C, D<br /> 2 F, G, H, J<br /> 3 G, I<br /> <hr /></p> <p>So what is the best way to optimize the data? Is there a particular algorithm which works best? I have some ideas for solutions which I will formulate and add, but they seem verbose and convulated.</p> <p>I am not a CS major so excuse the sloppy terminology and let me know if clarification is needed anywhere. Thanks! <hr /></p> <p>FYI.. I am using a MySQL DB. I am not using the spatial extensions. If you have an embarrassingly simple solution that uses the spatial extensions I would love to hear about it anyway.</p>
<p>I think the easiest way to go here is using the MySQL spatial extensions. </p> <p>Particularly I have only used Oracle spatial extensions. In Oracle we can use functions like <a href="http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14255/sdo_objgeom.htm#BGHCDIDG" rel="nofollow">SDO_GEOM.RELATE</a> or <a href="http://www.potu.com/man/mysql/manual_Spatial_extensions_in_MySQL.html#Functions_for_testing_spatial_relations_between_geometric_objects" rel="nofollow">SDO_RELATE</a> to find out the spatial relationship between two objects (contains, touches, intersects, etc.)</p> <p>I am sure there is an equivalent spatial function in MySQL</p> <p>EDIT:</p> <p>Here is a <a href="http://www.potu.com/man/mysql/manual_Spatial_extensions_in_MySQL.html#Functions_for_testing_spatial_relations_between_geometric_objects" rel="nofollow">link</a> that lists all the available MySQL spatial functions.</p>
Checkstyle for ActionScript (Flex) <p>HI, I'm currently working on a project that uses Flex and Java. In Java we easily enforced a coding standard with Checkstyle, and we want to do this for Flex.</p> <p>Does anybody know of a tool similar to Checkstyle that would allow coding standard checks? (I've googled for this but found only one project written in python and it seams abandoned)</p> <p>Thanks</p>
<p>The long and the short is that there is... kind of, but only for Actionscript, and you have to test it yourself... There is a <a href="http://code.google.com/p/checkstyleas3/downloads/list" rel="nofollow">prototype</a> of an Actionscript 3 version, but it is not even in Beta yet (and I admit that I haven't had the time to test it). I haven't found anything similar for XML, let alone MXML. This is in at least one list of <a href="http://clintm.esria.com/2007/12/10/flex-builder-4-feature-wish-list/" rel="nofollow">feature requests</a> for Flex 4, however.</p>
Getting odd error on .net ExecuteNonQuery <p>I'm working in .NET with SQL server on the backend</p> <p>I have a database that I create a record in using a web control - then I need to update some of the fields.<br /> I can trap the sql statement and run it in sql server successfully - however, when I try to run execute non-query I get the following error: </p> <p>Unhandled Execution Error Incorrect syntax near '&lt;'. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at TestAPI.UpdateTicketValues(String srId) in D:\Webs\Internal\veritythree.com\SupportBeta\TestAPI.ascx.vb:line 216 at TestAPI.Submit_Click(Object sender, EventArgs e) in D:\Webs\Internal\veritythree.com\SupportBeta\TestAPI.ascx.vb:line 170 at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) 0.517567748943243 0.511543 </p> <p>Here is my function: </p> <pre><code>Public Function UpdateTicketValues(ByVal srId As String) As Boolean Dim result As Boolean Dim myCDataReader As System.Data.SqlClient.SqlDataReader Dim myUConn As New System.Data.SqlClient.SqlConnection Dim myCCmd As New System.Data.SqlClient.SqlCommand Dim myUCmd As New System.Data.SqlClient.SqlCommand Dim strSQL As String strSQL = "SELECT Contact_RecId, First_Name, Last_Name, PhoneNbr, Extension, Email FROM vti_ContactInformation " &amp; _ "WHERE Company_RecId = " &amp; CoId &amp; " AND Email = '" &amp; txtEmail.Text &amp; "'" myCConn.Open() myUConn = New System.Data.SqlClient.SqlConnection("Data Source=x;Initial Catalog=x;User Id=x;Password=x;Trusted_Connection=False") myUConn.Open() myCCmd.Connection = myCConn myCCmd.CommandText = strSQL myCDataReader = myCCmd.ExecuteReader If myCDataReader.Read() Then 'Run update with contact information strSQL = "UPDATE SR_Service " &amp; _ "SET Contact_RecId = " &amp; myCDataReader.GetValue(0) &amp; ", " &amp; _ " Contact_Name = '" &amp; myCDataReader.GetValue(1) &amp; " " &amp; myCDataReader.GetValue(2) &amp; "', " &amp; _ " PhoneNbr = '" &amp; myCDataReader.GetValue(3) &amp; "', " &amp; _ " Extension = '" &amp; myCDataReader.GetValue(4) &amp; "', " &amp; _ " Email_Address = '" &amp; myCDataReader.GetValue(5) &amp; "' " &amp; _ "WHERE SR_Service_RecId = " &amp; srId &amp; " " myUCmd.Connection = myUConn myUCmd.CommandText = strSQL 'myCCmd.ExecuteNonQuery() lblServiceRequest.Text = myUCmd.CommandText result = True Else myUCmd.CommandText = "" result = False End If If myUCmd.CommandText &lt;&gt; "" Then myUCmd.ExecuteNonQuery() End If myCConn.Close() myUConn.Close() Return result End Function </code></pre> <p>Any help is appreciated!</p>
<p>before i even look where the error might be i suggest you stop immediatly what your doing and first go change all sql code to use parameters. if you don't your site will be open to sql injection attacks that can destroy your database.</p> <p>to find out where the problem is run profiler and check the stmt:starting and stmt:completed events.</p>
C++ Library for image recognition: images containing words to string <p>Does anyone know of a c++ library for taking an image and performing image recognition on it such that it can find letters based on a given font and/or font height? Even one that doesn't let you select a font would be nice (eg: readLetters(Image image).</p>
<p>I've been looking into this a lot lately. Your best is simply Tesseract. If you need layout analysis on top of the OCR than go with Ocropus (which in turn uses Tesseract to do the OCR). Layout analysis refers to being able to detect position of text on the image and do things like line segmentation, block segmentation, etc.</p> <p>I've found some really good tips through experimentation with Tesseract that are worth sharing. Basically I had to do a lot of preprocessing for the image.</p> <ol> <li>Upsize/Downsize your input image to 300 dpi.</li> <li>Remove color from the image. Grey scale is good. I actually used a dither threshold and made my input black and white.</li> <li>Cut out unnecessary junk from your image. For all three above I used netbpm (a set of image manipulation tools for unix) to get to point where I was getting pretty much 100 percent accuracy for what I needed.</li> </ol> <p>If you have a highly customized font and go with tesseract alone you have to "Train" the system -- basically you have to feed a bunch of training data. This is well documented on the tesseract-ocr site. You essentially create a new "language" for your font and pass it in with the -l parameter. </p> <p>The other training mechanism I found was with Ocropus using nueral net (bpnet) training. It requires a lot of input data to build a good statistical model.</p> <p>In terms of invoking Tesseract/Ocropus are both C++. It won't be as simple as ReadLines(Image) but there is an API you can check out. You can also invoke via command line.</p>
Most efficient way to convert BCD to binary <p>I have the code below to convert a 32 bit BCD value (supplied in two uint halves) to a uint binary value.</p> <p>The values supplied can be up to 0x9999, to form a maximum value of 0x99999999. </p> <p>Is there a better (ie. quicker) way to achieve this? </p> <pre><code> /// &lt;summary&gt; /// Convert two PLC words in BCD format (forming 8 digit number) into single binary integer. /// e.g. If Lower = 0x5678 and Upper = 0x1234, then Return is 12345678 decimal, or 0xbc614e. /// &lt;/summary&gt; /// &lt;param name="lower"&gt;Least significant 16 bits.&lt;/param&gt; /// &lt;param name="upper"&gt;Most significant 16 bits.&lt;/param&gt; /// &lt;returns&gt;32 bit unsigned integer.&lt;/returns&gt; /// &lt;remarks&gt;If the parameters supplied are invalid, returns zero.&lt;/remarks&gt; private static uint BCD2ToBin(uint lower, uint upper) { uint binVal = 0; if ((lower | upper) != 0) { int shift = 0; uint multiplier = 1; uint bcdVal = (upper &lt;&lt; 16) | lower; for (int i = 0; i &lt; 8; i++) { uint digit = (bcdVal &gt;&gt; shift) &amp; 0xf; if (digit &gt; 9) { binVal = 0; break; } else { binVal += digit * multiplier; shift += 4; multiplier *= 10; } } } return binVal; } </code></pre>
<p>If you've space to spare for a 39,322 element array, you could always just look the value up.</p>
How can I get and set the 'read-only' property of an edit box? <p>How can I get and set the 'read-only' property of an edit box?</p>
<p>The CEdit class has a SetReadOnly method which can be called at run-time. Details on MSDN: <a href="http://msdn.microsoft.com/en-gb/library/aa279328(VS.60).aspx">http://msdn.microsoft.com/en-gb/library/aa279328(VS.60).aspx</a></p>
Hide the uninstaller in Add/Remove Programs? <p>I am creating windows installer project using Visual Studio 2005.</p> <p>Is there an option make it so that my project does NOT have an uninstall option in Add/Remove programs?</p> <p>One of my customers has asked me to do this.. <strong>Here's Why</strong>: Because the installer is a patch to an existing program. After uninstalling, the program no longer works because the patched files get uninstalled. Instead of figuring out a way to restore the replaced files (which we haven't been able to do with this installer), we're wondering if it is possible to disable the uninstall.</p>
<p>You just need to set ARPSYSTEMCOMPONENT=1 in the Property table of the installer using <a href="http://www.microsoft.com/DownLoads/details.aspx?familyid=6A35AC14-2626-4846-BB51-DDCE49D6FFB6&amp;displaylang=en">Orca</a> (Can't be done directly in Visual Studio from what I know)</p> <p>This is commonly used when a program installs dependencies and you don't want the user to uninstall dependencies by hand, they need to use a specific uninstall script you've provided or something.</p> <p>Personally, I would author the patch as a patch and prevent the patch from being uninstalled. </p> <p>Also I suggest picking up a copy of <a href="http://rads.stackoverflow.com/amzn/click/1590592972">The Definitive Guide to Windows Installer</a> which will give you some explanation on how, why and where you should use tricks such as this. As well as giving you a really good understanding of the windows installer fundementals and help you to design a better installer in the long run. All the examples in the book use Visual Studio + free tools from the <a href="http://www.microsoft.com/DownLoads/details.aspx?familyid=6A35AC14-2626-4846-BB51-DDCE49D6FFB6&amp;displaylang=en">Windows Installer SDK.</a></p> <p><strong>Edit:</strong> The user still has full control to uninstall via MSIEXEC, via a custom uninstall shortcut that you provide, all this does is hide the entry in Add/Remove Programs (ARP)</p> <p><strong>Edit2:</strong> Sample VBS to add the property (if you want to do so as part of an automated build process)</p> <pre><code>Dim installer, database, view Set installer = CreateObject("WindowsInstaller.Installer") Set database = installer.OpenDatabase ("test.msi", 1) Set view = database.OpenView ("INSERT INTO Property(Property.Property, Property.Value) VALUES('ARPSYSTEMCOMPONENT', '1')") view.Execute Set database = Nothing Set installer = Nothing </code></pre>
ASP.NET MVC Release Date <p>Does anybody know if there is an official or estimated release date for the ASP.NET MVC framework? I'm starting on a project that I hope to have completed by mid March and it would be a perfect candidate for the platform, but I don't want to release it under a framework that isn't completed.</p>
<p>Originally it was supposed to RTW by the end of 2008. That was delayed without explanation. <a href="http://2009.visitmix.com/" rel="nofollow">Mix is March 18-20</a>. I would guess that's a pretty likely time for it to RTW. According to Phil Haack's twittering, a release candidate will be out soon.</p>
What is the best way to pass information from java to c++? <p>I have a java application I need to pass some info to a C++ program. It has been suggested that I use some simple socket programming to do this. Is this the best way? If not what are the alternatives? If so, how should I go about learning about socket programming? </p>
<p>You have a few options:</p> <ul> <li>Pass a file from Java to C++. This is probably simplest. It's easy to test and shouldn't require any 3rd party libraries on either end.</li> <li>Use sockets as mentioned. In C++, if you require a cross-platform solution a library such as <a href="http://www.cs.wustl.edu/~schmidt/ACE-overview.html">ACE</a> or <a href="http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio.html">boost</a> will save you some heartache</li> <li>Use <a href="http://en.wikipedia.org/wiki/Java_Native_Interface">JNI</a> to call from Java to C++ or vice versa. This is probably the most difficult, but most performant.</li> </ul> <p>For learning sockets, a Google search for <a href="http://java.sun.com/docs/books/tutorial/networking/sockets/">"java socket tutorial"</a> or <a href="http://www.google.com/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=uhO&amp;q=c%2B%2B+sockets+tutorial&amp;btnG=Search">"c++ socket tutorial"</a> will give you lots of information.</p>
How to rename the Node running a mnesia Database <p>I created a Mnesia database / Schema on machine1. The node was named mypl@machine1. I then moved all files to machine2, because machine1 broke down. Everything runs fine as long as the code is running with the name "mypl@machine1". Obviously this is somewhat confugsing, because it is now running on machine2.</p> <p>If I start Erlang with the node name "mypl@machine2" the Mnesia Database appears being empty.</p> <p>How do I rename the node in a Mnesia Database from machine1 to machine2?</p>
<p>I don't think this can be done online on a single node(anyone?), but it is possible to do via a backup/restore in addition to running two nodes and adding table copies. In the <a href="http://erlang.org/doc/apps/mnesia/part_frame.html">Mnesia User's guide</a> section 6.9.1 you'll find some code that uses mnesia:traverse_backup to alter the node names in the schema table (Shown below) in an mnesia backup file. The module name you should probably use is <code>mnesia_backup</code>.</p> <p>With this code you'll need to:</p> <pre><code>%% On mypl@machine1 mnesia:backup("/path/to/mnesia.backup"). change_node_name(mnesia_backup, mypl@machine1, mypl@machine2, "/path/to/mnesia.backup", "/path/to/new.mnesia.backup"). %% On mypl@machine2 mnesia:restore("/path/to/new.mnesia.backup", []). </code></pre> <p>I'm not sure if you need to create the schema first on <code>mypl@machine2</code>.</p> <p>The change node name code from the user's guide:</p> <pre><code>change_node_name(Mod, From, To, Source, Target) -&gt; Switch = fun(Node) when Node == From -&gt; To; (Node) when Node == To -&gt; throw({error, already_exists}); (Node) -&gt; Node end, Convert = fun({schema, db_nodes, Nodes}, Acc) -&gt; {[{schema, db_nodes, lists:map(Switch,Nodes)}], Acc}; ({schema, version, Version}, Acc) -&gt; {[{schema, version, Version}], Acc}; ({schema, cookie, Cookie}, Acc) -&gt; {[{schema, cookie, Cookie}], Acc}; ({schema, Tab, CreateList}, Acc) -&gt; Keys = [ram_copies, disc_copies, disc_only_copies], OptSwitch = fun({Key, Val}) -&gt; case lists:member(Key, Keys) of true -&gt; {Key, lists:map(Switch, Val)}; false-&gt; {Key, Val} end end, {[{schema, Tab, lists:map(OptSwitch, CreateList)}], Acc}; (Other, Acc) -&gt; {[Other], Acc} end, mnesia:traverse_backup(Source, Mod, Target, Mod, Convert, switched). </code></pre>