input
stringlengths
51
42.3k
output
stringlengths
18
55k
Should Locks and Mutexes in C# be used together <p>Wouldn't this be overkill and only one of these necessary? I've searched and found different posts about Mutual Exclusion and locks in C# <a href="http://stackoverflow.com/questions/301160/what-are-the-differences-between-various-threading-synchronization-options-in-c">here</a> and <a href="http://stackoverflow.com/questions/59590/lock-keyword-in-c">here</a>.<br /><br /> Example:<br/> In our app, we have a function that spins off multiple reconnection threads and inside this thread we use a <code>Mutex</code> and a <code>lock</code>. Wouldn't <code>lock</code> block access to this section of code and prevent <code>connect</code> from being updated by any other thread?</p> <pre><code>bool connect = false; Mutex reconnectMutex = new Mutex(false, "Reconnect_" + key); try { lock(site) { if(site.ContainsKey(key)) { siteInfo = (SiteInfo)site[key]; if(reconnectMutex.WaitOne(100, true)) { connect = true; } } } if (connect) { // Process thread logic } } catch {} reconnectMutex.ReleaseMutex(); </code></pre> <p>More Info:<br/> This is in an ASP.NET WebService not running in a Web Garden.</p>
<p>That Mutex (because it has a name) will stop any process on the same machine accessing it as well, whereas lock will only stop other threads in the same process. I can't see from that code sample why you'd need both kinds of lock. It seems good practice to hold the simple lock for a short period of time - but then the much heavier interprocess mutex is locked for a probably longer (though overlapping) period! Would be simpler to just use the mutex. And perhaps to find out whether an interprocess lock is really necessary.</p> <p>By the way, <code>catch {}</code> is absolutely the wrong thing to use in that scenario. You should use <code>finally { /* release mutex */ }</code>. They are very different. The catch will swallow far more kinds of exception than it should, and will also cause nested finally handlers to execute in response to low-level exceptions such as memory corruption, access violation, etc. So instead of:</p> <pre><code>try { // something } catch {} // cleanup </code></pre> <p>You should have:</p> <pre><code>try { // something } finally { // cleanup } </code></pre> <p>And if there are specific exceptions you can recover from, you could catch them:</p> <pre><code>try { // something } catch (DatabaseConfigurationError x) { // tell the user to configure the database properly } finally { // cleanup } </code></pre>
Invalid scale size. Cannot be less than zero <p>I am using spring-2.5.6 to connect from a standalone application to an Oracle 10g database (ojdbc14.jar) using the org.apache.commons.dbcp.BasicDataSource. When I try to retrieve a SqlRowSet using the <code>public SqlRowSet queryForRowSet(String sql, Object[] args) throws DataAccessException</code> method I am getting an 'java.sql.SQLException: Invalid scale size. Cannot be less than zero'.</p> <p>The sql calling the table is:</p> <pre><code>select CUSTAREADESC, BEGCOL, COLLENGTH from CUSTOMERAREA where upper(trim(FLEET)) = upper(trim(?)) and CUSTAREANO = ? </code></pre> <p>The columns BEGCOL and COLLENGTH are of the data type number with no precision defined.</p> <p>I found some information on this issue, seems to be an incompatibility between the Oracle drivers and Sun's implementation of the com.sun.rowset.CachedRowSetImpl.</p> <p><a href="http://forums.sun.com/thread.jspa?threadID=569712" rel="nofollow">Java Database Connectivity (JDBC) - Populating CachedRowSet produces SQLException: Invalid scale size</a></p> <p><a href="http://forum.springframework.org/showthread.php?t=19848" rel="nofollow">Using queryForRowSet with subquery factoring SQL gives errors </a></p> <p>They suggest changing the sql to the following as a work around. </p> <pre><code>select CUSTAREADESC, (BEGCOL + 0) BEGCOL, (COLLENGTH + 0) COLLENGTH from CUSTOMERAREA where upper(trim(FLEET)) = upper(trim(?)) and CUSTAREANO = ? </code></pre> <p>Does anyone know of a better generic solution that doesn't involve custom sql for any existing table where a column doesn't have precision defined?</p>
<p>This error is caused by an incompatibility in the Oracle JDBC drivers. You can fix it by setting the system property oracle.jdbc.J2EE13Compliant to true. For example, on the commandline:</p> <p><code>java -Doracle.jdbc.J2EE13Compliant=true</code></p>
Erroneous Data Retrieved From ListView <p>I am having some trouble with my program logic that loops through a collection of data that exists in two separate ListViews. After looping though and extracting the data from the ListView, I then add everything into a comma delimited text file (<strong>CLOSEULDCONFIG.TXT</strong>). </p> <p>The first time that I execute this logic, everything works as it should. If I execute this logic again, I get 2 copies of that which is in the ListView. Each time I run through this logic, number of copies of the previously added ListView items is increased by 1. </p> <p>This is undesirable as I would like to add the same number of elements as that which I have in my ListView to my text file. Can anyone spot what is wrong with my nested foreach statements that is causing this? </p> <pre><code> // HAZMAT PACKAGE ERROR LISTVIEW ITEMS foreach (ListViewItem HazPackErrItems in HazmatPackageErrorListview.Items) { bool first = true; foreach (ListViewItem.ListViewSubItem HazPackErrSub in HazPackErrItems.SubItems) { // removes the first element of each comma delimited string if (first) first = false; else CloseULDSubmitLogDataResponseHazpackerrCloseULDConfig += " " + HazPackErrSub.Text + ","; } } // HAZMAT WEIGHT AND COUNT COLLECTED LISTVIEW ITEMS foreach (ListViewItem HazWeightAndCountItems in HazmatWeightAndCountListview.Items) { bool first = true; foreach (ListViewItem.ListViewSubItem HazWeightAndCountSub in HazWeightAndCountItems.SubItems) { // removes the first element of each comma delimited string if (first) first = false; else CloseULDSubmitLogDataResponseHazWeightAndCountCloseULDConfig += " " + HazWeightAndCountSub.Text + ","; } } using (System.IO.StreamWriter sw = new System.IO.StreamWriter("CLOSEULDCONFIG.TXT", true)) { if (!AlreadyExists) { sw.WriteLine(PresetNameConfig + CloseULDSubmitLogDataRequestCloseULDConfig + CloseULDSubmitLogDataResponseCloseULDConfig + CloseULDSubmitLogDataResponseHazpackerrCloseULDConfig + CloseULDSubmitLogDataResponseHazWeightAndCountCloseULDConfig + CloseULDDateTimeConfig); } } </code></pre>
<p>If I'm not mistaken, you are opening the file to append, instead of overwrite. Have you checked the file itself to see if the data is being duplicated there?</p>
Freeze TH header and scrolling data <p>I have a html table and I want to freeze the header row th tag for scrolling the data. How I can do that? Does I need to use the Dom? Thanks !!</p>
<p>My solution is to use two tables and fix the column widths. The lower table is in a scrollable div and has no header.</p>
Is there a bug in "tf add /recursive"? <p>I'm trying to add the following folder tree to TFS:</p> <pre><code>C:\TFS\folder1 C:\TFS\folder1\folder2 C:\TFS\folder1\folder2\folder3 C:\TFS\folder1\folder2\folder3\test.txt </code></pre> <p>In the above example the folder "C:\TFS" is a mapped TFS working folder. I issue the following commands from the console:</p> <pre><code>cd C:\TFS tf add folder1 /recursive </code></pre> <p>After this command has finished my repository contains the following tree (as pending changes):</p> <pre><code>$/folder1 $/folder1/folder2 </code></pre> <p>As you can see "folder3" and the text file "test.txt" below are completely missing! Why?</p> <p><strong>Update:</strong> I've submitted this as a bug to Microsoft:</p> <p><a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=423279" rel="nofollow">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=423279</a></p>
<p>worked for me.</p> <pre><code>c:\Temp&gt;md Test\1\2\3\4\5 c:\Temp&gt;dir test /s/b c:\Temp\test\1 c:\Temp\test\1\2 c:\Temp\test\1\2\3 c:\Temp\test\1\2\3\4 c:\Temp\test\1\2\3\4\5 c:\Temp&gt;cd test c:\Temp\Test&gt;tf add 1 /recursive 1 1: 2 1\2: 3 1\2\3: 4 1\2\3\4: 5 c:\Temp\Test&gt; </code></pre> <p>In Tfs <img src="http://s5.tinypic.com/izbwc1.jpg" alt="TFS Tree View" /></p> <p>Same if I do it from Test or above Test directory</p>
Getting Number of Displayed Lines in Multi-Line Textbox in the Compact Framework <p>I have a multi-line textbox that typically displays very long strings (license agreements, for example), and a requirement around the display is that if the user "pages" through the text via the vertical scrollbar (not clicking the arrows or the scroll box, but clicking above or below the scrollbox), on the last "page" the first line must be the last line from the previous page, and the text is padded with blanks lines to accommodate this. </p> <p>I know I can get the size of the string, and the number of lines in the textbox, but is it possible to retrieve the number of lines <em>displayed</em> in the textbox at one time so I can calculate how much the text will need to be padded? Looking at the list of <a href="http://www.developerfusion.com/article/46/sending-messages/3/" rel="nofollow">messages</a> I can send via P/Invoke, I don't see one to request the number of displayed lines.</p>
<p>You could get the maximum number of lines displayed at one time by calculating the font height and devide the textbox height by that.</p> <p>Just an idea... Not sure if it will come out correct, but you could do some tests and see if it matches.</p> <p>To get the font Height:</p> <p><a href="http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx" rel="nofollow">public SizeF MeasureString( string text, Font font ) </a></p>
How to avoid duplicate logic with Mocks <p>I have the following challenge, and I haven't found a good answer. I am using a Mocking framework (JMock in this case) to allow unit tests to be isolated from database code. I'm mocking the access to the classes that involve the database logic, and seperately testing the database classes using DBUnit.</p> <p>The problem I'm having is that I'm noticing a pattern where the logic is conceptually duplicated in multiple places. For example I need to detect that a value in the database doesn't exist, so I might return null from a method in that case. So I have a database access class which does the database interaction, and returns null appropriately. Then I have the business logic class which receives null from the mock and then is tested to act appropriately if the value is null.</p> <p>Now what if in the future that behavior needs to change and returning null is no longer appropriate, say because the state has grown more complicated, so I'll need to return an object that reports the value doesn't exist and some additional fact from the database.</p> <p>Now, if I change the behavior of the database class to no longer return null in that case, the business logic class would still appear to function, and the bug would only be caught in QA, unless someone remembered the coupling, or properly followed the usages of the method.</p> <p>I fell like I'm missing something, and there has to be a better way to avoid this conceptual duplication, or at least have it under test so that if it changes, the fact that the change is not propagated fails a unit test.</p> <p>Any suggestions?</p> <p>UPDATE:</p> <p>Let me try to clarify my question. I'm thinking of when code evolves over time, how to ensure that the integration doesn't break between the classes tested via the mock and actual implementation of the classed that the mock represents.</p> <p>For example, I just had a case where I had a method that was originally created and didn't expect null values, so this was not a test on the real object. Then the user of the class (tested via a mock) was enhanced to pass in a null as a parameter under certain circumstances. On integration that broke, because the real class wasn't tested for null. Now when building these classes at first this is not a big deal, because you are testing both ends as you build, but if the design needs to evolve two months later when you tend to forget about the details, how would you test the interaction between these two sets of objects (the one tested via a mock vs the actual implementation)?</p> <p>The underlying problem seems to be one of duplication (that is violating the DRY principle), the expectations are really kept in two places, although the relationship is conceptual, there is no actual duplicate code.</p> <p>[Edit after Aaron Digulla's second edit on his answer]:</p> <p>Right, that is exactly the kind of thing I am doing (except that there is some further interaction with the DB in a class that is tested via DBUnit and interacts with the database during its tests, but it is the same idea). So now, say we need to modify the database behavior so that the results are different. The test using the mock will continue to pass unless 1) someone remembers or 2) it breaks in integration. So the stored procedure return values (say) of the database are essentially duplicated in the test data of the mock. Now what bothers me about the duplication is that the logic is duplicated, and it is a subtle violation of DRY. It could be that that is just the way it is (there is a reason for integration tests after all), but I was feeling that instead I'm missing something.</p> <p>[Edit on starting the bounty]</p> <p>Reading the interact with Aaron gets to the point of the question, but what I'm really looking for is some insight into how to avoid or manage the apparent duplication, so that a change in the behavior of the real class will show up in the unit tests that interact with the mock as something that broke. Obviously that doesn't happen automatically, but there may be a way to design the scenario correctly.</p> <p>[Edit on awarding the bounty]</p> <p>Thanks to everyone who spent the time answering the question. The winner taught me something new about how to think about passing the data between the two layers, and got to the answer first.</p>
<p>You are fundamentally asking for the impossible. You are asking for your unit tests to predict and notify you when you change the external resource's behaviour. Without writing a test to produce the new behaviour, how can they know?</p> <p>What you are describing is adding a brand new state that must be tested for - instead of a null result, now there is some object coming out of the database. How could your test suite possibly know what the intended behaviour of the object under test should be for some new, random object? You need to write a new test.</p> <p>The mock is not "misbehaving", as you commented. The mock is doing exactly what you set it up to do. The fact that the specification changed is of no consequence to the mock. The only problem in this scenario is that the person who implemented the change forgot to update the unit tests. I'm actually not too sure why you think there is any duplication of concerns going on.</p> <p>The coder that is adding some new return result to the system is responsible for adding a unit test to handle this case. If that code is also 100% sure that there <em>is no way</em> that the null result could possibly be returned now, then he could also delete the old unit test. But why would you? The unit test correctly describes the behavior of the object under test when it receives a null result. What happens if you change the backend of your system to some new database that does return a null? What if the specification changed back to returning null? You might as well keep the test, since as far as your object is concerned, it could really get anything back from the external resource, and it should gracefully handle every possible case.</p> <p>The whole purpose of mocking is to decouple your tests from real resources. It's not going to automatically save you from introducing bugs into the system. If your unit test accurately describes the behavior when it receives a null, great! But this test should not have any knowledge of any other state, and certainly should not be somehow informed that the external resource will no longer be sending nulls. </p> <p>If you're doing proper, loosely coupled design, your system could have any backend you could imagine. You shouldn't be writing tests with one single external resource in mind. It sounds like you might be happier if you added some integration tests that use your real database, thereby eliminating the mocking layer. This is always a great idea for use with doing a build or sanity/smoke tests, but is usually obstructive for day to day development.</p>
Override default styling in WPF TextBox, based on PresentationFramework.Aero <p>I want to use the Aero textbox styling, but still override some properties. I try to accomplish this by:</p> <pre><code>&lt;ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="/PresentationFramework.Aero, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}"&gt; &lt;Setter Property="Margin" Value="2" /&gt; &lt;Setter Property="Padding" Value="2" /&gt; &lt;/Style&gt; &lt;/ResourceDictionary&gt; </code></pre> <p>However, this results in a <code>StackOverflowException</code> when starting my app. When I remove the reference to PresentationFramework.Aero, this works but I get the default OS styling, which makes the app ugly. ;) </p> <p>So, in effect: if I want to override some style on all my textboxes I cannot get the Aero look. If I want the Aero look, I cannot override any styling. Deadlock.</p> <p>Any way to solve this?</p>
<p>It seems to work if you put the <code>Style</code> as a lower-level resource, instead of in the same ResourceDictionary:</p> <pre><code>&lt;Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Grid.Resources&gt; &lt;ResourceDictionary&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="/PresentationFramework.Aero, Version=3.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml"/&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;/ResourceDictionary&gt; &lt;/Grid.Resources&gt; &lt;Border BorderBrush="Blue" BorderThickness="3"&gt; &lt;Border.Resources&gt; &lt;Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}"&gt; &lt;Setter Property="Margin" Value="2" /&gt; &lt;Setter Property="Padding" Value="2" /&gt; &lt;/Style&gt; &lt;/Border.Resources&gt; &lt;TextBox /&gt; &lt;/Border&gt; &lt;/Grid&gt; </code></pre>
How can I clear memcache using capistrano? <p>I use capistrano to deploy my app to a machine that uses memcache. I want capistrano to clear memcache when it deploys a new version of the site. </p>
<p><a href="http://github.com/engineyard/eycap/blob/35c69f12aa78b5ee6f99bd9c1b22980698076b1f/lib/eycap/recipes/memcached.rb">Something like that?</a></p>
Suggestions for Data Access Interface Name <p>I am looking for suggestions for an interface name.</p> <p>The interface is for the primitive CRUD methods that will be defined later in the DAL, however I need to use it in a lower-level API. The interface itself will just have the four members, Create(), Read(), Update(), and Delete().</p> <p>I am currently thinking something along the lines of IDataAccessPrimatives, but am very ambivalant on that name. What do you gals/guys suggest?</p> <p>Thanks.</p>
<p>How about ICantBelieveItsNotButter ?</p> <p>Or, ICanReadUpsideDown?</p> <p>Or, (more seriously), <strong>IPersistData</strong></p>
HTML/IE: stretch image to fit, preserve aspect ratio <p>In an HTML window, I am setting a custom body </p> <pre><code>&lt;img src="file://[filename]"&gt; </code></pre> <p>to display an image.</p> <p>Now I want to strectch the image to fit the available window, but preserve aspect ratio. </p> <pre><code>&lt;img src="file://[filename]" width="100%" height="100"&gt; </code></pre> <p>stretches but also distorts the image.</p> <p>Is there some HTML trickery to do that? IE only solution is fine, since this is in a hosted broweser control.</p>
<p>If you want to preserve aspect ratio, you only need to specify one dimension ie:</p> <pre><code>&lt;img src="file://[filename]" width="100%" alt="" /&gt; </code></pre> <p>You can use javascript to determine max dimension and resize accordingly</p> <pre><code>&lt;script type="text/javascript"&gt; function getImgSize(id){ var pic = document.getElementById(id); var h = pic.offsetHeight; var w = pic.offsetWidth; alert ('The image size is '+w+'*'+h); } &lt;/script&gt; </code></pre>
How do I access the .NET TimeZoneInfo class from SQL Server 2005? <p>The TimeZoneInfo class has a Host Protection Attribute of MayLeakOnAbort.</p> <p>This seems to prevent me accessing it from the SQL Server CLR. But is there a workaround?</p>
<p>Yeah sure. You encapsulate it in another .NET class and then reference from your .NET assembly in SQL Server. Then you complete disable the security in your SQL Server database so you can run the second class.</p> <p>If that does not work, you can create a COM wrapper and then an Interop wrapper and still destroy security in SQL Server to run the thing.</p> <p>Now, if security actually matters to you, you can create a WCF service that wraps the bits you need and use it as a service from your SQL code. It is a bit of latency and cannot work against objects in SQL Server, per se, but it is cleaner.</p> <p>Sorry for the snarky sounding answer, but I am in a strange mood right now. :-)</p>
Maximum MIMEType Length when storing type in DB <p>What are people using as the length of a MIMEType field in their databases? The longest one we've seen so far is 72 bytes:</p> <pre><code>application/vnd.openxmlformats-officedocument.wordprocessingml.document </code></pre> <p>but I'm just waiting for a longer one. We're using 250 now, but has anyone seen a longer MIMEType than that?</p> <p>Edit: From the accepted answer, 127 for type and sub-type each, so that's 254 max, plus the '/' is a limit of 255 for the combined value.</p>
<p>According to RFC 4288 "Media Type Specifications and Registration Procedures", type (eg. "application") and subtype (eg "vnd...") both <a href="http://tools.ietf.org/html/rfc4288#section-4.2">can be max 127 characters</a>. you do the math :)</p> <p><strong>Edit:</strong> meanwhile, that document has been obsoleted by <a href="http://tools.ietf.org/html/rfc6838#section-4.2">RFC 6838</a>, which does not alter the maximum size but adds a remark:</p> <blockquote> <p>Also note that while this syntax allows names of up to 127 characters, implementation limits may make such long names problematic. For this reason, <code>&lt;type-name&gt;</code> and <code>&lt;subtype-name&gt;</code> SHOULD<br> be limited to 64 characters.</p> </blockquote>
"Cached Item Was Locked" causing Select Statement in Hibernate <p>I am having trouble with getting some caching to work with hibernate exactly the way I would like. I created some example code to replicate this problem I am having. </p> <p>I have one object that contains instances of itself. For instance, a Part that is made up of more Parts. </p> <p>I really need to minimize the select statements that Hibernate is using when an updated object comes in. After going through the logs, I see this log output that is causing a SELECT statement:</p> <p><strong>Cached item was locked: com.cache.dataobject.Part.parts#1</strong></p> <p>What can I change in my annotation mappings, xml files, caching provider, or logic to keep the cached item from being locked? I would really like to get rid of that select statement.</p> <p>I included the Entity, DataObject, code I am testing with, and log output. </p> <p><strong>Hibernate version:</strong> 3.4</p> <p><strong>EHCache Version:</strong> 1.2.3 (Included with Hibernate Download)</p> <p><strong>Part DataObject:</strong></p> <pre><code>package com.cache.dataobject; import java.io.Serializable; import java.lang.String; import java.util.List; import javax.persistence.*; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import static javax.persistence.CascadeType.ALL; /** * Entity implementation class for Entity: Part * */ @Entity @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Part implements Serializable { private int id; private String name; private static final long serialVersionUID = 1L; private Part mainPart; private List&lt;Part&gt; parts; public Part() { super(); } @Id public int getId() { return this.id; } public void setId(int id) { this.id = id; } @Column(name = "PART_NAME") public String getName() { return this.name; } public void setName(String name) { this.name = name; } @ManyToOne(cascade = ALL) public Part getMainPart() { return mainPart; } public void setMainPart(Part mainPart) { this.mainPart = mainPart; } @OneToMany(cascade = ALL) @JoinColumn(name = "mainPart_id", referencedColumnName = "id") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public List&lt;Part&gt; getParts() { return parts; } public void setParts(List&lt;Part&gt; parts) { this.parts = parts; } } </code></pre> <p><strong>CacheDao:</strong></p> <pre><code>package com.cache.dao; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import com.cache.dataobject.Part; /** * Session Bean implementation class CacheDao */ @Stateless(mappedName = "ejb/CacheDao") public class CacheDao implements CacheDaoRemote { @PersistenceContext(unitName="CacheProjectUnit") EntityManager em; /** * Default constructor. */ public CacheDao() { // TODO Auto-generated constructor stub } public Part addPart(Part part){ System.out.println("CALLED PERSIST"); em.persist(part); return part; } public Part updatePart(Part part){ System.out.println("CALLED MERGE"); em.merge(part); return part; } } </code></pre> <p><strong>Test Client Code:</strong></p> <pre><code>package com.cache.dao; import java.util.ArrayList; import java.util.List; import javax.naming.InitialContext; import javax.naming.NamingException; import com.cache.dao.CacheDaoRemote; import com.cache.dataobject.Part; public class test { /** * @param args */ public static void main(String[] args) { InitialContext ctx; try { ctx = new InitialContext(); CacheDaoRemote dao = (CacheDaoRemote) ctx.lookup("ejb/CacheDao"); Part computer = new Part(); computer.setId(1); computer.setName("Computer"); List&lt;Part&gt; parts = new ArrayList&lt;Part&gt;(); Part cpu = new Part(); cpu.setId(2); cpu.setName("CPU"); Part monitor = new Part(); monitor.setId(3); monitor.setName("Monitor"); parts.add(cpu); parts.add(monitor); computer.setParts(parts); dao.addPart(computer); computer.setName("DellComputer"); dao.updatePart(computer); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </code></pre> <p><strong>Persistence.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"&gt; &lt;persistence-unit name="CacheProjectUnit"&gt; &lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt; &lt;!-- JNDI name of the database resource to use --&gt; &lt;jta-data-source&gt;jdbc/H2Pool&lt;/jta-data-source&gt; &lt;properties&gt; &lt;!-- The database dialect to use --&gt; &lt;property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" /&gt; &lt;!-- drop and create tables at deployment --&gt; &lt;property name="hibernate.hbm2ddl.auto" value="create-drop" /&gt; &lt;property name="hibernate.max_fetch_depth" value="3" /&gt; &lt;property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider" /&gt; &lt;/properties&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </code></pre> <p><strong>EhCache.xml</strong></p> <pre><code>&lt;ehcache&gt; &lt;diskStore path="java.io.tmpdir"/&gt; &lt;defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /&gt; &lt;cache name = "com.cache.dataobject.Part" maxElementsInMemory="100000" eternal="true" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="0" /&gt; &lt;cache name = "com.cache.dataobject.Part.parts" maxElementsInMemory="100000" eternal="true" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="0" /&gt; &lt;/ehcache&gt; </code></pre> <p><strong>Output Log:</strong></p> <pre><code>INFO: CALLED PERSIST FINEST: Cache lookup: com.cache.dataobject.Part#1 FINE: key: com.cache.dataobject.Part#1 FINE: Element for com.cache.dataobject.Part#1 is null FINEST: Cache miss: com.cache.dataobject.Part#1 FINEST: Cache lookup: com.cache.dataobject.Part#2 FINE: key: com.cache.dataobject.Part#2 FINE: Element for com.cache.dataobject.Part#2 is null FINEST: Cache miss: com.cache.dataobject.Part#2 FINEST: Cache lookup: com.cache.dataobject.Part#3 FINE: key: com.cache.dataobject.Part#3 FINE: Element for com.cache.dataobject.Part#3 is null FINEST: Cache miss: com.cache.dataobject.Part#3 FINEST: Invalidating: com.cache.dataobject.Part.parts#1 FINE: key: com.cache.dataobject.Part.parts#1 FINE: Element for com.cache.dataobject.Part.parts#1 is null FINE: insert into Part (mainPart_id, PART_NAME, id) values (?, ?, ?) FINE: insert into Part (mainPart_id, PART_NAME, id) values (?, ?, ?) FINE: insert into Part (mainPart_id, PART_NAME, id) values (?, ?, ?) FINE: update Part set mainPart_id=? where id=? FINE: update Part set mainPart_id=? where id=? FINEST: Inserting: com.cache.dataobject.Part#1 FINE: key: com.cache.dataobject.Part#1 FINE: Element for com.cache.dataobject.Part#1 is null FINEST: Inserted: com.cache.dataobject.Part#1 FINEST: Inserting: com.cache.dataobject.Part#2 FINE: key: com.cache.dataobject.Part#2 FINE: Element for com.cache.dataobject.Part#2 is null FINEST: Inserted: com.cache.dataobject.Part#2 FINEST: Inserting: com.cache.dataobject.Part#3 FINE: key: com.cache.dataobject.Part#3 FINE: Element for com.cache.dataobject.Part#3 is null FINEST: Inserted: com.cache.dataobject.Part#3 FINEST: Releasing: com.cache.dataobject.Part.parts#1 FINE: key: com.cache.dataobject.Part.parts#1 INFO: CALLED MERGE FINEST: Cache lookup: com.cache.dataobject.Part#1 FINE: key: com.cache.dataobject.Part#1 FINEST: Cache hit: com.cache.dataobject.Part#1 FINEST: Cache lookup: com.cache.dataobject.Part#1 FINE: key: com.cache.dataobject.Part#1 FINEST: Cache hit: com.cache.dataobject.Part#1 FINEST: Cache lookup: com.cache.dataobject.Part#2 FINE: key: com.cache.dataobject.Part#2 FINEST: Cache hit: com.cache.dataobject.Part#2 FINEST: Cache lookup: com.cache.dataobject.Part#2 FINE: key: com.cache.dataobject.Part#2 FINEST: Cache hit: com.cache.dataobject.Part#2 FINEST: Cache lookup: com.cache.dataobject.Part#3 FINE: key: com.cache.dataobject.Part#3 FINEST: Cache hit: com.cache.dataobject.Part#3 FINEST: Cache lookup: com.cache.dataobject.Part#3 FINE: key: com.cache.dataobject.Part#3 FINEST: Cache hit: com.cache.dataobject.Part#3 FINEST: Cache lookup: com.cache.dataobject.Part.parts#1 FINE: key: com.cache.dataobject.Part.parts#1 FINEST: Cached item was locked: com.cache.dataobject.Part.parts#1 FINE: select parts0_.mainPart_id as mainPart3_1_, parts0_.id as id1_, parts0_.id as id18_0_, parts0_.mainPart_id as mainPart3_18_0_, parts0_.PART_NAME as PART2_18_0_ from Part parts0_ where parts0_.mainPart_id=? FINEST: Caching: com.cache.dataobject.Part.parts#1 FINE: key: com.cache.dataobject.Part.parts#1 FINEST: Cached: com.cache.dataobject.Part.parts#1 FINEST: Invalidating: com.cache.dataobject.Part.parts#2 FINE: key: com.cache.dataobject.Part.parts#2 FINE: Element for com.cache.dataobject.Part.parts#2 is null FINEST: Invalidating: com.cache.dataobject.Part.parts#3 FINE: key: com.cache.dataobject.Part.parts#3 FINE: Element for com.cache.dataobject.Part.parts#3 is null FINEST: Invalidating: com.cache.dataobject.Part.parts#1 FINE: key: com.cache.dataobject.Part.parts#1 FINEST: Invalidating: com.cache.dataobject.Part#1 FINE: key: com.cache.dataobject.Part#1 FINE: update Part set mainPart_id=?, PART_NAME=? where id=? FINE: update Part set mainPart_id=null where mainPart_id=? FINE: update Part set mainPart_id=null where mainPart_id=? FINEST: Updating: com.cache.dataobject.Part#1 FINE: key: com.cache.dataobject.Part#1 FINEST: Updated: com.cache.dataobject.Part#1 FINEST: Releasing: com.cache.dataobject.Part.parts#2 FINE: key: com.cache.dataobject.Part.parts#2 FINEST: Releasing: com.cache.dataobject.Part.parts#3 FINE: key: com.cache.dataobject.Part.parts#3 FINEST: Releasing: com.cache.dataobject.Part.parts#1 FINE: key: com.cache.dataobject.Part.parts#1 </code></pre>
<p>You've probably seen this already, but there is an open Hibernate bug that seems to relate to your problem - <a href="http://opensource.atlassian.com/projects/hibernate/browse/HHH-1813" rel="nofollow">"2nd level cached collections are locked causing a cache miss".</a>.</p> <p>From that bug, the fix may be to use a new session for your add/update calls. You can get an EntityManagerFactory rather than EntityManager and request a new Entity Manager for each call. Obviously it depends on the wider context of your code as to how appropriate this is.</p>
Is there some kind of memory limit for an executable (written in C) to run without problems? <p>i´m doing a project using C, and CodeBlocks is my IDE. Windows Vista is the OS. I added some new stuff to the already working code and now the executable crashes everytime. i have no errors after compiling though. Computers and programming is not my field, but i suspect it may have something to do with some kind of memory limitations (if that exists and even makes sense). i say this because i´m working with three different 3D matrices/arrays of dimensions:</p> <ul> <li>1500x5x2 </li> <li>1500x5x12 </li> <li>1500x5x200</li> </ul> <p>I then had another two 1D arrays both of dimension 1500. this was all working fine.</p> <p>it started crashing when i added another three 2D matrices/arrays all of dimension 1500x5. if i comment some of the existing matrices, the new ones work fine, but only one at a time.</p> <p>(btw, all the above referred matrices are of the INT type and were defined with pointers and callocs)</p> <p>Any suggestions?</p>
<p>There are limitations with platforms, etc, but your 3 3D matrices only use a few MB of RAM (just over 6), so I doubt that you're hitting the limits given those.</p> <p>If it just started crashing when you added other matrices, I'd be more suspicious that you're having memory allocation/access errors on the pointers defining the new matrix code you added.</p> <p>How are you defining your matrices? </p> <p>---- EDIT ----</p> <p>You should try to <a href="http://wiki.codeblocks.org/index.php?title=Debugging%5Fwith%5FCode::Blocks" rel="nofollow">debug in CodeBlocks</a>. This should tell you exactly where your crash is occurring.</p>
Extension of question many to many relationships in same table <p>I got a single table and it contain 4 fields</p> <pre> Id|Hospital| Doctor|patient 1 A D1 P11 2 B D6 P61 3 A D2 P21 4 A D1 P12 5 B D7 P71 6 B D6 P62 7 B D6 P63</pre> <p>Doctors are unique to the Hospital. They don't work in other hospitals. Patients are unique to the doctor they don't visit any other doctor. Each hospital is having multiple Doctors.</p> <p>If you observe there are multiple patients for each doctor.</p> <p>Now the question is: How can I get "only one patient" related to the each doctor. It can be any patient from the record. </p> <p>I am looking forward to see some thing like this</p> <pre> Hospital Doctor Patient A D1 P11 A D2 P21 B D6 P61 B D7 P71</pre> <p>I got the answer like select Hospital,doctor, max(patient) from table GROUP BY Hospital,Doctor ORDER BY Hospital,Doctor;</p> <p>How to get the id also which is unique from the above table like.</p> <pre> id Hospital Doctor Patient 1 A D1 P11 3 A D2 P21 2 B D6 P61 5 B D7 P71</pre> <p>I am very sorry to repost this question.</p>
<p>Try something like:</p> <pre><code>select Id,Hospital,Doctor,Patient from table where Id in (select max(t.Id) from table t group by t.Hospital,t.Doctor) order by Hospital,Doctor; </code></pre>
Help me optimize this selector? $('#data div.item:has(div.video_guid:empty)') <p>It's currently not so slow as to make the site unusable, but in mobile safari on the iphone there is a noticeable lag. Is there a simpler way to do this?</p> <p>"Find div.items that have an empty div.video_guid"</p>
<p>Are there div's with a class video_guid anywhere else on the page? If not, you could simplify it to:</p> <pre><code>$('div.video_guid:empty'); </code></pre> <p>The only difference between your selector and mine is that yours would match the parent <code>div.item</code> while mine would match the actual <code>div.video_guid</code>. To get around this, once my selector matches, if you want to perform operations to the parent <code>div.item</code> you could just do:</p> <pre><code>$('div.video_guid:empty').each(function() { var container = $(this).parents('div.item'); // do something to the containing div }); </code></pre> <p>All things considered, I would expect that to perform better..</p>
CommandType.Text vs CommandType.StoredProcedure <p>Is there any benefit to explicitly using the StoredProcedure CommandType as opposed to just using a Text Command? In other words, is</p> <pre><code>cmd = new SqlCommand("EXEC StoredProc(@p1, @p2)"); cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@p1", 1); cmd.Parameters.Add("@p2", 2); </code></pre> <p>any worse than</p> <pre><code>cmd = new SqlCommand("StoredProc"); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@p1", 1); cmd.Parameters.Add("@p2", 2); </code></pre> <p>EDIT: Fixed bad copy paste job (again). Also, the whole point of the question is for a data access class. I'd much rather be able to pass the stored proc name and parameters in one line as opposed to extra lines for each parameter.</p>
<p>One difference is how message pumping happens. </p> <p>Where I used to work we had a number of batch processes that ran over night. Many of them simply involved running a stored procedure. We used to schedule these using sql server jobs, but moved away from it to instead call the procedures from a .Net program. This allowed us to keep <em>all</em> our scheduled tasks in one place, even the ones that had nothing to do with Sql Server. </p> <p>It also allowed us to build better logging functionality into the .Net program that calls the procedures, so that the logging from all of the overnight processes was consistent. The stored procedures would use the sql <code>print</code> and <code>raiserror</code> functions, and the .Net program will receive and log those. What we learned was that <code>CommandType.StoredProcedure</code> would <em>always</em> buffer these messages into batches of about 50. The .Net code wouldn't see any log events until the procedure finished or flushed the buffer, no matter what options you set on the connection or what you did in your sql. <code>CommandType.Text</code> fixed this for us.</p> <p>As a side issue, I'd use explicit types with your query parameters. Letting .Net try to infer your parameter types can cause issues in some situations.</p>
Using "like" in a cursor/query with a parameter in python (django) <p>I know this may be something stupid but I decided to ask any way.</p> <p>I've been trying to query something like:</p> <pre><code> cursor.execute("select col1, col2 \ from my_tablem \ where afield like '%%s%' and secondfield = %s order by 1 desc " % (var1, var2) ) </code></pre> <p>But I get an error in the like sentence. It doesn't like the extra % which I need to get all the results that contains the first %s value.</p> <p>Ideas?</p> <p>TIA! </p>
<p>First, why aren't you using the Django ORM for this?</p> <pre><code>MyClass.objects.filter( aField__contains=var1, secondField__exact=var2 ) </code></pre> <p>Second, be sure you're getting the SQL you expect.</p> <pre><code>stmt= "select... afield like '%%%s%%' and secondfield = '%s'..." % ( var1, var2 ) print stmt cursor.execute( stmt ) </code></pre> <p>Third, your method has a security hole called a SQL Injection Attack. You really should not be doing SQL like this.</p> <p>If you absolutely must do things outside Django's ORM, you have to use bind variables in your query, not string substitution. See <a href="http://docs.djangoproject.com/en/dev/topics/db/sql/#performing-raw-sql-queries">http://docs.djangoproject.com/en/dev/topics/db/sql/#performing-raw-sql-queries</a>.</p>
How do I rewrite $x = $hash{blah} || 'default' in Python? <p>How do I pull an item out of a Python dictionary without triggering a KeyError? In Perl, I would do:</p> <pre><code>$x = $hash{blah} || 'default' </code></pre> <p>What's the equivalent Python?</p>
<p>Use the <a href="http://docs.python.org/library/stdtypes.html#dict.get" rel="nofollow"><code>get(key, default)</code></a> method:</p> <pre><code>&gt;&gt;&gt; dict().get("blah", "default") 'default' </code></pre>
RDLC Medium Trust <p>Does anyone know of a free (for a non-profit group) RDLC reporting tool that will work under medium trust in IIS 7?</p>
<p>Our <a href="http://www.datadynamics.com/Products/DDRPT/" rel="nofollow">Data Dynamics Reports</a> product is not free, but we did implement special support for working in the restrictive medium trust environments. I don't know if it is tested on IIS7 yet, but I presume the security policy is the same so it should work in any case. If it does not let us know and we will surely get it working as this is a scenario we explicitly wanted to make sure that we provide a great solution for. For more information see the following links:</p> <ul> <li>Brief information about when we added the feature from the Product Manager of Data Dynamics: <a href="http://mrdotnet.wordpress.com/2007/11/18/new-release-of-data-dynamics-reports/" rel="nofollow">http://mrdotnet.wordpress.com/2007/11/18/new-release-of-data-dynamics-reports</a> Reports</li> <li>Instructions on setting up security in ASP.NET including how to configure medium trust: <a href="http://www.datadynamics.com/Help/ddReports/ddrtskSettingPermissions.html" rel="nofollow">http://www.datadynamics.com/Help/ddReports/ddrtskSettingPermissions.html</a></li> <li>General Product Information: <a href="http://www.datadynamics.com/Products/DDRPT/" rel="nofollow">http://www.datadynamics.com/Products/DDRPT</a></li> </ul> <p>Also, you can always contact sales@grapecity.us.com for more information about pricing for non-profit groups.</p> <p>Hope this helps.</p> <p>Scott Willeke</p>
SVN Branching and "IIS Url Already Mapped to Different Location" <p>I maintain several subversion development branches on my development pc and build box.</p> <p>How do you guys deal with opening a solution on one branch and having IIS get configured to that location. Then opening the same solution / project in a different branch / location and get "IIS Url Already Mapped to Different Location" ?</p>
<ol> <li>I added localhost.branch to my host file</li> <li>In IIS I created a new website mapped to host header localhost.branch. </li> <li>I searched and replaced <code>&lt;IISUrl&gt;<a href="http://localhost/myapp&lt;/IISUrl&amp;gt" rel="nofollow">http://localhost/myapp&lt;/IISUrl&amp;gt</a>;</code> with <code>&lt;IISUrl&gt;<a href="http://localhost.branch/myapp&lt;/IISUrl&amp;gt" rel="nofollow">http://localhost.branch/myapp&lt;/IISUrl&amp;gt</a>;</code> in all my csproj files in the branch.</li> </ol>
Design considerations for internationalization <p>I've read Joel's article on <a href="http://www.joelonsoftware.com/articles/Unicode.html">Unicode</a> and I feel that I have at least a basic grasp of internationalization from a character set perspective. In addition to reading <a href="http://stackoverflow.com/questions/898/internationalization-in-your-projects">this question</a>, I've also done some of my own research on internationalization in regards to design considerations, but I can't help but suspect that there is a lot more out there that I just don't know or don't know to ask.</p> <p><strong>Some of the things I've learned:</strong></p> <ul> <li>Some languages read right-to-left instead of left-to-right.</li> <li>Calendar, dates, times, currency, and numbers are displayed differently from language to language.</li> <li>Design should be flexible enough to accommodate a lot more text because some languages are far more verbose than others.</li> <li>Don't take icons or colors for granted when it comes to their semantic meaning as this can vary from culture to culture.</li> <li>Geographical nomenclature varies from language to language.</li> </ul> <p><strong>Where I'm at:</strong></p> <ul> <li>My design is flexible enough to accommodate a lot more text.</li> <li>I automatically translate each string, including error messages and help dialogs.</li> <li>I haven't come to a point yet where I've needed to display units of time, currency or numbers, but I'll be there shortly and will need to develop a solution.</li> <li>I'm using the UTF-8 character set across the board.</li> <li>My menus and various lists in the application are sorted alphabetically for each language for easier reading.</li> <li>I have a tag parser that extracts tags by filtering out stop words. The stop words list is language specific and can be swapped out.</li> </ul> <p><strong>What I'd like to know more about:</strong></p> <ul> <li>I'm developing a downloadable PHP web application, so any specific advice in regards to PHP would be greatly appreciated. I've developed my own framework and am not interested in using other frameworks at this time.</li> <li>I know very little about non-western languages. Are there specific considerations that need to be taken into account that I haven't mentioned above? Also, how do PHP's array sorting functions handle non-western characters?</li> <li>Are there any specific gotchas that you've experienced in practice? I'm looking in terms of both the GUI and the application code itself.</li> <li>Any specific advice for working with date and time displays? Is there a breakdown according to region or language?</li> <li>I've seen a lot of projects and sites let their communities provide translation for their applications and content. Do you recommend this and what are some good strategies for ensuring that you have a good translation?</li> <li>This question is basically the extent of what I know about internationalization. What don't I know that I don't know that I should look into further?</li> </ul> <p><strong>Edit</strong>: I added the bounty because I would like to have more real-world examples from experience.</p>
<p>Our game <a href="http://www.lobstersoft.com/gemsweeper/index.php" rel="nofollow">Gemsweeper</a> has been translated to 8 different languages. Some things I have learned during that process:</p> <ul> <li><p><strong>If the translator is given single sentences to translate, make sure that he knows about the context that each sentence is used in.</strong> Otherwise he might provide one possible translation, but not the one you meant. Tools such as <a href="http://babelfish.yahoo.com/" rel="nofollow">Babelfish</a> translate without understanding the context, which is why the result is usually so bad. Just try translating any non-trivial text from English to German and back and you'll see what I mean. </p></li> <li><p><strong>Sentences that should be translated must not be broken into different parts for the same reason.</strong> That's because you need to maintain the context (see previous point) and because some languages might have the variables at the beginning or end of the sentence. Use placeholders instead of breaking up the sentence. For example, instead of </p></li> </ul> <blockquote> <p>"This is step" "of our 15-step tutorial" </p> </blockquote> <p>Write something like: </p> <blockquote> <p>"This is step %1 of our 15-step tutorial"</p> </blockquote> <p>and replace the placeholder programmatically. </p> <ul> <li><p><strong>Don't expect the translator to be funny or creative.</strong> He usually isn't motivated enough to do it unless you name the particular text passages and pay him extra. For example, if you have and word jokes in your language assets, tell the translator in a side note not to try to translate them, but to leave them out or replace them with a more somber sentence instead. Otherwise the translator will probably translate the joke word by word, which usually results in complete nonsense. In our case we had one translator and one joke writer for the most critical translation (English). </p></li> <li><p><strong>Try to find a translator who's first language is the language he is going to translate your software to, not the other way round.</strong> Otherwise he is likely to write a text that might be correct, but sounds odd or old-fashioned to native speakers. Also, he should be living in the country you are targeting with your translation. For example a German-speaking guy from Switzerland would not be a good choice for a German translation.</p></li> <li><p><strong>If any possible, have one of your public beta test users who understands the particular translation verify translated assets and the completed software.</strong> We've had some very good and very bad translations, depending on the person who provided it. According to some of our users, the Swedish translation was total gibberish, but it was too late to do anything about it. </p></li> <li><p><strong>Be aware that, for every updated version with new features, you will have to have your languages assets translated.</strong> This can create some serious overhead.</p></li> <li><p><strong>Be aware that end users will expect tech support to speak their language if your software is translated.</strong> Once again, Babelfish will most probably not do. </p></li> </ul> <p><strong>Edit - Some more points</strong></p> <ul> <li><p><strong>Make switching between localizations as easy as possible.</strong> In Gemsweeper, we have a hotkey to switch between different languages. It makes testing much easier. </p></li> <li><p><strong>If you are going to use exotic fonts, make sure these include special characters.</strong> The fonts we chose for Gemsweeper were fine for English text, but we had to add quite a few characters by hand which only exist in German, French, Portughese, Swedish,... </p></li> <li><p><strong>Don't code your own localization framework.</strong> You're probably much better off with an open source framework like <a href="http://www.gnu.org/software/gettext/" rel="nofollow">Gettext</a>. Gettext supports features like variables within sentences or pluralization and is rock-solid. Localized resources are compiled, so nobody can tamper with them. Plus, you can use tools like <a href="http://www.poedit.net/" rel="nofollow">Poedit</a> for translating your files / checking someone else's translation and making sure that all strings are properly translated and still up to date in case you change the underlying source code. I've tried both rolling my own and using Gettext instead and I have to say that Gettext plus PoEdit were way superior. </p></li> </ul> <p><strong>Edits - Even More Points</strong> </p> <ul> <li><p><strong>Understand that different cultures have different styles of number and date formats.</strong> Numbering schemes are not only different per culture, but also per purpose within that culture. In EN-US you might format a number '-1234'; '-1,234' or (1,234) depending on what the purpose of the number is. Understand other cultures do the same thing.</p></li> <li><p><strong>Know where you're getting your globalization information from.</strong> E.g. Windows has settings for CurrentCulture, UICulture, and InvariantCulture. Understand what each one means and how it interacts with your system (they're not as obvious as you might think).</p></li> <li><p><strong>If you're going to do east Asian translating, really do your homework.</strong> East-Asian languages have quite a few differences from languages here. In addition to having multiple alphabets that are used simultaneously, they can use different layout systems (top-down) or grid-based. Also numbers in east Asian languages can be very different. In the en-US you only change systems for limited conditions (e.g. 1 versus 1st), there are additional numeric considerations besides just comma and period.</p></li> </ul>
Is it possible to have Castor marshal/unmarshal an EnumMap? <p>I'm using Castor to marshal/unmarshal my Java objects, one of which contains an EnumMap. Can Castor marshal/unmarshal EnumMaps? I have a mapping file with some nested HashMaps, but I've never pushed an EnumMap through Castor. If it is possible, how is it done through the mapping file?</p>
<p>One of the big problems is that Enums can't really be serialized and restored, at least not in Java 1.5. And I think also not in Java 1.6. </p> <p>As enums can not - by default - be serialized or XMLEncoded I very much doubt an EnumMap can be serialized. From the <a href="http://www.castor.org/xml-mapping.html#7.5-Type-safe-enumeration-mapping-%28since-0.9.5%29" rel="nofollow">castor web page</a> :</p> <blockquote> <p>While you can always use your own custom FieldHandler for handling type-safe enumeration classes, Castor does have a built-in approach to dealing with these types of classes. If the type-safe enum class has a public static valueOf(String) method Castor will call that method so that the proper instance of the enumeration is returned. Note: You'll also need to disable the default constructor check in the mapping file (see section 7.4 above to see more on this).</p> </blockquote> <p>if that does not work you have to write your own <a href="http://www.castor.org/xml-fieldhandlers.html" rel="nofollow">field handler</a>.</p> <p>I hope this helps a bit. </p>
How does Python sort a list of tuples? <p>Empirically, it seems that Python's default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what's the right way to sort a list of tuples by their first elements?</p>
<p>It automatically sorts a list of tuples by the first elements in the tuples, then by the second elements and so on tuple([1,2,3]) will go before tuple([1,2,4]). If you want to override this behaviour pass a callable as the second argument to the sort method. This callable should return 1, -1, 0.</p>
Converting a pthreaded program to MPI? <p>I understand the differences between a multithreaded program and a program relying on inter-machine communication. My problem is that I have a nice multithreaded program written in 'C' that works and runs really well on an 8-core machine. There is now opportunity to port this program to a cluster to gain access to more cores. Is it worth the effort to rip out the pthread stuff and retrofit MPI (which I've never used) or are we better off recoding the whole thing (or most of it) from scratch? Assume we are "stuck" with C so a wholesale change of language isn't an option.</p>
<p>Depending on how your software is written, there may or may not be advantages to going to MPI over keeping your pthread implementation.</p> <p>Unfortunately (or fortunately), message passing is a very different beast than pthreading - the basic assumption is quite different. I love <a href="http://blogs.msdn.com/maestroteam/archive/2009/02/27/we-haven-t-forgotten-about-other-models-honest.aspx" rel="nofollow">this quote from Joshua Phillips of the Maestro team</a>: "The difference between message-passing and shared-state communication is equivalent to the difference between sending a colleague an e-mail requesting her to complete a task and opening up her organizer to write down the task directly in her to-do list. More than just being rude, the latter is likely to confuse her – she might erase it, not notice it, or accidentally prioritize it incorrectly."</p> <p>Unfortunately, the way you share data is very different. There is no direct access to data in other threads (since it can be on other machines), so it can be a very daunting task to migrate from pthreads to MPI. On the other hand, if the code is written so each thread is isolated, it can be an easy task, and definitely worthwhile.</p> <p>In order to determine how useful this will be, you'll need to understand the code, and what you hope to achieve by switching. It can be worthwhile as a learning experience (you learn a LOT about synchronization and threading by working in MPI), but may not be practical if the gains will be minor.</p>
What settings affect the layout of compiled java .class files? How can you tell if two compiled classes are equal? <p>I have an app that was compiled with the built-in Eclipse "Compile" task. Then I decided to move the build procedure into Ant's <code>javac</code>, and the result ended being smaller files.</p> <p>Later I discovered that adjusting the debuglevel to <code>"vars,lines,source"</code> I could embed the same debug information that Eclipse did, and in a lot of cases files stayed exactly the same size but the internal layout was different. And as a consequence, I couldn't use md5sum signatures to determine if they were exactly the same version.</p> <p>Besides debug information, what can be the reason that 2 supposedly equal files get a different internal layout or size? </p> <p>And how can you compare compiled .class files?</p>
<p>THere is no required order for things such as the order of the constant pool entries (essentially all of the symbol info) as well as the attributes for each field/method/class. Different compilers are free to write out in whatever order they want.</p> <p>You can compared compiled classes, but you would need to dig into the class file structure and parse it. There are libraries out there for doing that, like <a href="http://jakarta.apache.org/bcel/" rel="nofollow">BCEL</a> or <a href="http://asm.objectweb.org/" rel="nofollow">ASM</a>, but I am not 100% sure they will help you with what you want to do.</p>
Query on Select System Call <p>select() is defined as :</p> <pre><code>int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout); </code></pre> <p><em>nfds</em> represents the highest file descriptor in all given sets plus one. I would like to know why is this data required for select() when the fd_set information is available. </p> <p>If the FDs in the set are say, 4, 8, 9 ,the value of <em>nfds</em> would be 10. Would select() moniter fds 9,8,7,6,5,4 ?</p>
<p>The catch is that fd_set is not really a "set" in the way you're thinking. The behind-the-scenes detail is that the implementation of an fd_set is just an integer that is used as a bitfield. In other words, executing</p> <pre><code>fd_set foo; FD_CLEAR(&amp;foo); FD_SET(&amp;foo, 3); </code></pre> <p>Sets foo to decimal value 8 - it sets the fourth-least-singificant bit to 1 (remember that 0 is a valid descriptor).</p> <pre><code>FD_SET(&amp;foo, 3); </code></pre> <p>is equivalent to </p> <pre><code>foo |= (1 &lt;&lt; 3); </code></pre> <p>So in order for select to work right, it needs to know which bits of the fd_set are bits that you care about. Otherwise there would be no way for it to tell a zero bit that is "in" the set but set to false from a zero bit that is "not in" the set.</p> <p>In your example, a fd_set with 4, 8, and 9 set and n = 10 is interpreted as "A set with 10 entries (fds 0-9). Entries 4, 8, and 9 are true (monitor them). Entries 1,2,3,5,6,7 are false (don't monitor them). Any fd value greater than 9 is simply not in the set period."</p>
CPU clock frequency and thus QueryPerformanceCounter wrong? <p>I am using QueryPerformanceCounter to time some code. I was shocked when the code starting reporting times that were clearly wrong. To convert the results of QPC into "real" time you need to divide by the frequency returned from QueryPerformanceFrequency, so the elapsed time is:</p> <p>Time = (QPC.end - QPC.start)/QPF</p> <p>After a reboot, the QPF frequency changed from 2.7 GHz to 4.1 GHz. I do not think that the actual hardware frequency changed as the wall clock time of the running program did not change although the time reported using QPC did change (it dropped by 2.7/4.1).</p> <p>MyComputer->Properties shows:</p> <p>Intel(R) Pentium(R) 4 CPU 2.80 GHz; 4.11 GHz; 1.99 GB of RAM; Physical Address Extension</p> <p>Other than this, the system seems to be working fine.</p> <p>I will try a reboot to see if the problem clears, but I am concerned that these critical performance counters could become invalid without warning.</p> <p>Update:</p> <p>While I appreciate the answers and especially the links, I do not have one of the affected chipsets nor to I have a CPU clock that varies itself. From what I have read, QPC and QPF are based on a timer in the PCI bus and not affected by changes in the CPU clock. The strange thing in my situation is that the FREQUENCY reported by QPF changed to an incorrect value and this changed frequency was also reported in MyComputer -> Properties which I certainly did not write.</p> <p>A reboot fixed my problem (QPF now reports the correct frequency) but I assume that if you are planning on using QPC/QPF you should validate it against another timer before trusting it. </p>
<p>Apparently there is a known <A href="http://support.microsoft.com/kb/274323" rel="nofollow">issue</A> with QPC on some chipsets, so you may want to make sure you do not have those chipset. Additionally some dual core AMDs may also cause a <A href="http://forum.beyond3d.com/showthread.php?t=47951" rel="nofollow">problem</A>. See the second post by sebbbi, where he states:</p> <blockquote> <p>QueryPerformanceCounter() and QueryPerformanceFrequency() offer a bit better resolution, but have different issues. For example in Windows XP, all AMD Athlon X2 dual core CPUs return the PC of either of the cores "randomly" (the PC sometimes jumps a bit backwards), unless you specially install AMD dual core driver package to fix the issue. We haven't noticed any other dual+ core CPUs having similar issues (p4 dual, p4 ht, core2 dual, core2 quad, phenom quad).</p> </blockquote> <p>From this <a href="http://stackoverflow.com/questions/275004/c-timer-function-to-provide-time-in-nano-seconds/275231#275231">answer</a>.</p>
Can you force symfony resolve to a specific route? <p>Say that I have to following 2 routes in this order:</p> <pre><code>Zip: url: home/:zip param: { module: home, action: results } State: url: home/:state param: { module: home, action: results } </code></pre> <p>and I use a route such as:</p> <pre><code>'@State?state=CA' </code></pre> <p>Why does it resolve to the Zip route? I thought when you specified the route name explicitly: '@State' that it did not parse the entire routing file and just used the specific route you asked for.</p> <p>I would like to be able to use the same action to display data based on the variable name (zip or state) I don't want to have to create the same action (results) twice just to pass in a different parameter.</p>
<p>You need to add requirements so that it will recognize the different formats</p> <pre><code>Zip: url: home/:zip param: { module: home, action: results } requirements: { zip: \d{5} } # assuming only 5 digit zips State: url: home/:state param: { module: home, action: results } requirements: { state: [a-zA-Z]{2} } </code></pre> <p>That should fix it, although I agree with you that when you use a route name in a helper it should use the named route.</p>
Is this causing EXC_BAD_ACCESS? <p>I'm getting a EXC_BAD _ACCESS after leaving the method below. At that point htmlDocument becomes invalid, which it should since it falls out of scope. But is that why I'm getting the error? By the time the contentView (UIWebView) loads, htmlDocument is gone. But doesn't contentView already have what it needs from loadHTMLString?</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; //something other processing here NSString *htmlDocument = [NSString stringWithFormat:@"&lt;html&gt; \n" "&lt;body&gt;%@&lt;/body&gt; \n" "&lt;/html&gt;", aboutContent]; [contentView loadHTMLString:htmlDocument baseURL:[NSURL URLWithString:@"http://www.abc.com"]]; </code></pre> <p>}</p> <p>Is there a better way to follow this all the way to failure? Leaving this method is the end of the line for my code. SDK stuff from there.</p>
<p>From your second post, the line you have commented out ([button release]) releases an object already marked to be released automatically. </p> <p>Either remove the "autorelease" where you are doing an alloc for the button or remove the [button release] statement for the code to compile without errors and exceptions.</p> <p>If an object is marked for autorelease, calling a release on it will be the same as calling a release on a deallocated instance, hence the error.</p>
How do I send Asian charset plaintext emails in ASP.NET? <p>I have an ASP.NET application that needs to send emails in Korean. These emails are sent in plaintext. </p> <p>But when the emails are received, they look like this:</p> <blockquote> <p>? First name? ??: ?????.</p> <p>?? ???? ???? ?? ??? ??? ?? ???? ???? ????? ???? ????. ??????? ??? ????? ???? ??? ??1-888-123-4567 ? ??????? ?? info@example.com ?? ?????? ???? ??? ??????.</p> </blockquote> <p>Currently I'm not setting the encoding. Just using the default. Ideally, I would like the encoding to work with all sorts of emails. Hopefully I don't have to set the encoding on a per-email basis.</p>
<p>You basically have 2 ways to encode email parts:</p> <ol> <li><p>Using the Korean Code page for your email so people not using Unicode can still view it (charsets like <code>ISO-2022-KR</code> and <code>x-windows-949 </code>, I don't know which of the 3 is the most common):</p> <pre><code>Content-Type: text/plain; charset="EUC-KR" Content-Transfer-Encoding: quoted-printable </code></pre></li> <li><p>Using UTF8 encoding, which is the preferred way nowadays.<br /> In any case, the recipient must have proper support for <a href="http://www.microsoft.com/globaldev/handson/user/xpintlsupp.mspx" rel="nofollow">Asian languages installed on their machine</a> for the message to display correctly.</p> <pre><code>Content-Type: text/plain; charset=UTF-8; Content-Transfer-Encoding: 8bit </code></pre></li> </ol> <p>Here are a couple of good articles that explain how to implement this properly:</p> <ul> <li><a href="http://www.systemwebmail.com/faq/3.1.aspx" rel="nofollow">System.Web.Mail FAQ</a></li> <li><a href="http://www.aspnetmime.com/help/welcome/overviewmimei.html" rel="nofollow">MIME Overview Part I: A brief overview of the MIME specification</a></li> </ul>
Allow php sessions to carry over to subdomains <p>I use php sessions (not cookies, except for session id cookie) for all user data, and when a user goes to their profile user.mydomain.com they are immediately "logged out" untill then remove the subdomain.</p> <p>Is there a way to accept sessions from all domains as long as its *.mydomain.com</p>
<p>Here are 4 options.</p> <p>Place this in your php.ini:</p> <pre><code>session.cookie_domain = ".example.com" </code></pre> <p>Or in your .htaccess:</p> <pre><code>php_value session.cookie_domain .example.com </code></pre> <p>Or as the first thing in your script:</p> <pre><code>ini_set('session.cookie_domain', '.example.com' ); </code></pre> <p>Or in your php-fpm pool configuration for your site:</p> <pre><code>php_value[session.cookie_domain] = .example.com </code></pre>
Force UIView/UIVIewController orientation <p>We're writing an application that's in landscape mode exclusively. We use a transform on a root view to rotate it to LandscapeRight, then every view that gets loaded by that view shares the coordinate system. That's all fine and dandy, except one of our views has a UIWebView object that's being loaded by a view controller. The site that we're trying to look at doesn't have its content filling the view. When I view the same site in mobile Safari in landscape mode, it looks correct. My guess is that the View Controller we're using to host the WebView still thinks it's in portrait mode, as querying the interfaceOrientation of the property returns "1"...is there a way to trick a view/view controller to think it's in a specific orientation?</p>
<p>Hopefully you've already found an answer for this, but you might try telling your app to just start out in landscape mode, rather than forcing it to always rotate to that orientation. Then if your root view's shouldAutorotateToInterfaceOrientation returns yes only for landscape modes, I'd bet you'd have the behavior you're looking for.</p> <p>This guy seems to have a good tutorial about how to do all that. <a href="http://www.dejoware.com/blogpages/files/iphone_programming_landscape_view_tutorial.html">http://www.dejoware.com/blogpages/files/iphone_programming_landscape_view_tutorial.html</a></p>
[i.][m.] HTTP Addresses <p>I noticed that on the web some sites have subdomains dedicated to images or information on sub-domains such as i.domain.com. I was wondering what is the advantage of this? Is there a name for this type of "Method"? Where can I get more information on this? Thanks.</p>
<p>Parallel-izing image/script downloads.</p> <p>Some browsers will only have 2 concurrent connections open to a given <strong>domain</strong> at a time. If you have 20 images/scripts to download you can only get 2 at a time x10. If you use different domains (subdomains) you can increase the amount of concurrent downloads. </p> <p>As an example StackOverflow puts images under i.stackoverflow.com to help with speed.</p> <p><strong>EDIT</strong></p> <p>As noted by Richard (in a comment) that the HTTP spec strongly advises a 2 concurrent connection limit.</p>
Calling typeface.js on HTML fetched by jQuery? <p>I have a page where I'm fetching a Wordpress main index to handle my 'news feed', imported via jQuery.ajax. I'm also using typeface.js on the same page to have better typeface control. I want to call typeface.js on the elements in the Ajax'd HTML. The problem is that I'm not sure how to do that, since the structure of it is unfamiliar to me. It doesn't have functions to call in the normal sense, otherwise I'd just use those on success with the ajax request.</p> <p>Does anyone have experience with typeface.js to help me out?</p> <p>Thanks.</p>
<p>Once you append the returned contents to your document you can call: _typeface_js.renderDocument() which will render the new content</p>
Runtime query analysis and optimization <p>I'm wondering if there's some sort of runtime mechanism that would observe the queries that are running against my database server; record how many queries of each "type" are running; look at the performance of these queries; then, based on this runtime data, suggest what indexes need to be added/removed. </p> <p>I'm working against MySQL at the moment; if you know of similar tools for other DB vendors, I'd be interested to know, too. Thanks!!</p>
<p>I'd suggest giving <a href="http://www.jetprofiler.com/" rel="nofollow">Jet Profiler</a> a try. The free version is a bit limited but i still found it useful. It will do most of what you have asked, but you may struggle to find a tool that will suggest indexes for you though.</p>
How to hook up LED lights in C++ without microcontroller? <p>I want to light up/off LEDs without a microcontroller. I'm looking to control the LEDs by writing a C++ program. but the problem im having is hooking them up is there a free way to do !!!!</p> <p>I'm using Windows XP if that is relevant.</p> <p>I have LEDs but I don't have a microcontroller.</p> <p>Well, I found some functions but their headers are not working, so can someone help me find headers?</p> <p>Here is an example of what I'm talking about:</p> <pre><code>poke(0x0000,0x0417,16); gotoxy(1,1); printf("Num Lock LED is now on r"); delay(10); </code></pre> <p>Also, does anyone have a "Kernel Programming" eBook? </p> <p>I also need a circuit diagram to show where to hook up the LEDs.</p>
<p>That completely depends on which hardware you have, which determines which driver you need. Back then, i got a simple led and put it into the printer LPT port. Then i could write a byte to address 0x0378h and the bits in it determined whether a pin had power or not (using linux). For windows, you need a driver that allows you to access the lpt port directly. I did it with a friend back then too, and it worked nicely (we built up a traffic light :)) Read <a href="http://logix4u.net/" rel="nofollow">this page</a> (click on Parallel Port on the left. For some reason, i cannot link directly to it) for details on windows. And read <code>man outb</code> on linux. Now, that Port is really old. But if you have some machine around that still got one, i think it's a lot of fun to play with it. </p> <p>Anyway, i've got a fritz box that has a neat LED. One can connect to it via <code>telnet</code> and then write something (i forgot the numbers) into <code>/proc/led</code> iirc. A kernel driver then interprets the number and makes the right LED blink. That's another way of doing it :)</p>
How to blend a quad, already with a texture on it <p>I made a quad with a nice texture on it. The texture has an alpha channel (RGBA). I replaced the quad with the texture <code>(GL_REPLACE)</code>, so now I have a billboard with (semi)transparant pixels on it.</p> <p>So far, no problem. </p> <p>But now I want to <em>blend the entire</em> billboard, so it's <em>overall opacity changes</em>.</p> <p><strong>How would I do this?</strong></p>
<p>GL_MODULATE, instead of GL_REPLACE, after setting the color to solid white, with an appropriate amount of alpha. (glColor(1,1,1,0.5) for instance)</p> <p>(Should work fine on OpenGL. Seems likely it'll be good on ES, too.)</p>
Have buildbot poll a git repository for new commits? <p>Is there a <a href="http://buildbot.net/trac" rel="nofollow">buildbot</a> plugin that will poll a git repository for new commits, like the currently included <a href="http://github.com/djmitche/buildbot/blob/d4ec886c3740a4f97ab172b81c9a9b94eb6f00d3/buildbot/changes/svnpoller.py" rel="nofollow"><code>changes.SVNPoller</code></a>?</p> <p>The closest I have found is <a href="http://github.com/djmitche/buildbot/blob/d4ec886c3740a4f97ab172b81c9a9b94eb6f00d3/contrib/git%5Fbuildbot.py" rel="nofollow">git_buildbot.py</a>, but it works as a post-commit hook, so will not work with my setup (using Github, and buildbot on a machine that github's post-commit cannot reach) - simply polling the git repository would work perfectly.</p> <p>I currently have a build run once an hour, but there's not really any point in running the tests unless something has changed..</p>
<p><strong>Update:</strong> The kind folks at the Buildbot project have made the GitPoller an official Change Source as of version 0.8.2, and made several improvements to the original.</p> <hr> <p>Our company is in a similar situation where our build machines cannot be reached by GitHub's post-commit hook. I've written a <code>GitPoller</code> change source that can be used like the <code>SVNPoller</code>. </p> <p>It can be found here: <a href="http://github.com/wimba/buildbot/blob/master/buildbot/changes/gitpoller.py" rel="nofollow">http://github.com/wimba/buildbot/blob/master/buildbot/changes/gitpoller.py</a></p> <p>and used like this:</p> <pre><code>from buildbot.changes.gitpoller import GitPoller c['change_source'] = GitPoller('git@example.com:foobaz/myrepo.git', branch='great_new_feature') </code></pre> <p>It will create a local repo to work out of (location configurable), and it's only been tested with <code>git 1.7</code> so your mileage may vary.</p> <p>Hopefully it will be pulled into the Buildbot project proper at some point, but it's been working for us so far and hoping it may be of use to others :)</p>
side effects of garbage collection? <p>This may be an eminently closeable question, but I'm the type that sees what sticks to the wall. For all of the benefits of memory and lifetime management afforded by a garbage collected runtime, have there been any notable cases of program indeterminacy caused by race conditions between an application and its garbage collector? Has a gestalt of defensive programming against this kind of thing emerged? Surely programmers accustomed to RAII must learn lessons when in the presence of GC.</p>
<p>The problem with garbage collection is that it only manages memory resources. Unfortunately, programmers must manage many, many other resource types:</p> <ul> <li>file and socket handles</li> <li>database connections</li> <li>synchronisation objects</li> <li>gui resources</li> </ul> <p>to name but a few. To manage those succesfully, you really need the concepts embodied in the RAII idiom. </p>
Insert a commit before the root commit in Git? <p>I've asked before about how to <a href="http://stackoverflow.com/questions/598672/git-how-to-squash-the-first-two-commits">squash the first two commits</a> in a git repository.</p> <p>While the solutions are rather interesting and not really as mind-warping as some other things in git, they're still a bit of the proverbial bag of hurt if you need to repeat the procedure many times along the development of your project. </p> <p>So, I'd rather go through pain only once, and then be able to forever use the standard interactive rebase. </p> <p>What I want to do, then, is to have an empty initial commit that exists solely for the purpose of being the first. No code, no nothing. Just taking up space so it can be the base for rebase.</p> <p>My question then is, having an existing repository, how do I go about inserting a new, empty commit before the first one, and shifting everyone else forward?</p>
<p>Here’s a cleaner implementation of the same solution, in that it works without the need to create an extra repository, futz around with remotes, and correct a detached head:</p> <pre><code># first you need a new empty branch; let's call it `newroot` git checkout --orphan newroot git rm -rf . # then you apply the same steps git commit --allow-empty -m 'root commit' git rebase --onto newroot --root master git branch -d newroot </code></pre> <p>Voila, you’ve ended up on <code>master</code> with its history rewritten to include an empty root commit.</p> <hr> <p>NB.: on old versions of Git that lack the <code>--orphan</code> switch to <code>checkout</code>, you need the plumbing to create an empty branch:</p> <pre><code>git symbolic-ref HEAD refs/heads/newroot git rm --cached -r . git clean -f -d </code></pre>
Keeping my web app running after Browser close <p>I have a aspx web application that updates or adds files in a database. The clients access through the browser and one of the requirements is that they can start the update and be able to close the browser while the update continues. It appears to run for a little bit after I close the browser but then it stops. How can you keep the application running for asp.net?</p>
<p>That's something you could very well solve with <a href="http://msdn.microsoft.com/en-us/netframework/aa663328.aspx" rel="nofollow">WF (Workflow Foundation)</a>. Create a workflow for the task that should survive closing the browser. Workflows have their own threads and livecycles separate from ASP.NET. </p>
Servlets and JSP video tutorials <p>Are there video tutorials for Servlets and JSPs with the same caliber as asp.net and windowsclient.net Learn section?</p>
<p>Perhaps this is helpful: <a href="http://blogs.oracle.com/arungupta/entry/screencast_28_simple_web_application" rel="nofollow">http://blogs.oracle.com/arungupta/entry/screencast_28_simple_web_application</a></p>
Mimic Window. onerror in Opera using javascript <p>I am currently working on a web application, I have a JS logging mechanism that Handles Javascript error that are not caught by the js code inside the page. I am using window.onerror to catch all such errors and log them else where.</p> <p>However, Problem is with Opera which does not have window.onerror event. one approach I could think of is, to string process all js functions code and insert try catch blocks inside those functions after body load. It does not work in many cases though, But, It at least works to some extent.</p> <p>I am sure this approach sucks, But, I could not think of anything better. Please advise.</p> <p>Update: For now, I am calling the code below to Catch as many errors as I could.</p> <pre><code>function OnBodyLoad() { var allElements = document.getElementsByTagName("*"); for(var cnt = 0;cnt &lt; allElements.length;cnt++) { RegisterAllEvents(allElements[cnt]); } } function RegisterAllEvents(objToProcess){ for(var cnt = 0;cnt &lt; objToProcess.attributes.length;cnt++){ if(IsAttributeAnEvent(objToProcess.attributes[cnt].name)) { objToProcess.attributes[cnt].value = 'try{'+objToProcess.attributes[cnt].value+'}catch(err){LogError("'+ objToProcess.id+'"'+ ',err);}'; } } } </code></pre>
<p>Opera 11.60+ supports <code>window.onerror</code>.</p> <p>Opera's <a href="http://dev.opera.com/articles/view/introduction-to-opera-dragonfly/" rel="nofollow">Dragonfly</a> supports <a href="http://dev.opera.com/articles/view/remote-debugging-with-opera-dragonfly/" rel="nofollow">remote debugging</a>. You might be able to <a href="https://dragonfly.opera.com/app/core-2-2/" rel="nofollow">hack it</a> (it's all written in JavaScript) and log errors yourself (unfortunately the protocol <a href="http://dev.opera.com/articles/view/opera-dragonfly-architecture/#scopeprotocol" rel="nofollow">isn't published yet</a>).</p>
Process rdl/rdlc report files without SSRS? <p>Is there any way to render and export an rdl file within a batch process without using SSRS?</p> <p>I don't want the overhead of SSRS (IIS + database) and instead want to handle this within my own batch/scheduling service.</p> <p>Thanks</p>
<p>You can conceivably use the <a href="http://msdn.microsoft.com/en-us/library/ms251671%28VS.80%29.aspx" rel="nofollow">Report Viewer control</a> in a server process written in managed code. You pass the control a data source (which can be a DataTable memory object), and it will return a byte stream that you can direct into a file.</p> <p>The control has a UI, but that can be by-passed.</p>
.NET port of OGNL Library <p>Does anyone know of a good .NET port of the <a href="http://www.opensymphony.com/ognl/" rel="nofollow">OGNL library</a> here? It looks like I could use something like this and the only one I have found so far is on SourceForge <a href="http://sourceforge.net/projects/ognlnet/" rel="nofollow">here</a> and hasn't been updated since 2005.</p>
<p>I've been looking for something like this as well. Unfortunately, there isn't anything I'm aware of that's feasible for use in a real project. Sorry!</p> <p>One suggestion that might be of help is to e-mail the author directly. Oftentimes, they abandon the project because they've found that another existing project's work is more in line with what they were trying to accomplish.</p>
Distributing loadable builtin bash modules <p>I've written a built-in for bash which modifies the 'cd' command, a requirement for my software. Is there a way to actually distribute a loadable independently of bash itself? I'd ideally like to distribute just a drop in "additional feature" because I know people can be put off by patching and compiling their shell from source code.</p> <hr> <p>In a <a href="http://stackoverflow.com/questions/646010/distributing-loadable-builtin-bash-modules#comment460316_646593">comment</a> to a now-deleted <a href="http://stackoverflow.com/a/646593/">answer</a>, <a href="http://stackoverflow.com/users/25466/philluminati">Philluminati</a> said:</p> <blockquote> <p>I want to time how long a user is in a directory so I can determine where they want to be. It's this functionality: <a href="http://github.com/joelthelion/autojump/tree/master" rel="nofollow">http://github.com/joelthelion/autojump/tree/master</a> rewritten as a bash builtin, for performance issues. This implementation uses <code>$PROMPT_COMMAND</code> to work but I wanted something integrated. </p> </blockquote>
<p>It is unclear what you have modified but in any case, <code>bash</code> (like at least <code>ksh93</code> which IIRC introduced the concept and <code>zsh</code>) supports, using the <code>enable -f file name</code> syntax, loading built-in functions as external dynamically loaded modules.</p> <p>These modules being plain files can certainly be distributed independently, as long as you make sure they are compatible with the target version/architecture. This was already true 5 years ago when you asked this question.</p> <p>One issue in your case is there seems to be no documented way to overload a internal built-in like <code>cd</code> by a dynamically loaded one while keeping the ability to access the former.</p> <p>A simple workaround would be to implement your customized cd with a different name, say mycd, like this:</p> <pre><code>int mycd_builtin(list) WORD_LIST *list; { int rv; rv=cd_builtin(list); if(rv == EXECUTION_SUCCESS) { char wd[PATH_MAX+1]; getcwd(wd,sizeof(wd)); // do your custom stuff knowing the new working directory ... } return (rv); } </code></pre> <p>then to use an alias, or better, a shell function for your customized version to be used instead of the regular one:</p> <pre><code>cd() { mycd "$@" } </code></pre> <p>As long as your customization doesn't affect the behavior of the standard command and thus doesn't risk breaking scripts using it, there is nothing wrong in your approach.</p>
Jqmodal isn't working in the Updatepanel <p>I have a method named raise_alarm() which, show a message box based on jquery. But when I call this method from an event of a control(such as submit button) which is inside of Updatepanel, it isn't working. Related codes are below. How can I fix it?</p> <pre><code> Public Sub Raise_Alarm(ByVal p_Page As Page, ByVal p_Message As String, Optional ByVal p_IsError As Boolean = True) Dim strScript As String strScript = "$(function() { Mesaj('" &amp; p_Message &amp; "'); });" &amp; ControlChars.NewLine p_Page.ClientScript.RegisterStartupScript(p_Page.GetType(), "alert", strScript, True) end sub Private Sub dtlQuestion_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles dtlQuestion.ItemCommand If Not User.Identity.IsAuthenticated Then Raise_Alarm(Me, "Giriş Yapmadan Oy Veremezsiniz") Exit Sub End If end sub </code></pre>
<p>You have to use <code>ScriptManager</code> instead of <code>p_Page.ClientScript</code>.</p> <p>EDIT : Example. I replaced <code>p_Page.ClientScript</code> by <code>ScriptManager</code> in your code.</p> <pre><code>Public Sub Raise_Alarm(ByVal p_Page As Page, ByVal p_Message As String, Optional ByVal p_IsError As Boolean = True) Dim strScript As String strScript = "$(function() { Mesaj('" &amp; p_Message &amp; "'); });" &amp; ControlChars.NewLine ScriptManager.RegisterStartupScript(p_Page.GetType(), "alert", strScript, True) end sub Private Sub dtlQuestion_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles dtlQuestion.ItemCommand If Not User.Identity.IsAuthenticated Then Raise_Alarm(Me, "Giriş Yapmadan Oy Veremezsiniz") Exit Sub End If end sub </code></pre> <p>ClientScript is not ajax enabled, ScriptManager knows how to deal with partial postbacks. Please have a quick look at <a href="http://msdn.microsoft.com/en-us/magazine/cc163354.aspx" rel="nofollow">this article on msdn</a>.</p>
Silverlight's WebClient isn't connecting to my server <p>I've got a problem here.</p> <p>I've got an ASP.net website hosting a silverlight 2 application. I'd like the site to communicate to and fro from the silverlight app, and I'm doing this via http requests. Incidentally, if anyone knows a better way, please do tell me.</p> <p>My server's got the following http listener set up. I copied this from a tutorial site somewhere, since it's mainly experimentation at the moment :</p> <pre><code> HttpListener listener = new HttpListener ( ); listener.Prefixes.Add("http://localhost:4531/MyApp/"); listener.Start( ); // Wait for a client request: HttpListenerContext context = listener.GetContext( ); // Respond to the request: string msg = "You asked for: " + context.Request.RawUrl; context.Response.ContentLength64 = Encoding.UTF8.GetByteCount (msg); context.Response.StatusCode = (int) HttpStatusCode.OK; using (Stream s = context.Response.OutputStream) using (StreamWriter writer = new StreamWriter (s)) writer.Write (msg); listener.Stop( ); </code></pre> <p>I'm using the following code to send a request :</p> <pre><code> private void MyButton_Click(object sender, RoutedEventArgs e) { Button b = sender as Button; b.Content = "Hello World"; Uri serviceUri = new Uri("http://localhost:4531/MyApp/"); WebClient downloader = new WebClient(); downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TestDownloadStoriesCompleted); downloader.DownloadStringAsync(serviceUri); } void TestDownloadStoriesCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { TextBox1.Text = e.Result; } } </code></pre> <p>My problem is that I can connect to the webserver from a console application using pretty much the same code (I tested it by setting a breakpoint in the code), however nothing happens when I click the button in silverlight. (I've added the "Hello World" to test that I am indeed connecting the delegate to the button.)</p> <p>I've read that silverlight needs policies to connect via webclient, but it shouldn't be the case if I'm using the same server and the same domain for both the server and the silverlight application!</p> <p>Thanks for all your replies!</p> <p>EDIT : I am recieving this exception :</p> <p>System.Security.SecurityException ---> System.Security.SecurityException: Security error.</p> <p>Also, based on what I'm <a href="http://scorbs.com/2008/04/05/silverlight-http-networking-stack-part-1-site-of-origin-communication/" rel="nofollow">reading</a> apparently to be site-of-origin, the deployment URI of the xap and the request URI must also be of the same port. </p> <p>However, when I set the properties for the server to be hosted on a specific port, and I set the listener to listen to that same port, it fails with the message that The process cannot access the file because it is being used by another process. I assume it is because the http listener can't listen to the same port being used to host it :| But then how can I make Silverlight perform host of origin webclient requests?</p>
<p>Since this is only a test add an "else TextBox1.Text=e.Error.ToString();" in your TestDownloadStoriesCompleted handler to see what error you get.</p> <p>EDIT:</p> <p>You can't host both the asp.net app and your listener on the same port - you could fix this by using a different port and serving a clientaccesspolicy.xml from your httplistener.</p> <p>However I think it would make more sense for you to take a look at WCF web services (you add the svc to your asp.net app). Here's a <a href="http://blogs.msdn.com/suwatch/archive/2008/04/07/tutorial-using-silverlight-web-service-client-configuration.aspx" rel="nofollow">sample</a>.</p>
ASP.NET MVC - Custom validation message for value types <p>When I use UpdateModel or TryUpdateModel, the MVC framework is smart enough to know if you are trying to pass in a null into a value type (e.g. the user forgets to fill out the required Birth Day field) .</p> <p>Unfortunately, I don't know how to override the default message, "A value is required." in the summary into something more meaningful ("Please enter in your Birth Day").</p> <p>There has to be a way of doing this (without writing too much work-around code), but I can't find it. Any help?</p> <p><strong>EDIT</strong></p> <p>Also, I guess this would also be an issue for invalid conversions, e.g. BirthDay = "Hello".</p>
<p>Make your own ModelBinder by extending DefaultModelBinder:</p> <pre><code>public class LocalizationModelBinder : DefaultModelBinder </code></pre> <p>Override SetProperty:</p> <pre><code> base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value); foreach (var error in bindingContext.ModelState[propertyDescriptor.Name].Errors. Where(e =&gt; IsFormatException(e.Exception))) { if (propertyDescriptor.Attributes[typeof(TypeErrorMessageAttribute)] != null) { string errorMessage = ((TypeErrorMessageAttribute)propertyDescriptor.Attributes[typeof(TypeErrorMessageAttribute)]).GetErrorMessage(); bindingContext.ModelState[propertyDescriptor.Name].Errors.Remove(error); bindingContext.ModelState[propertyDescriptor.Name].Errors.Add(errorMessage); break; } } </code></pre> <p>Add the function <code>bool IsFormatException(Exception e)</code> to check if an Exception is a FormatException:</p> <pre><code>if (e == null) return false; else if (e is FormatException) return true; else return IsFormatException(e.InnerException); </code></pre> <p>Create an Attribute class:</p> <pre><code>[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)] public class TypeErrorMessageAttribute : Attribute { public string ErrorMessage { get; set; } public string ErrorMessageResourceName { get; set; } public Type ErrorMessageResourceType { get; set; } public TypeErrorMessageAttribute() { } public string GetErrorMessage() { PropertyInfo prop = ErrorMessageResourceType.GetProperty(ErrorMessageResourceName); return prop.GetValue(null, null).ToString(); } } </code></pre> <p>Add the attribute to the property you wish to validate:</p> <pre><code>[TypeErrorMessage(ErrorMessageResourceName = "IsGoodType", ErrorMessageResourceType = typeof(AddLang))] public bool IsGood { get; set; } </code></pre> <p>AddLang is a resx file and IsGoodType is the name of the resource.</p> <p>And finally add this into Global.asax.cs Application_Start:</p> <pre><code>ModelBinders.Binders.DefaultBinder = new LocalizationModelBinder(); </code></pre> <p>Cheers!</p>
PSD to HTML (with text) conversion <p>I just downloaded a website template that is in a .PSD form. I have made the changes via photoshop, setup the splices then clicked "Save for web devices". </p> <p>I export the website and I get the images directory and the html file. All ok so far.</p> <p>I next open the html file using dreamweaver.</p> <p>My question is what is the best method to create the text content of the site. The images are all embedded at part of a table i.e.</p> <pre><code>&lt;tr&gt; &lt;td colspan="2" rowspan="8"&gt; &lt;img src="images/storage.jpg" width="28" height="118" alt=""&gt;&lt;/td&gt; &lt;td colspan="4" rowspan="5"&gt; &lt;img src="images/index_39.jpg" width="125" height="75" alt=""&gt;&lt;/td&gt; &lt;td colspan="4" rowspan="8"&gt; &lt;img src="images/storage-41.jpg" width="81" height="118" alt=""&gt;&lt;/td&gt; &lt;td&gt; &lt;img src="images/spacer.gif" width="1" height="3" alt=""&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>I set the image as the background to the table element however I am wondering what would be the best method for creating the text i.e. create a table in a table, or div etc?<br /> I dont know too much about css so if you have an example I would be grateful</p> <p>Also, are there are tools / websites out there that does this automatically for you?</p> <p>Thanks</p>
<p>Did your template only come with a PSD file?</p> <p>Typically, the PSD file allows you to edit the graphical portion, then save off the images you need, to be placed back in HTML, rather than generating HTML directly from the PSD.</p> <p>Since you asked for the <em>best</em> way to do this, I will give you my answer based on my opinion.</p> <p>Using tables for layout is not a good way to design webpages.</p> <p>Tables should be used for tabular data. </p> <p>You should place content in HTML, and use CSS for layout/presentation.</p> <p>If you want to learn about CSS, I suggest the following:</p> <ul> <li><a href="http://www.csszengarden.com/" rel="nofollow">CSSZen</a></li> <li><a href="http://htmldog.com/guides/cssbeginner/" rel="nofollow">HTMLDog</a></li> <li><a href="http://www.designmeme.com/articles/beginnercss/" rel="nofollow">DesignMeme</a></li> </ul> <p>If you have a Mac, I highly recommend downloading and trying out CSSEdit. For a PC, Visual Studio 2008 has a nice CSS editor as well.</p>
Need a php script diagnosis for a small snippet of code <p>Can somebody tell me what I am doing wrong really? I am going nuts, the following code works perfect on localhost/WIN and when I try it on the webhost/linux it gives warnings:</p> <pre><code>$lines = file('english.php'); foreach($lines as $line) { $matches=array(); if (preg_match('/DEFINE\(\'(.*?)\',\s*\'(.*)\'\);/i', $line, $matches)) { $keys[] = $matches[1]; $values[] = $matches[2]; } } $lang = array_combine($keys, $values); </code></pre> <p>When I test on webhost:</p> <pre><code>Warning: array_combine() expects parameter 1 to be array, null given in /home/xx/public_html/xx on line 616 </code></pre> <p>But on local server (windows xp) it works perfect. I do not know what I am doing wrong, please help me resolve this nightmare :(</p> <p>Thanks.</p>
<p>I don't see anything obviously wrong with your code, but I'm curious why you're building separate arrays and then combining them rather than just building a combined array:</p> <pre><code>// Make sure this file is local to the system the script is running on. // If it's a "url://" path, you can run into url_fopen problems. $lines = file('english.php'); // No need to reinitialize each time. $matches = array(); $lang = array(); foreach($lines as $line) { if (preg_match('/DEFINE\(\'([^\']*)\',\s*\'([^\\\\\']*(?:\\.[^\\\\\']*)*)\'\);/i', $line, $matches)) { $lang[$matches[1]] = $matches[2]; } } </code></pre> <p>(I've also changed your regex to handle single quotes.)</p>
Get resource file inside the application <p>i was wondering if i could access a folder inside the Resources folder of the application? i would make it to eliminate the use of the debug directory in storing files and to use the clickonce deployment.</p> <p>I need your advices and suggestions. Thank you.</p>
<p>You can change where the project outputs it's build to. Right click on the Project's name and click properties then go to Build and down near the bottom it tells you where it will output the build to. If you're building it in debug, it usually goes to bin\Debug, release goes to \bin\Release, etc.</p> <p>You can look <a href="http://www.15seconds.com/issue/041229.htm" rel="nofollow">here</a> for information on the ClickOnce deployment.</p>
How to access your website through LAN in ASP.NET <p>I have an asp.net web-page application and i want it to be accessed using a local area network(LAN) or wireless area network(WLAN).</p> <p>I do not know where to start. Is there something that i will configure in order for others to access my web-page?? </p> <p>I would really appreciate your answer, thanks a lot.. (^_^)...</p>
<p>I'm not sure how stuck you are:</p> <p><strong>You must have a web server</strong> (Windows comes with one called IIS, but it may not be installed)</p> <ol> <li>Make sure you actually have IIS installed! Try typing <code>http://localhost/</code> in your browser and see what happens. If nothing happens it means that you <strong>may</strong> not have IIS installed. See <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/750d3137-462c-491d-b6c7-5f370d7f26cd.mspx?mfr=true">Installing IIS (IIS 6.0)</a> </li> <li>Set up IIS <a href="http://support.microsoft.com/kb/323972">How to set up your first IIS Web site</a></li> <li>You may even need to <a href="http://www.microsoft.com/downloads/details.aspx?familyid=0856eacb-4362-4b0d-8edd-aab15c5e04f5&amp;displaylang=en">Install the .NET Framework</a> (or your server will only serve static html pages, and not asp.net pages)</li> </ol> <p><strong>Installing your application</strong></p> <p>Once you have done that, you can more or less just copy your application to <code>c:\wwwroot\inetpub\</code>. Read <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/fd7236aa-f429-4139-adc2-6834595d051f.mspx?mfr=true">Installing ASP.NET Applications (IIS 6.0)</a> for more information</p> <p><strong>Accessing the web site from another machine</strong></p> <p>In theory, once you have a web server running, and the application installed, you only need the <code>IP address</code> of your web server to access the application.</p> <p>To find your IP address try: <code>Start</code> -> <code>Run</code> -> type <code>cmd</code> (hit <code>ENTER</code>) -> type <code>ipconfig</code> (hit <code>ENTER </code>)</p> <p>Once you have the IP address AND IIS running AND the application installed you can access you website from another machine in your LAN by just typing in the IP Address of you web server and the correct path to your application. If you put your application in a directory called <code>NewApp</code>, you will need to type something like <code>http://your_ip_address/NewApp/default.aspx</code></p> <p><strong>Turn off your firewall</strong></p> <p>If you do have a firewall turn it off while you try connecting for the first time, you can sort that out later.</p>
Vertical center a TextFlow in GEF <p>I'm trying to vertical center a multiline textbox within a RectangleFigure in GEF. It needs to be ajusted on resize.</p> <p>This would be best done with a layout, but I can't figure out how that works.</p> <p>I'm adding a BorderMargin to the parent FlowPage and changing the margin when the RectangleFigure gets resized. Unfortunately, at that particular point, the TextFlow hasn't been layouted and it often no longer has the correct number of lines.</p> <p>Given that all I need is the number of lines, how can I calculate that.</p> <p>Alternatively, what does an "auto-centering" layout look like?</p>
<p>I'm not seeing an answer (yet) but I do have some questions:</p> <ul> <li>Can you post an example of your code so far?</li> <li>Messing with the parent BorderMargin to center is probably the wrong way to go. What happens if you don't do that?</li> <li>Are you doing invalidateTree() to force recomputation / layout?</li> <li>When you say "all you need is the number of lines," which object are you referring to and what are you intending to do with the answer?</li> </ul>
How to subscribe for an javascript event form Flex 3 action script code? <p>We have that Flex app talking to the server. We need some kind of *FlexEvent.ON_BROWSER_WINDOW_CLOSE* event but, unfortunately Flex does not provide such.</p> <p>So I've got the advice to catch a javascript "onbeforeunload" event and call the flash client thru the ExternalInterface-registred method.</p> <p>Is there any way to subscribe for a javascript event without any javascript code?</p> <p><strong>Update</strong> I'm want to do that is multiply flash app hosting pages. Certainly we could manage that by external javascript file, but it's unclear still...</p>
<p>You can use ExternalInterface to call Javascript functions defined in the container. See <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=19%5FExternal%5FInterface%5F06.html#126566" rel="nofollow">this</a>.</p> <p><a href="http://gregjessup.com/flex-3-catch-browser-exit-or-close-event-using-javascript-and-externalinterface/" rel="nofollow">This</a> post describes a situation similar to yours. Take a look.</p>
Is using a Mutex to prevent multiple instances of the same program from running safe? <p>I'm using this code to prevent a second instance of my program from running at the same time, is it safe?</p> <pre><code>Mutex appSingleton = new System.Threading.Mutex(false, "MyAppSingleInstnceMutx"); if (appSingleton.WaitOne(0, false)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); appSingleton.Close(); } else { MessageBox.Show("Sorry, only one instance of MyApp is allowed."); } </code></pre> <p>I'm worried that if something throws an exception and the app crashes that the Mutex will still be held. Is that true?</p>
<p>It is more usual and convenient to use Windows events for this purpose. E.g.</p> <pre><code>static EventWaitHandle s_event ; bool created ; s_event = new EventWaitHandle (false, EventResetMode.ManualReset, "my program#startup", out created) ; if (created) Launch () ; else Exit () ; </code></pre> <p>When your process exits or terminates, Windows will close the event for you, and destroy it if no open handles remain.</p> <p><em>Added</em>: to manage sessions, use <code>Local\</code> and <code>Global\</code> prefixes for the event (or mutex) name. If your application is per-user, just append a suitably mangled logged-on user's name to the event name.</p>
Catch tasks from windows task scheduler in a .net app <p>I have a program that is running in the background, this program has to be notified when a specific windows event is occurring.</p> <p>I know the name and id for the event and i know how to schedule an action for it in the task scheduler, but here i can only start a new program. I want to call a function in an already running application.</p> <p><strong>Edit:</strong> Solved it like this.</p> <p>The main program is listening for a TCP connection and from the task scheduler i start another instance of the program with a command line argument. If the program receives this argument it will connect to the main program that performs some action when it receives the connection.</p>
<p>I would have the scheduler start a new process (it could be the same application exe) and have this process set an event that the first process is waiting on. Seems pretty clean to me, especially if you have the scheduler launch the same application (maybe with a special command line).</p>
Strange temporary array corruption <p>I am attempting to create a permutation, and I receive this strange error when I finish my problem:</p> <pre><code>Stack around the variable "temp" was corrupted </code></pre> <p>the segment of the variable is within a nested for loop:</p> <pre><code>for(int i = 0 ; i &lt; str_length ; i++) { for(int j = 0 ; j &lt; str_length ; j++) { char temp[1]; temp[1] = text[i]; text[i] = text[j]; text[j] = temp[1]; cout &lt;&lt; text &lt;&lt; endl; } } </code></pre> <p>text is initialized outside of the for loop as a string, and I get the same error when i make temp[1] into a char or an int. The program works fine but I am concern why I am receive this error, does anyone know why?</p>
<p>You just need to use <code>char temp;</code> and acces it as <code>temp = text[i];</code>, etc.</p> <p>You're accessing a point on the stack one byte PAST temp, which is invalid. In this case, since you only want a single char, there's no need for an array at all.</p>
How can I implement an algorithm for multicore in Java? <p>Modern computers have more and more cores. We want to change our current linear algorithm to use these cores.</p> <p>A splitting of any algorithm to use different threads only makes sense if there is a free processor.</p> <p>Are there any good libraries that can help to parallelize some steps if there are free processors?</p> <p>I will give some examples.</p> <ul> <li>If there is only one processor it makes no sense to create multiple threads. It will reduce the speed.</li> <li>If there run 2 processes (requests on a server) on a core duo it make also no sense to start threads.</li> <li>If there only one process on a core duo it make sense.</li> </ul> <p>The abstract algorithm has 4 steps A, B, C and D. Steps A, B and C can execute parallel. Step D needs the results from A, B and C.</p> <p>Edit: I means an mathematic algorithm. No IO, No events, etc</p>
<p>This isn't necessarily true.</p> <p>Depending on the algorithm, it often makes sense to split it into multiple threads even if there is only a single core available. If there is any waiting on sockets, IO, etc, you can get benefits from this. If there are 2 processes, the "other" process may not be using 100% of the other core, so threading can help here. Trust your OS in this case to handle it correctly.</p> <p>You can always check the processor count with Runtime.availableProcessors() to determine how to split it into separate threads. Alternatively, you can use a threadpool, which should scale correctly with more processors.</p> <p>In general, though, I would design your algorithm to use more than one processor if the algorithm makes sense to parallelize. Most systems will have more cores/processors available, and you can always tweak your implementation later if you find it needs it. If the process is long running, the overhead of generating the thread will be worth it - if it's already fast, it may be more worthwhile looking at other places to optimize.</p>
Can I save data from the Visual Studio 2008 debugger? <p>I have an rare data-dependent error in some code. It's difficult to reproduce the conditions that generated the problematic data, so I need to be able to serialize the (fairly large) data that causes the error to disk to make a test case. Is there any way to serialize data from the debugger?</p>
<p>Is all the data that you want already in some serializable form? If so, you could use the Immediate window to create an appropriate serializer and write it to disk that way.</p> <p>If you need to do this reasonably regularly, and if you're after the data contained in a single object, you could add a method to that type to dump the data to disk given just a filename - and again, call that method from the Immediate window.</p>
send request with gwt to a different domain <p>Is there a way I can make a request to a different server than the one that's being used for development using a RequestBuilder?</p> <p>I keep getting </p> <pre><code>com.google.gwt.http.client.RequestPermissionException: The URL http://127.0.0.1:4321/getSellers is invalid or violates the same-origin security restriction </code></pre> <p>while I am sending request from 127.0.0.1:8888</p>
<p>GWT currently doesnt support cross domain ajax calls - but it can be worked around if you are willing to do a bit of jsni. And I heard a rumour some time ago that there is a gwt patch with the solution, but its not perfect. see this <a href="http://groups.google.com/group/Google-Web-Toolkit-Contributors/browse_thread/thread/94c18c4ec158070c/" rel="nofollow">http://groups.google.com/group/Google-Web-Toolkit-Contributors/browse_thread/thread/94c18c4ec158070c/</a></p> <p>to work around using jsni, you can use whats called the windows.name transport - see this blog <a href="http://www.sitepen.com/blog/2008/07/22/windowname-transport/" rel="nofollow">http://www.sitepen.com/blog/2008/07/22/windowname-transport/</a> . i havent been able to locate a library for gwt to automate this, but i dont think its too hard to do yourself in jsni (and dont me misled by the blog being about dojo, its a general technique). </p>
Window settings for Google Maps widget <p>I've got a plain-vanilla google maps widget sitting in a page and I'd like it if the driving directions opened up in a new window instead of taking over the current window. Is there a setting for this?</p>
<p>The driving directions go into whatever HTML element you specify as the second argument when you construct the GDirections object. So I guess that means you'd have to create the window before you create the GDirections object, which is likely not what you want.</p> <p>The other thing that jumps out, looking at the documentation, is that you can call the load() method with the option getSteps = true. It's not clear what the "steps" data looks like, but I assume it essentially comes back as an HTML string. (Actually, it's not even clear how you <em>get</em> the data in the first place, but I assume it's GDirections.getSteps() or something similar.) So then when the "load" event happens, you can create the new window then put the "steps" data in it.</p>
Where is the class assigned to when stored in a struct? <p>I read a thread (which had the input of Marc Gravell and Jon Skeet) that mentioned if a struct is in a class, that struct is stored on the heap like the class.</p> <p>What if a class is a member of a struct? Where does the class get assigned to?</p> <p>Thanks</p>
<p>If a class is a member of a struct, then only the <strong>reference</strong> is stored in the struct (i.e. the 32/64-bit address to the instance). The instance of a class is <strong>always</strong> on the heap.</p>
A site where users could make suggestion for my code? <p>Hi do you guys know a site where other programmers could make suggestions about the code that I make? I always think that the code I make could be better and I also wish someone could like mentor me or point out some bad habits that I make. I code in Java.</p>
<p>What's wrong with right here? Also there is <a href="http://www.refactormycode.com" rel="nofollow">refactor my code</a>.</p>
Cannot connect to X server :0.0 with a Qt application <p>Compiling on Fedora 10.</p> <p>I have just started my first qt GUI application. I used all the default settings.</p> <p>Its just a simple form. It builds OK without any errors. But when I try and run the application. I get the following message:</p> <pre><code>Starting /home/rob/projects/qt/test1/test1/test1... No protocol specified test1: cannot connect to X server :0.0 </code></pre> <p>Thanks for any advice,</p>
<p>The general causes for this are as follows: </p> <ol> <li><p>DISPLAY not set in the environment.<br /> <strong>Solution</strong>: </p> <pre><code>export DISPLAY=:0.0 ./myQtCmdHere </code></pre> <p>( This one doesn't appear to be the one at fault though, as its saying which X display its trying to connect to. Also, its not always 0.0, but most of the time it is )</p></li> <li><p>Non-Authorised User trying to run the X Application<br /> <strong>Solution</strong> ( as X owning user, ie: yourself )</p> <pre><code>xhost +local:root # where root is the local user you want to grant access to. </code></pre></li> </ol>
why does java's inputstream.close() block? <p>My Java program uses ProcessBuilder (with redirectErrorStream set true) and has a loop that runs the processes's inputstream's read method, which is blocking. The external program I'm calling then comes to a stop waiting for input and stdin. I now want to kill the process. Is this not done by (in a seperate thread) calling the process's destroy method, and calling the inputstream's close method to stop the read method from blocking anymore, so that my initial thread can end its life?</p> <p>For some reason <code>process.getInputStream().close()</code> blocks. From the JavaDoc I don't see why this can happen. Furthermore, I don't understand why the javadoc says "The close method of InputStream does nothing." (<a href="http://java.sun.com/javase/6/docs/api/java/io/InputStream.html#close%28%29" rel="nofollow">link to javadoc</a>) Could someone explain this?</p> <p>Thanks :-)</p>
<p>Regarding the blocking behavior, there is a known issue in Java that can cause deadlock when communicating with another process. I can't tell if this is what you're seeing but it's worth looking into. The document for <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Process.html" rel="nofollow">java.lang.Process</a> says:</p> <blockquote> <p>Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.</p> </blockquote>
What do you think of my simple Java class that encrypts text into SHA-1? <p>Anyway I'm starting out to make Java programs (a programming newb) and I've decide to do a simple utility class that converts text into SHA-1 strings. I'm planning on using this to encrypt passwords for databases. Feel free to comment and I'd love to learn from you guys. Here's my code:</p> <pre><code>/* * Utility class that encrypts a string created for storing passwords * into databases */ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * * @author mamamambo */ public final class Encryptor { // Salt for extra security private static String salt = "54L7"; private static String encrptionAlgorithm = "SHA-1"; private Encryptor() { } public static String encrypt(String str) { StringBuffer encryptedResult = new StringBuffer(); String strWithSalt = salt + str; try { MessageDigest md = MessageDigest.getInstance(encrptionAlgorithm); md.update(strWithSalt.getBytes()); byte[] digest = md.digest(); for (byte b : digest) { int number = b; // Convert negative numbers number = (number &lt; 0) ? (number + 256) : number; encryptedResult.append(Integer.toHexString(number)); } } catch (NoSuchAlgorithmException ex) { System.out.println(ex.toString()); } return encryptedResult.toString(); } } </code></pre>
<p>If you're using this to create hashed passwords why not just store the bytes directly in the database. The advantage is that you know the size of the field in advance. I also agree that if you're going to the effort of using salts then it makes sense to create and store a unique salt for each as this makes rainbow tables useless even if you know the salts (for example if your database and code becomes public). To create a random salt use code like this:</p> <pre><code>//declaracations at top of class static Random srnd; //static constructor static { srnd = new SecureRandom(); } //just before you need to use the salt byte[] salt = new byte[20]; srnd.nextBytes(salt); </code></pre> <p>Note that you should create the SecureRandom object outside of the method and cache it because it takes a while to initialise. Also there is no need to append the bytes of the salt to the string before calling update, simply call update twice with the salt in the first call and the password to be hashed in the second.</p> <p>Note that if you really do need the output as a string then I recommend using a Formatter to ensure that each number is 3 digits. Use code like this:</p> <pre><code>StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb); formatter.format("%03d", integerToOutput); String output = sb.toString(); </code></pre>
Is it possible to wait for methods that aren't in Threads to finish in Java? <p>I have an object which does some computation, then for each iteraction I want to draw what happens. While the drawing is happening, I want it to wait.</p> <p>This is what I did, basically:</p> <pre><code>synchronized public void compute() { other.mark(variable); try { wait(); } catch(InterruptedException e) { } } </code></pre> <p>in the OtherClass, I have</p> <pre><code>synchronized public void mark(int var) { //change some stuff repaint(); notify(); } </code></pre> <p>What happens is that compute() waits forever. I thought this was going to work, since no erros were given by the compiler. Neither class implements Runnable or extends Thread, so maybe that's the problem? I'm not sure since I figure I'd be warned if these objects couldn't use such methods.</p> <p>I'm thinking it might be an error regarding the logic of the program itself, but in a nutshell that's what I have.</p>
<p>Your question suggests that you want to perform some operation that updates the GUI state either when it is finished or notifies the GUI of its progress. This is what <a href="http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html" rel="nofollow">SwingWorker</a> was designed for. There are some examples on the linked javadoc for both cases.</p>
List all permutations of the numbers 1,...,n in lexicographic order <p>I'm trying to program a Matlab to list all permutations of the numbers 1 through n in lexicographic order. What I have so far is below. I am using recursion to try and write a program that will work for n=3 first, and then see if I can gain insight into writing the program for any n. So far I have 2 of the 6 columns for n=3: <code>P=[1 2 3;1 3 2]</code>. I need the next two columns to simply swap the ones and the twos. I don't know how to begin to do that. </p> <pre><code>function [P] = shoes(n) if n == 1 P = 1; elseif n == 2 P = [1 2; 2 1]; else T = shoes(n-1) + 1; G = ones(factorial(n-1),1); P(1:2,1:3) = [G T]; end </code></pre>
<p>See <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/perms.html" rel="nofollow">the documentation</a> for a start. If by lexicographical order you mean alphabetical by english name, you may want to populate your input with the names, sort them, then permute that.</p> <p>If I've misunderstood what you're wanting, comment or edit the question &amp; I'll check back later.</p> <p>Hints:</p> <ul> <li>The permutations of an empty list are easy to find.</li> <li>Induction is an important concept in mathematics. You should be familiar with it.</li> <li>The environment you are working in supports recursion </li> <li>The permutations of a longer list can be produced in the order you want by recursion; first figure out what you want the first element to be, and then figure out the rest.</li> </ul> <p>If you get stuck again, edit the question posting what you've gotten so far and where/why you think you're stuck.</p> <p>Hints after seeing your code.</p> <ul> <li>Your core function permutes a vector, and so should take a vector as argument, not an integer</li> <li>Don't start solving the n=3 case; try the n=0 case (it's []) and then go straight to the n=20 case.</li> <li>Think about the n=20 case before you write any code. What is the first column going to look like? Are there any examples of the n=19 case hidden in the answer to the n=20 case? (The answer is yes, and they are all different).</li> <li>Reread the first set of hints</li> </ul>
How do I get an Expression Blend Keyspline control? <p>I need a control in my C# program that behaves exactly the same as MS Expression Blend keyspline control - is there any way to get hold of that control and add it to my application? </p> <p>As a side note it'd be nice to use some of the other controls that appear in that applications as well</p>
<p>What do you mean by add it to your application? If you're developing a C# WPF application you can already add it using the Blend designer or programatically in Visual Studio.</p> <p>You can inherit from all the WPF controls to create new ones that enhance the behaviour if needed. If you simply want to customise the feel of a control you can use styles within Expression Blend. If you want to customise the complete look, feel and behaviour of a control you also have the option of templates.</p>
Opinion on Visual WebGui <p>I would like to hear your experiense with Gizmox Visual WebGui product. Thanks.</p>
<p>I've been looking at it for a few weeks on and off and I've been unable to find substantive information that doesn't originate from Gizmox itself. That combined with documentation that seems lacking at best makes me think it needs some more time before it should really be considered.</p>
Why does new Rails db migration file start with datestamp instead of sequence number? <p>Whenever I use script/generate to generate a new scaffold for a change to my Rails database, the new migration file is prepended by a datestamp (e.g. 200903140912_create_users.rb) instead of a sequence number (e.g. 004_create_users.rb).</p> <p>I then have to manually change the file name to fit in with the rest of the migration files.</p> <p>Does anyone know how to fix this?</p> <p>System: Mac OS X Leopard 10.5.6<br /> Rails: v2.2.2<br /> Ruby: v1.8.6 </p>
<p>This was introduced in Rails 2.1. According to the <a href="http://guides.rubyonrails.org/migrations.html#whatsinaname">migrations docs</a>, you can revert it by setting <code>config.active_record.timestamped_migrations</code> to <code>false</code> in <code>config/environment.rb</code>.</p>
Python: Abstract Base Class and ZopeInterface <p>What's the point of both? When do you think it's appropriate to use either?</p>
<p>There is an article <a href="http://griddlenoise.blogspot.com/2007/05/abc-may-be-easy-as-123-but-it-cant-beat.html">ABC may be easy as 123, but it can't beat zope.interface</a>, which goes into details comparing both and links to other documents.</p>
Clustered index insert performance on not-so-unique column? <p>In your experience, at about how many records does insert performance become intolerable when using a clustered index on not-typically-unique columns?</p> <p>A good example I can think of would be the comments table for stack overflow. Do you think that insert performance would be acceptable if the comments table had a clustered index on their foreign key to the answers or questions table? I'm assuming that this would result in the fastest read performance for the way that comments are typically queried.</p> <p>I often read that the clustered index should be reserved for uniquely-valued columns, but what if the table in question was most often queried by this index?</p>
<p>It Depends on:</p> <ul> <li>The size of the rows</li> <li>On Fill Factor (i.e. space left in the index)</li> <li>The number of non-clustered indexes on the table</li> <li>How often the index is reorganised (note: not so important when the clustered index is on a montonically increasing key)</li> </ul> <p>You should benchmark for your particular situation.</p>
Just what is 'A big database'? <p>Ok, dumb question I know but I see the nebulous comment 'a large database' as well as small and medium and I wonder just what that means. Can someone define what a small, medium and large database is for us SQL neophytes?</p>
<p>There isn't a threshold where a small database becomes medium or a medium database becomes large. Generally, when I hear these terms, I think of particular orders of magnitude in terms of total records being stored.</p> <ul> <li>Small: 10<sup>5</sup> or fewer records.</li> <li>Medium: 10<sup>5</sup> to 10<sup>7</sup> records. </li> <li>Large: 10<sup>7</sup> to 10<sup>9</sup> records.</li> <li>Very large: 10<sup>9</sup> or greater number of records. </li> </ul> <p>As poster <em>le dorfier</em> suggested, you could also think about it in terms of the properties each kind of database has. Categorizing it this way, I'd say:</p> <ul> <li><p>Small: Performance is not a concern. Your queries run fine without making any special optimizations. You see only a marginal performance difference when using front-line enhancements like indexes.</p></li> <li><p>Medium: Your database probably has one or more staff that are assigned part-time to its maintenance and care. These people pay attention to the database's health; their primary administrative responsibility is to prevent unacceptable performance problems and minimize downtime.</p></li> <li><p>Large: Probably has dedicated staff member(s) whose job is to work on the database and improve performance, as well as make sure that application changes don't cause schema breakage over the lifetime of the database. Metrics about the health and status of the database are monitored closely. Significant expertise is required to understand and perform optimizations.</p></li> <li><p>Very large: The database stores vast amounts of information that must be readily accessible. Performance optimizations are absolutely required to wring every last ounce of speed out of each queries, and without it, the database would be much less usable or even impossible to use. The database may be using sophisticated or innovative replication or clustering techniques, pushing the boundaries of current technology.</p></li> </ul> <p>Note that these are entirely subjective, and that someone may very well have a perfectly legitimate alternate definition of "large".</p>
Deleting a section of text from an RSS feed <p>Twitter's RSS feed displays names as: </p> <pre><code>&lt;name&gt;johnDoe (John Doe)&lt;/name&gt; </code></pre> <p>Is there a way to use php or javascript (preferably jquery) to delete everything starting with the first parentheses and after? I only want to show the username and not the username and the person's actual name.</p> <p>Other details: I'm parsing an RSS feed into a page using SimplePie</p>
<p>I would suggest parsing the RSS feed as usual then getting the value of the <code>&lt;name&gt;</code> element from your parsed structure, finding the index of the opening parenthesis, and trimming off everything from the previous index (i.e. the space) onwards. Something like</p> <pre><code>var nameStr = ...; // get the value of &lt;name&gt; var pIndex = nameStr.indexOf(" ("); if (pIndex) { // just make sure a parenthesis was in fact found nameStr = nameStr.substring(0, pIndex); } </code></pre>
Deep copying an NSArray <p>Is there any built-in function that allows me to deep copy an <code>NSMutableArray</code>?</p> <p>I looked around, some people say <code>[aMutableArray copyWithZone:nil]</code> works as deep copy. But I tried and it seems to be a shallow copy.</p> <p>Right now I am manually doing the copy with a <code>for</code> loop:</p> <pre><code>//deep copy a 9*9 mutable array to a passed-in reference array -deepMuCopy : (NSMutableArray*) array toNewArray : (NSMutableArray*) arrayNew { [arrayNew removeAllObjects];//ensure it's clean for (int y = 0; y&lt;9; y++) { [arrayNew addObject:[NSMutableArray new]]; for (int x = 0; x&lt;9; x++) { [[arrayNew objectAtIndex:y] addObject:[NSMutableArray new]]; NSMutableArray *aDomain = [[array objectAtIndex:y] objectAtIndex:x]; for (int i = 0; i&lt;[aDomain count]; i++) { //copy object by object NSNumber* n = [NSNumber numberWithInt:[[aDomain objectAtIndex:i] intValue]]; [[[arrayNew objectAtIndex:y] objectAtIndex:x] addObject:n]; } } } } </code></pre> <p>but I'd like a cleaner, more succinct solution.</p>
<p>As the <a href="https://developer.apple.com/library/mac/documentation/cocoa/conceptual/Collections/Articles/Copying.html#//apple_ref/doc/uid/TP40010162-SW3">Apple docs</a> state,</p> <blockquote> <p>If you only need a one-level-deep copy, you can explicitly call for one...</p> <pre><code>NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:oldArray copyItems:YES]; </code></pre> </blockquote> <p>The above code creates a new array whose members are shallow copies of the members of the old array.</p> <p>Note that if you need to deeply copy an entire nested data structure - what the linked Apple docs call a <em>"true deep copy"</em> - then this approach will not suffice - see the other answers here.</p>
How to refresh the windows desktop programmatically (i.e. F5) from C#? <p>Yeah, I know this seems like a dumb question, its just a one-off hack I need to wrap up a somewhat mundane task so I can move on to something more interesting.</p> <p>EDIT: Maybe more info would help: I'm trying to remove some shortcuts from the desktop and I need the user to see it removed right away (so they don't have to press F5).</p>
<p>You can use the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb762118(v=vs.85).aspx" rel="nofollow">SHChangeNotify</a> API.</p> <pre><code>[System.Runtime.InteropServices.DllImport("Shell32.dll")] private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2); </code></pre> <p>and then call it this way</p> <pre><code>SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero); </code></pre>
C# to C++/CLI to C DLL System.IO.FileNotFoundException <p>I'm getting <em><code>System.IO.FileNotFoundException: The specified module could not be found</code></em> when running C# code that calls a C++/CLI assembly which in turn calls a pure C DLL. It happens as soon as an object is instantiated that calls the pure C DLL functions.</p> <p>BackingStore is pure C. CPPDemoViewModel is C++/CLI calling BackingStore it has a reference to BackingStore.</p> <p>I tried the simplest possible case - add a new C# unit test project that just tries to create an object defined in CPPDemoViewModel . I added a reference from the C# project to CPPDemoViewModel .</p> <p>A C++/CLI test project works fine with just the added ref to CPPDemoViewModel so it's something about going between the languages.</p> <p>I'm using Visual Studio 2008 SP1 with .Net 3.5 SP1. I'm building on Vista x64 but have been careful to make sure my Platform target is set to x86.</p> <p>This feels like something stupid and obvious I'm missing but it would be even more stupid of me to waste time trying to solve it in private so I'm out here embarrassing myself!</p> <p>This is a test for a project porting a huge amount of legacy C code which I'm keeping in a DLL with a ViewModel implemented in C++/CLI.</p> <p><strong>edit</strong> After checking directories, I can confirm that the BackingStore.dll has not been copied.</p> <p>I have the standard unique project folders created with a typical multi-project solution.</p> <pre> WPFViewModelInCPP BackingStore CPPViewModel CPPViewModelTestInCS bin Debug Debug </pre> <p>The higher-level Debug appears to be a common folder used by the C and C++/CLI projects, to my surprise.</p> <p>WPFViewModelInCPP\Debug contains BackingStore.dll, CPPDemoViewModel.dll, CPPViewModelTest.dll and their associated .ilk and .pdb files</p> <p>WPFViewModelInCPP\CPPViewModelTestInCS\bin\Debug contains CPPDemoViewModel and CPPViewModelTestInCS .dll and .pdb files but <strong>not</strong> BackingStore. However, manually copying BackingStore into that directory <strong>did not fix the error.</strong></p> <p>CPPDemoViewModel has the property <em>Copy Local</em> set which I assume is responsible for copying its DLL when if is referenced. I can't add a reference from a C# project to a pure C DLL - it just says <em>A Reference to Backing Store could not be added.</em></p> <p>I'm not sure if I have just one problem or two.</p> <p>I can use an old-fashioned copying build step to copy the BackingStore.dll into any given C# project's directories, although I'd hoped the new .net model didn't require that.</p> <p>DependencyWalker is telling me that the missing file is GPSVC.dll which <a href="http://forums.guru3d.com/showthread.php?t=212244">has been suggested</a> indicates security setting issues. I suspect this is a red herring.</p> <p><strong>edit2</strong> With a manual copy of BackingStore.dll to be adjacent to the executable, the GUI now works fine. The C# Test Project still has problems which I suspect is due to the runtime environment of a test project but I can live without that for now.</p>
<p>Are the C and C++ DLLs in the same directory as the C# assembly that's executing?</p> <p>You may have to change your project output settings so that the C# assembly and the other DLLs all end up in the same folder.</p> <p>I've often used the <a href="http://www.dependencywalker.com/">Dependency Walker</a> in cases like this; it's a sanity check that shows that all the dependencies can actually be found.</p> <p>Once your app is running, you may also want to try out <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx">Process Monitor</a> on the code you are running, to see which DLLs are being referenced, and where they are located.</p>
Is the original Java ideal dead? <p>I feel that while I love J2ME and Java it's hypocritical of them to have two APIs for Java. Java was designed with "One code, many platforms" in mind, and now it's more like "One API for every OS, and one API for everything smaller than a netbook." I see a lot of J2ME emulators and such being ported to things like the PSP, and other consoles for homebrew, and I wonder why no one is doing this with normal Java. </p> <p>I'd love to write a game to play on my PC, than fire up a simple emulator and play the same game on the PSP, or the Dreamcast, but I can't. J2ME can't even run on a PC, you need an emulator for it, which reduces your market greatly. Plus most emulators are bulky, and not good.</p> <p>With super-phones like the IPhone coming out people are going to want more than little J2ME games, so if Java can't port their standard JRE to it they might find themselves missing the boat like Microsoft did with the netbook boom.</p> <p>It just feels like Sun needs to ether work on making the standard JRE smaller and more portable, or making J2ME available on the PC easily.</p>
<p>I think this should be a community Wiki</p> <p>But to the point, my view is that J2ME is going to die a horrible death and leave us with normal Java. The current Netbook trend combined with the more powerful smartphone trend means that your average cellphone today is much stronger than the machines that ran J2SE when it first came out. </p> <p>Hence, we can do away with J2ME, which was designed for ancient Nokias, and enjoy the standard Java on a smart doorknob (or a smartphone).</p> <p>The only problem that Java faces is that the biggest player in smartphone applications - Apple - isn't going to allow a JVM anytime in the foreseeable future.</p>
Resources for WinForms/WPF dev trying to learn ASP.NET <p>What are your best resources for a WinForms/WPF developer to come up to speed on ASP.NET? Will it take a complete paradigm shift for me to learn how to use ASP.NET or will it be a slight adjustment?</p> <p>I will award the answer flag to the post with a resource that gets me up to speed in the shortest amount of time. Downloadable code and code examples would be most helpful.</p>
<p><a href="http://www.asp.net/" rel="nofollow">The Official ASP.NET Site</a> has <a href="http://www.asp.net/Learn/" rel="nofollow">tutorials and videos</a></p> <p><a href="http://www.4guysfromrolla.com/" rel="nofollow">4 Guys From Rolla</a> is a great resource, as is <a href="http://weblogs.asp.net/scottgu/" rel="nofollow">Scott Guthrie's blog</a>.</p> <p>W3Schools has <a href="http://www.w3schools.com/ASPNET/default.asp" rel="nofollow">tutorials</a>.</p> <p>[There is quite a bit of a shift towards ASP.NET MVC, so I would suggest you look at that]</p>
Cocoa or Objective-C? <p>In regards to iPhone development, how do you now when your using a Cocoa vs pure Objective-C objects. For example, the following are Objective-C:</p> <ul> <li>NSTimer</li> <li>NSString</li> <li>int, float</li> <li>NSMutableArray</li> </ul> <p>But these are Cocoa:</p> <ul> <li>UILabel</li> <li>UIColor(?)</li> <li>UIView</li> </ul> <p>And to be clear, does</p> <p>Cocoa Touch == iPhone development</p> <p>Cocoa == Mac OS X development</p>
<p>You've got it a little wrong.</p> <p>NSTimer, NSString, NSMutableArray are all Cocoa. <code>int</code> and <code>float</code> are actually C, but since Objective-C is a strict superset of C, you are able to use them in your Objective-C code.</p> <p>Pure Objective-C requires linking only to the Objective-C runtime library and no other frameworks or libraries. Cocoa is a framework that includes things like NSObject and NSString. Other frameworks, like AppKit, extend the Cocoa framework.</p> <p>Coding in pure Objective-C usually means deriving from the root object called <code>Object</code> and not NSObject. Things like <code>@implementation</code>, <code>@interface</code>, <code>@selector</code> etc. are the Objective-C extensions to C and these are what are common in all Objective-C source, pure or not. If you want to code in pure Objective-C you cannot use anything other than your own objects derived from <code>Object</code>.</p> <pre><code>#import &lt;objc/Object.h&gt; </code></pre>
Converting an empty string into nil in Ruby <p>I have a string called <code>word</code> and a function called <code>infinitive</code> such that<br /> <code>word.infinitive</code> would return another string on some occasions and an empty string otherwise<br /> I am trying to find an elegant ruby one line expression for the code-snippet below </p> <pre><code>if word.infinitive == "" return word else return word.infinitive </code></pre> <p>Had infinitive returned nil instead of "", I could have done something like</p> <pre><code>(word.infinitive or word) </code></pre> <p>But since it does not, I can't take advantage of the short-circuit OR<br /> Ideally I would want<br /> 1) a single expression that I could easily embed in other code<br /> 2) the function infinitive being called only once<br /> 3) to not add any custom gems or plugins into my code</p>
<p>The ActiveSupport <a href="http://guides.rubyonrails.org/active_support_core_extensions.html#presence"><code>presence</code></a> method converts an empty (or <code>blank?</code>) string to <code>nil</code>. It's designed for your exact use case:</p> <pre><code>word.infinitive.presence || word </code></pre> <p>Note that you can easily use ActiveSupport outside of rails:</p> <pre><code>require 'active_support/core_ext/object/blank' </code></pre>
Showing a Splash Screen during script execution <p>I want to know how to show a splash screen (like a gif or jpeg file) on the user screen during my script execution.</p> <p>Thank you for your help. </p>
<p>The trick is to let the rendering re-paint after the splash display is enabled before coninuing with long running JS. To do that you can use the setTimeout method.</p> <p>For example assuming you splash display is in a div with display style none you can use this function to run you code:-</p> <pre><code>function splash(splashDivId, fn) { var splashDiv = document.getElementById(splashDivId) splashDiv.style.display = "block"; setTimeout(function() { fn() splashDiv.style.display = "none"; }, 100); } </code></pre> <p>Usage:-</p> <pre><code>splash("mySplashDiv", longRunner) function longRunner() { //This may take a while } </code></pre>
How do I forward a complete email without downloading attachments? <p>Hello (and thanks in advance!)</p> <p>I'm working in Python and I got IMAP and SMTP to work with my Gmail account. I now need to forward select messages to another account (after reading their body).</p> <p>How do I do this without downloading the attachments and recreating the entire message?</p> <p>Thanks!</p> <p>Tal.</p>
<p>Look at the IMAP and SMTP Lemonade extensions. There is support for forwarding messages without downloading. It's a very new extension, so not many IMAP servers support it yet; I'm not sure if Gmail is one of them.</p> <p>Section 2 of <a href="ftp://ftp.rfc-editor.org/in-notes/rfc4550.txt" rel="nofollow">RFC 4550</a> contains the technical details on how this works.</p>
Does qt 4.5 have any skins? <p>I am developing for the first time using qt 4.5. I am developing a desktop app that will run on windows xp/vista.</p> <p>The client would like to have a skin that assemblies a softphone, or something similar. </p> <p>Does qt come with any skinning engine? Is it possible to create skins using qt?</p> <p>Many thanks,</p>
<p>Yes, you can write <a href="https://doc.qt.io/qt-5/stylesheet.html" rel="nofollow">style sheets</a> to customize the look of your application. The syntax is like CSS and gives you many possibilities. If you just want all your buttons to be red, for example:</p> <pre><code>QPushButton { color: red; } </code></pre>
Applications for using couchDB and a RDBMS together <p>Wondering if there was a scenario where one would use a document-based DB and a relational DB together in a best-of-both-worlds scenario? </p>
<p>One idea is to use a relational database as the main data store and a document-based db as a data distribution mechanism from the back end to the front end(s).</p>
.NET Equivalent for Hotkey Control <p>What is the .NET equivalent for the <a href="http://msdn.microsoft.com/en-us/library/bb775233%28VS.85%29.aspx" rel="nofollow">Hotkey Control</a>?</p>
<p>There is no implementation of HotKey Control in .Net but u can create a Custom control deriving from TextBox. One such implementation available to steal is <a href="http://www.codeproject.com/KB/buttons/hotkeycontrol.aspx" rel="nofollow">here</a></p>
Anyone recommends 'Pure Variants' for Software Product Lines generation? <p>Dear all, I am working on a software product line for online-tests automatic builds in coordination with my professor. He recommended for me "Pure Variants" as an open source tool which can be used as a plugin to Eclips. However, I am not really sure whether to go for it or search for other ones. So if you recommend this tool, then please tell me why you think so, or suggest for me another one you find better! Thanks </p>
<p>In fact pure::variants isn't open source but there is a Community edition for personal use. I think you should do a search though as learning to do this well could help your future academic career but you will only find one other tool specifically developed for <em><a href="http://www.software-acumen.com/about-product-lines/" rel="nofollow">software product line</a></em> development.</p>
Python - test that succeeds when exception is not raised <p>I know about <code>unittest</code> Python module.</p> <p>I know about <code>assertRaises()</code> method of <code>TestCase</code> class.</p> <p>I would like to write a test that succeeds when an exception is <strong>not</strong> raised.</p> <p>Any hints please?</p>
<pre><code>def runTest(self): try: doStuff() except: self.fail("Encountered an unexpected exception.") </code></pre> <p>UPDATE: As liw.fi mentions, the default result is a success, so the example above is something of an antipattern. You should probably only use it if you want to do something special before failing. You should also catch the most specific exceptions possible.</p>
Set the icon of a Flex button with a Sprite in runtime <p>I want to set the icon of a button in flex.</p> <p>The default syntax is as follows.</p> <pre><code>myButton.setStyle("icon", iconClass); </code></pre> <p>and iconClass is normally an embedded object.</p> <p>But what I want to do is, use a standard <strong>Sprite or a MovieClip</strong> (which I find during runtime) as the icon.</p> <p>Is this possible? Has anyone done this?</p> <p>Thanks!</p>
<p>This is actually a fatal flaw in Flex's framework in regards to styling. When Flex grabs a style value for an icon it assumes it's of type <code>Class</code> and that the instantiated object will be of type <code>DisplayObject</code> (or derived). It's a trivial change to the code (which classes like <code>mx:Image</code> do for their source property) to test whether or not the style's value is of type <code>DisplayObject</code> and if so, just skip the construction step that it currently performs.</p> <p>Ben's solution is the best possible if you won't want to change the Flex framework source. Personally, I end up monkey-patching the specific components to accept instantiated <code>DisplayObjects</code> instead of <code>Classes.</code> Some components are more of a pain than others to patch.</p> <p><a href="http://dougmccune.com/blog/2008/02/21/monkey-patching-flexsprite-to-list-all-event-listeners-on-any-flex-component/" rel="nofollow">Doug McCune explaining how to monkey patch the Flex framework.</a></p>
How to properly release and switch views in multiview controller? <p>I'm trying to create a multiview controller for a game, in which one root view controller releases views before switching to another view. The sub view controllers are, in turn, sub-root view controllers themselves since they contain other view controllers.</p> <p>For instance, my singlePlayerViewController will have a shakeObjectViewController and possibly others. Using actionsheets to switch between the views, with the app delegate as the actionsheet's delegate, everything works as expected when going from singlePlayer view to another.</p> <p>But when I attempt to create a new singlePlayerViewController using the same init methods, the debugger throws me a EXC<code>_BAD</code>_ACCESS error when I try to insert a subview, namely shakeObjectViewController.view.</p> <p>Initialization looks like this at the moment: The app delegate initializes the window with the default init method,</p> <pre><code>- (void)applicationDidFinishLaunching:(UIApplication *)application { // Override point for customization after application launch [window addSubview:rootViewController.view]; [window makeKeyAndVisible]; } </code></pre> <p>Then in the rootViewController.m's viewDidLoad,</p> <pre><code> if(singlePlayerViewController == nil) { SinglePlayerViewController *singleController = [[SinglePlayerViewController alloc] initWithNibName:@"SinglePlayerView" bundle:nil]; self.singlePlayerViewController = singleController; [singleController release]; } [self.view insertSubview:singlePlayerViewController.view atIndex:0]; </code></pre> <p>Followed by singlePlayerViewController.m,</p> <pre><code>- (void)viewDidLoad { self.view.tag = kSinglePlayerView; // tag the view ShakeObjectViewController *shakeController = [[ShakeObjectViewController alloc] initWithNibName:@"ShakeObjectView" bundle:nil]; self.shakeObjectViewController = shakeController; self.view = shakeController.view; [shakeController release]; } </code></pre> <p>Note how my singlePlayerViewController is not inserting subviews, but is instead replacing its own view with a sub-view controller's view. (Don't know if this is a good practice or not :?: )</p> <p>When switching views, the app delegate performs the following:</p> <pre><code>for(UIView *subview in [rootViewController.view subviews]) { [subview removeFromSuperview]; } [rootViewController.singlePlayerViewController release] [rootViewController initMultiplayerView]; </code></pre> <p>Then when switching back to single player mode, the same init method in rootViewController.m's viewDidLoad is executed, and the debugger throws the error on the "[self.view insertSubview:singlePlayerViewController.view atIndex:0];" line.</p> <p>Any ideas as to why a new view isn't being created? I've tried setting the singlePlayerViewController to nil instead of releasing, but then the error is thrown on the "self.view = shakeController.view;" line. It was my understanding that if the view property is currently nil, a new one is created automatically for you upon the next access to the view.</p> <p>Is initWithNibName only meant to be executed once? Or is my design way too convoluted in terms of # view controllers?</p>
<blockquote> <p>Note how my singlePlayerViewController is not inserting subviews, but is instead replacing its own view with a sub-view controller's view. (Don't know if this is a good practice or not :?: )</p> </blockquote> <p>Huge warning flag here. It sounds like you have one view with two view controllers. This is bad. </p> <p>Consider inserting and removing subviews instead: </p> <ul> <li>RootView <ul> <li>SinglePlayerView (can be removed and replaced with MutliplayerView) <ul> <li>ShakeView</li> </ul></li> </ul></li> </ul> <p>This way you have 3 view with 3 view controllers.</p> <p>It's the way the framework was meant to be used.</p>
Get User Input From Dynamic Controls <p>I am looking to create a dynamic survey. Where I generate all the question controls from the database. Below is an example of what I am trying to do (without the database part). I am able to display questions as seen below. I am unable to read the users input. </p> <p>Does anyone have any ideas. </p> <p>I have looked into the viewstate, but I can not seem to get it to work.</p> <p>When the page is reloaded through a Post Back the controls are gone. I have looked at every event I can think of and there are no controls on the page. Until I create them again on the Page_Load event. </p> <p>Where do I look to find the value of the user input on dynamicly created controls? </p> <p>Page</p> <pre><code>&lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p>Code File</p> <pre><code> protected override void OnPreLoad(EventArgs e) { base.OnPreLoad(e); foreach (Control item in form1.Controls) { } } protected void Page_PreInit(object sender, EventArgs e) { foreach (Control item in form1.Controls) { } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); foreach (Control item in form1.Controls) { } } protected override void OnSaveStateComplete(EventArgs e) { base.OnSaveStateComplete(e); foreach (Control item in form1.Controls) { } } protected override void OnInit(EventArgs e) { base.OnInit(e); foreach (Control item in form1.Controls) { } } protected void Page_Load(object sender, EventArgs e) { RadioButton rb; rb = new RadioButton(); rb.ID = "rb_1"; rb.Text = "yes"; rb.GroupName = "question"; form1.Controls.Add(rb); rb = new RadioButton(); rb.ID = "rb_2"; rb.Text = "no"; rb.GroupName = "question"; form1.Controls.Add(rb); rb = new RadioButton(); rb.ID = "rb_3"; rb.Text = "other"; rb.GroupName = "question"; form1.Controls.Add(rb); TextBox tb = new TextBox(); form1.Controls.Add(tb); Button btn = new Button(); btn.Text = "Save"; form1.Controls.Add(btn); foreach (Control item in form1.Controls) { } } </code></pre>
<p>You have to generate the controls with an unique id. You must be able to math each control-id with exactly one question in your database. After doing this, you are able to write back the answer to a specific question into a datbase.</p>
How do I create an instance from a string in C#? <p>I'm reading information from an XML which contains the type of an object that I need to instantiate along with it's constructor parameters.</p> <p>The object type is actually in another project, within a sibling namespace. (I need to create a Company.Project2.Type within Company.Project1 class.)</p> <p>I found <a href="http://stackoverflow.com/questions/223952/c-create-an-instance-of-a-class-from-a-string">this question</a>, but it doesn't handle the constructor parameters or the fact that it's in another namespace.</p> <p>How can I do this?</p> <p><strong>Edit:</strong> The assembly name and default namespace wasn't set correctly in the project properties.</p>
<ul> <li>You need to specify the full type name to <a href="http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx"><code>Type.GetType()</code></a>, including namespace, e.g. "Company.Project2.Type"</li> <li>If the type isn't in the same assembly (or mscorlib), you need to give the assembly name too, including version information if it's strongly typed. For example, for a non-strongly typed assembly <code>Company.Project2.dll</code>, you might specify "Company.Project2.Type, Company.Project2".</li> <li>To call a constructor with parameters you can call <a href="http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx"><code>Activator.CreateInstance(Type, Object[])</code></a> or get the exact constructor you want with <a href="http://msdn.microsoft.com/en-us/library/system.type.getconstructor.aspx"><code>Type.GetConstructor()</code></a> and then call <a href="http://msdn.microsoft.com/en-us/library/system.reflection.constructorinfo.invoke.aspx"><code>ConstructorInfo.Invoke()</code></a>.</li> </ul> <p>If that doesn't help, please give more information.</p>
Regex: How to match a string that contains repeated pattern? <p>Is there a regex pattern that will match a string that contains repeated pattern, e.g.:</p> <pre>"a"|"b","c"|"d",...,"y"|"z"</pre> <p>Do you have any idea?</p>
<p>Maybe you are looking for something like this:</p> <pre><code>^"."\|"."(,"."\|".")*$ </code></pre> <p>This will match a comma-separated list of sequences of form <code>"</code><em>α</em><code>"|"</code><em>β</em><code>"</code> where <em>α</em> and <em>β</em> can be any character.</p>
Implementing an Application in PL/SQL <p>We're developing a web application which according to my spec must have the backend written entirely in PL/SQL (stored procs etc.). Anyone have any advice/links on how to write a well structured backend using stored procedures and custom types? Normally I would have a business layer where all this would happen but what the employer wants the employer gets and so on. </p>
<p>You can <strong>still</strong> have a business layer - it's just that you are writing it in PL/SQL instead of some other language.</p> <p>A typical PL/SQL business layer would use packages for each major area of functionality, with appropriate procedures and functions in it e.g. </p> <pre><code>create package employees_pkg as procedure hire_employee (p_id integer, p_name varchar2, p_start_date date, ...); procedure terminate_employee (p_id integer, p_end_date date); ... end; </code></pre> <p>These packages can perform DML directly against the tables, though some (not I) would advocate a "table API" layer below this so that employees_pkg.terminate_employee would call "employee_tapi.update(...)" instead of "UPDATE employees...", which seems pointless to me.</p> <p>Custom types have their uses, but I wouldn't go overboard and try to build an OO layer in PL/SQL.</p> <p>You don't say what your client application is built with, but <a href="http://apex.oracle.com/i/index.html" rel="nofollow">Oracle Application Express</a> would be a great choice for a web-based Oracle database application.</p>
How to: Back button support "Ajax" <p>I have an asp.net ajax website, it full of things happen on the same page without page reload, such as sorting records, paging,... When the user go to another page in the same site and press the browser back button, how can i make the browser save the page state to return to it with the preselected options such as sorting option, page number in the paging.</p> <p>I knew that there is a history control in the new .net 3.5 but its working in the same page not while navigating from a page to another. Also i am looking for a solution which work in all browsers.</p> <p>Thanks,</p>
<p>You dont need 3.5 for the history control, <a href="http://weblogs.asp.net/scottgu/archive/2006/09/14/Tip%5F2F00%5FTrick%5F3A00%5F-Enabling-Back%5F2F00%5FForward%5F2D00%5FButton-Support-for-ASP.NET-AJAX-UpdatePanel.aspx" rel="nofollow">check ScottGu's blog here</a></p> <p>Also check if <a href="http://geekswithblogs.net/frankw/archive/2008/10/29/enable-back-button-support-in-asp.net-ajax-web-sites.aspx" rel="nofollow">this article helps</a></p>
What's the point of using Amazon SimpleDB? <p>I thought that I could use SimpleDB to take care of the most challenging area of my application (as far as scaling goes) - twitter-like comments, but with location on top - till the point when I sat down to actually start implementing it with SDB.</p> <p>First thing, SDB has a 1000 bytes limitation per attribute value, which is not enough even for comments (probably need to break down longer values into multiple attributes). </p> <p>Then, maximum domain size is 10GB. The promise was that you could scale up without worrying about database sharding etc., since SDB will not degrade with increasing loads of data. But if I understand correctly, with domains I would have exactly the same problem as with sharding, ie. at some point need to implement data records' distribution and queries across domains on application level.</p> <p>Even for the simplest objects that I have in the whole application, ie. atomic user ratings, SDB is not an option, because it cannot calculate an average within the query (everything is string based). So to calculate average user rating for an object, I would have to load all records - 250 at a time - and calculate it on application level.</p> <p>Am I missing something about SDB? Is 10GB really that much of a database to get over all SDB limitations? I was honestly enthusiastic about taking advantage of SDB, since I use S3 and EC2 already, but now I simply don't see a use case.</p>
<p>I use SDB on a couple of large-ish applications. The 10 GB limit per domain does worry me, but we are gambling on Amazon allowing this to be extended if we need it. They have a request form on their site if you want more space.</p> <p>As far as cross domain joins, don't think of SDB as a traditional database. During the migration of my data to SDB, I had to denormalize some of it so I could manually do the cross domain joins. </p> <p>The 1000 byte per attribute limitation was tough to work around also. One of the applications I have is a blog service which stores posts and comments in the database. While porting it over to SDB, I ran into this limitation. I ended up storing the posts and comments as files in S3, and read that in my code. Since this server is on EC2, the traffic to S3 isn't costing anything extra.</p> <p>Perhaps one of the other problems to watch out for is the eventual consistency model on SDB. You can't write data and then read it back with any guarantee that the newly written data will be returned to you. Eventually the data will be updated.</p> <p>All of this said, I still love SDB. I don't regret switching to it. I moved from a SQL 2005 server. I think I had a lot more control with SQL, but once giving up that control, I have more flexibility. Not needing to pre-define the schema is awesome. With a strong and robust caching layer in your code, it's easy to make SDB more flexible.</p>