instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I am calling 4-5 scripts from a file at once. But I need to give only one input to the file in the first sql that I am calling.</p> <p>That input will be the input for all the other sql files I have called after the first one.</p> <p>Is there any way to do that?</p> <p>please help.</p>
<p>I think you can achieve what you want by using the <a href="http://msdn.microsoft.com/en-us/library/ms162773.aspx" rel="nofollow noreferrer">sqlcmd</a> utility and <a href="http://msdn.microsoft.com/en-us/library/ms188714.aspx" rel="nofollow noreferrer">scripting variables</a>. The last link states that you can also use environment variables.</p>
<p>Do you mean:</p> <p>query2 is based on the result of query1, query3 is based on the result of query2 etc...</p> <p>If so, you can use views to </p> <pre><code>create view view1 as select * from table1; create view view2 as select * from view2; create view view3 as select * from view3; create view view4 as select * from view4; select * from view4 </code></pre> <p>Of course you have to add the where clause yourself.</p> <p>See for more on views <a href="http://dev.mysql.com/doc/refman/5.0/en/create-view.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/create-view.html</a></p>
47,333
<p>In a MVC application, what are some of the components that make up the application. What tools and functionality is missing that you would like to have. Regardless of the server-side language, what would you want?</p> <p>I see a lot in my code where I code some much functionality that it seems should already be there. I looked at Google web toolkit and they seem to get it right. Widgets are widgets and you simply add them to your application.</p> <p>For example. I work with J2EE apps but in other languages, the components are the same.</p> <ol> <li>Controller Objects</li> <li>Controller handlers, defined by methods in the controller objects.</li> <li>Configuration files defining the URL mapping and settings.</li> <li>Template server page files (e.g. JSP/ASP files).</li> <li>Configuration files defining O/RM mapping between application objects and the database.</li> <li>Configuration files defining the database connection properties.</li> <li>JavaScript libraries (e.g. jQuery)</li> <li>Logging configuration files</li> <li>Resource message bundle files</li> <li>Validation configuration files or code</li> <li>Middleware components and objects (EJB configurations, JMS/Messaging configurations, etc).</li> <li>Credit Card or other middleware connectivity APIs and libraries.</li> </ol> <p>Anything else you can think of?</p>
<p>Built-in Unit Testing Component </p>
<p>I think one thing you're missing from that very exhaustive list is the automatic binding of request properties to form objects, and the saving of these objects to the session where appropriate. Form objects here being the object on the server that represents the current state of the HTML-based for displayed to the user.</p>
29,136
<p>Can anyone tell me how to write a nested SQL query like </p> <p>SELECT * FROM X WHERE X.ID IN (SELECT Y.XID FROM Y WHERE .....)</p> <p>in LINQ?</p>
<p>You could try:</p> <pre><code>var yIds = from y in dataContext.Y where ... select y.XId; var query = from x in dataContext.X where yIds.Contains(x.Id) select x; </code></pre> <p>I don't know whether it will work though - any reason why you don't want to just do a join instead? For instance:</p> <pre><code>var query = from x in dataContext.X join y in dataContext.Y.Where(...) on x.Id equals y.Xid select x; </code></pre>
<p>To do an IN in sql, you need to use the Contains function in Linq.</p> <p>So for example:</p> <pre><code>var query = from x in GetX() where (from y in GetY() select y.xID).Contains(x.xID) select x; </code></pre> <p>You could also define the inner linq query seperately if you like, which is a bit more readable</p>
48,010
<p>I'm looking to have windows recognize that certain folders are associated to my application - maybe by naming the folder 'folder.myExt'.</p> <p>Can this be done via the registry?</p> <p>A bit more info<br> - This is for a x-platform app ( that's why I suggested the folder with an extension - mac can handle that ) <br> - The RAD I'm using doesn't read write binary data efficiently enough as the size of this 'folder' will be upwards of 2000 files and 500Mb</p>
<p>Folders in Windows aren't subject to the name.extension rules at all, there's only 1 entry in the registry's file type handling for "folder" types. (If you try to change it you're going to have very, very rough times ahead)</p> <p>The only simple way to get the effect you're after would be to do what OpenOffice, MS Office 2007, and large video games have been doing for some time, use a ZIP file for a container. (It doesn't have to be a "ZIP" exactly, but some type of readily available container file type is better than writing your own) Like OO.org and Office 2K7 you can just use a custom extension and designate your app as the handler. This will also work on Macs, so it can be cross-platform. It may not be fast however. Using low or no compression may help with that.</p>
<p>You can have an "extension" on your folder, but as far as I know, windows just treats it all as the folder name and opens the folder like normal when you click on it.</p> <p>The few times I messed with opening a .app on my windows system, it acted like it was a normal folder.</p>
9,353
<p>I need to write a Stored procedure in SQL server whose data returned will be used to generate a XML file.</p> <p>My XML file to be in structure of </p> <pre><code>&lt;root&gt; &lt;ANode&gt;&lt;/ANode&gt; &lt;BNode&gt;&lt;/BNode&gt; &lt;CNode&gt; &lt;C1Node&gt; &lt;C11Node&gt;&lt;/C11Node&gt; &lt;C12Node&gt;&lt;/C12Node&gt; &lt;/C1Node&gt; &lt;C2Node&gt; &lt;C21Node&gt;&lt;/C21Node&gt; &lt;C22Node&gt;&lt;/C22Node&gt; &lt;/C2Node&gt; &lt;C3Node&gt; &lt;C31Node&gt;&lt;/C31Node&gt; &lt;C32Node&gt;&lt;/C32Node&gt; &lt;/C3Node&gt; &lt;/CNode&gt; &lt;/root&gt; </code></pre> <p>My question is, in the stored procedure we can select values for ANode and BNode as a simple SELECT statement like</p> <pre><code>Select ANodeVal,BNodeVal from Table </code></pre> <p>But how to design the stored procedure to get records for the CNode which is a subtree which has 3 or more(dynamic) separate nodes in it for each record in addition to the normal ANode and BNode.</p>
<p>See</p> <p>&nbsp; &nbsp; <a href="https://stackoverflow.com/questions/147897/in-sql-server-can-i-insert-multiple-nodes-into-xml-from-a-table#148877">Nesting XML-returning scalar valued functions</a> </p> <p>Once you get the hang of the nesting, and are willing to write the number of scalar-valued functions necessary to construct the node segments from the bottom up (I wouldn't want lots of these laying around), then it's not so hard. </p>
<p>If you are able to modify the database design, consider keeping each node as a record, instead of as a column (as the sample select statement would indicate).</p> <p>For example, each row might include the following fields:</p> <ul> <li>RowId</li> <li>ParentRowId</li> <li>Name</li> <li>RowData</li> </ul> <p>I'm assuming that you are passing the data to an application befcause you indicated that the returned data will be used to generate the XML. In which case the Stored Procedure would simply be a <code>SELECT</code> statement, leaving the formatting to the application.</p> <p>Most implementations of XML engines should allow you to add child nodes to existing parent nodes. The XML is built in memory and then "exported" by whatever method necessary to get the desired final result.</p>
34,076
<p>I'm struggling with Visual Studio 2008. I've used some form of "Zen" colors for more than I can remember. In VS2008 I keep getting one color that I cannot read and I have been unable to identify it; the purpose of the question is to avoid trial an error (the VS color interface is really ugly with no "real time" apply button).</p> <p>If you look at the following picture, I'm debugging and the function on top has called the function below. The problem is that the calling line in upper function turns white (background) and is hard to read. </p> <p>The question is: Does anybody know what exact setting will allow me to change that?</p> <p>Thanks in advance. </p> <p><img src="https://i.stack.imgur.com/mb5Bi.jpg" alt="Sshot"></p>
<p>This describes the meaning of all those color options.</p> <p>I think the one you are looking for is "Call Return"</p> <p><a href="http://msdn.microsoft.com/en-us/library/kw7t0545.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/kw7t0545.aspx</a></p>
<p>I think that's your Call Return, under Text Editor.</p>
28,497
<p>I'm trying to use NAnt/NAntContrib build script to build a web application on Windows 2008 (IIS 7.0).</p> <p>In the build file, there is mkiisdir task, which fails with:</p> <p>[mkiisdir] The webservice at 'localhost' does not exist or is not reachable.</p> <p>All the documents/posts I found so far (non for w2k8, only Vista) say to install IIS 6 Compatibility services (all of them, including scripting tools, etc.) So I did, but it still throws this error.</p> <p>Any idea what else need to be changes, so NAnt be able to create/delete virtual directories on IIS 7.0?</p> <p>EDIT: New data - when I log in as local administrator to this server, the nant task succeeds, but it fails when I log in as a domain admin. I have added the domain admins group in the local Administrators group, but it still fails. Any idea what other permissions I need to check/change in order to make my domain admin user to be able to execute this task? I can create manually virtual folders without any problems.</p>
<p>To answer my own question - I have isolated the part of the code in NantContrib which was causing the problem, and made a sample application to test.</p> <p>I have posted this as a separate question <a href="https://stackoverflow.com/questions/263552/directoryentrynativeobject-throws-access-denied-for-a-user-in-administrators-gr">here</a>, and there is the <a href="https://stackoverflow.com/questions/263552/directoryentrynativeobject-throws-access-denied-for-a-user-in-administrators-gr#263784">solution</a> as well.</p> <p>Cheers</p>
<p>In order to get iis nantcontrib tasks to work you need to install IIS6 Management Compatibility Tools. Here is the blog describing how to do it in Vista:</p> <p><a href="http://thoughtworker.in/2008/01/15/nant-the-webservice-at-localhost-does-not-exist-or-is-not-reachable/" rel="nofollow noreferrer">http://thoughtworker.in/2008/01/15/nant-the-webservice-at-localhost-does-not-exist-or-is-not-reachable/</a></p> <p>Here is a screenshot of how to do it in Windows Server 2008:</p> <p><a href="http://img407.imageshack.us/img407/699/iis6tools.png" rel="nofollow noreferrer">alt text http://img407.imageshack.us/img407/699/iis6tools.png</a></p>
32,573
<p>Wnen I use external resources such as files or DB connection I need to close them before I let them go.</p> <p>Do I need to do the same thing with Swing components ? If yes then how ?</p>
<p>Normally, you don't need to dispose of objects when you are done with them (although setting the references to them to null may allow them to be GCed sooner). However, AWT and Swing objects allocate some amount of native resources that need to be freed. Furthermore, the AWT thread treats the windows as top-level objects, preventing them from being garbage collected and the JVM from terminating.</p> <p>Thus, when you are done with your window, you need to dispose of it, which frees the native resources that it has allocated. One way to do this is to call <a href="http://java.sun.com/javase/6/docs/api/java/awt/Window.html#dispose()" rel="noreferrer">Window.dispose</a>() on it. However, a better option would be to call <a href="http://java.sun.com/javase/6/docs/api/javax/swing/JFrame.html" rel="noreferrer">JFrame.setDefaultCloseOperation</a>() when you initialize each of your root windows. If you pass it DISPOSE_ON_CLOSE it will take care of disposing itself when the user closes the window. When the last such window closes, the AWT thread will stop blocking and allow the JVM to close (assuming you don't have any other aberrant threads running). Alternatively, you can pass it EXIT_ON_CLOSE, which will cause your window to call System.exit(), which tells the JVM that your application is done and to gracefully terminate.</p>
<p>Objects are automatically garbage collected if there are no references to them. You do not have to treat Swing components the same way that you do external resources. However, if you have a component that you are not going to need later you can set any references to that component to null.</p> <pre><code>JPanel p = new JPanel(); p = null; </code></pre> <p>Setting p to null does not delete the object but it removes any references to the object so the next time the garbage collector passes it gets picked up.</p> <p>You will have to be careful though that other reference to the component do not exist.</p>
41,488
<p>I am using JSF frontend for a page where an image is uploaded or deleted. Clicking on the upload or delete button causes a postback and the page to reload with the updated status. This however, resets the scroll position of the page. How should I go about retaining the scrollback of this page on the postback actions.</p>
<p>You can do that with an actionListener. For example, in your page (page.jsf for example):</p> <pre><code>&lt;f:view&gt; &lt;h:form&gt; &lt;h:commandLink actionListener="#{bean.method}"&gt; &lt;h:outputText value="Submit" /&gt; &lt;f:param name="anchor" value="image" /&gt; &lt;/h:commandLink&gt; &lt;/h:form&gt; &lt;div id='result'&gt; &lt;h1&gt;&lt;a name='image'&gt;Image&lt;/a&gt;&lt;/h1&gt; &lt;/div&gt; &lt;/f:view&gt; </code></pre> <p>And the managed bean looks like:</p> <pre><code>public class Bean { public void method(ActionEvent actionEvent) { // Get parameter String ancla = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("anchor"); try { FacesContext.getCurrentInstance().getExternalContext().redirect("page.jsf#" + anchor); } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <p>Hope this helps</p>
<p>If you are using Apache MyFaces Tomahawk, you can set the parameter AUTOSCROLL then make sure AutoScrollPhaseListener is enabled.</p> <p>I'm not sure this functionality is specified by JSF, but instead is something extra implemented by Apache MyFaces Tomahawk.</p> <p>Also, be aware that prior to version 1.1.6, there is a cross-site scripting vulnerability in the AUTOSCROLL implementation.</p>
30,776
<p>I am doing some research on Unicode for a white-paper I am writing. Does anyone remember the first version of MS Office on the Windows platform that was fully Unicode compliant? Not having much luck Googling this answer out of the net.</p>
<p>office 97: <br/> "The universal character set provided by Unicode overcomes this problem. Office 97 was the first version of Office to support Unicode in all applications except Microsoft Access and Microsoft Outlook®. In Office 2000, Access and Microsoft Publisher gain Unicode support. Microsoft FrontPage® 2000 also supports Unicode on Web pages, but text typed into dialog boxes and other elements of the user interface are limited to characters defined by the user’s code page." - Microsoft <br/> url:<br/> <a href="http://office.microsoft.com/en-us/ork2000/HA011382921033.aspx" rel="nofollow noreferrer">http://office.microsoft.com/en-us/ork2000/HA011382921033.aspx</a></p>
<p>Further to DanWoolston's answer, Microsoft Outlook 2003 was the first Outlook version to offer full Unicode support, so depending on your definition of 'Office' (seeing as there are so many different editions), your answer might be Microsoft Office 2003.</p> <p>URL: <a href="http://office.microsoft.com/en-us/ork2003/HA011402611033.aspx" rel="nofollow noreferrer">http://office.microsoft.com/en-us/ork2003/HA011402611033.aspx</a></p>
13,029
<p>Running IIS5 (yes, really). I'd like to remove the eTag http header that IIS generates for me. MS has an article on how to sync eTags across the web farm, but not how to remove them ( <a href="http://support.microsoft.com/?id=922733" rel="nofollow noreferrer">http://support.microsoft.com/?id=922733</a> ). </p> <p>Is there a way to remove eTags? </p>
<p>AFAIK, there's no easy way to remove etag of web resources such as image, css or js files from IIS 5. As each of the etag value regenerates on each subsequent web browser refresh which is unnecessary since there might not be any changes on those web resources.</p> <p>You might want to try EtagFix, it doesn't remove the etag though but it stabilizes the etag values so they don't change until the web resources are modified.</p> <blockquote> <p>EtagFix stabilizes the etag that Internet Information Services (IIS) generates so that it doesn't change each time the web server is restarted.</p> </blockquote> <p><a href="http://www.isapilabs.com/Products/ETagFix/index.htm" rel="nofollow noreferrer">http://www.isapilabs.com/Products/ETagFix/index.htm</a></p>
<p>Go into Inetmgr and in the website properties, switch to the HTTP Headers tab and add an "ETag" custom HTTP header with no value.</p>
34,682
<p>I want to sort members by name in the source code. Is there any easy way to do it? </p> <p>I'm using NetBeans, but if there is another editor that can do that, just tell me the name of it.</p>
<p>In Netbeans 8.0.1:</p> <pre><code>Tools -&gt; Options -&gt; Editor -&gt; Formatting -&gt; Category: Ordering </code></pre> <p><img src="https://i.stack.imgur.com/7BxRT.png" alt="Netbeans member sorting"></p> <p>Then:</p> <pre><code>Source -&gt; Organize Members </code></pre> <p><img src="https://i.stack.imgur.com/MO7Dc.png" alt="Netbeans member sorting"></p>
<p>Here is the easy way to do it in NetBeans:</p> <ol> <li>Go to the Tools tab and chose Options. The option Window should appear.</li> <li>Click on Editor and chose the Formatting Tab. </li> <li>Select Ordering for Category. Ordering is the last element from the drop down Category list.</li> <li>Uncheck the Sort Members By Visibility field. At this point only the "Sort Members in Groups Alphabetically" should be checked.</li> <li>Click Apply and exit the Option window. Now you globally set to sort members alphabetically. </li> <li>Open or Select the source file you want to sort the members.</li> <li>Click the Source Tab (upper right corner) and chose Organize Members.</li> </ol> <p>And that is it. Your source file should have the members sorted alphabetically.</p>
26,703
<p>I am wondering what are the possible value for *_la_LDFLAGS in Makefile.am ? </p> <p>If I ask this question, it is because I would like the following :</p> <pre><code>Actual shared library : libA.so (or with the version number I don't care) Symbolic links : libA-X.Y.Z.so, libA-X.so, libA.so soname : libA-X.so </code></pre> <p>However here is what I get by using the <em>-release</em> flag :</p> <pre><code>Actual shared library : libA-X.Y.Z.so Symbolic links : libA.so soname : libA-X.Y.Z.so !!! this is not what I want </code></pre> <p>I also tried with no flags at all and got </p> <pre><code>Actual shared library : libA-0.0.0.so !!! 0.0.0 and not the real version Symbolic links : libA.so, libA-0.so soname : libA-0.so !!! 0.0.0 and not the real version </code></pre> <p>How should I do ? which flag should I use ? </p> <p>Thanks in advance</p>
<p>You should use the <code>-version-info</code> option of Libtool to specify the interface version of the library, but be sure to read <a href="http://sources.redhat.com/autobook/autobook/autobook_91.html" rel="nofollow noreferrer">how versioning works</a> (or <a href="http://www.gnu.org/software/libtool/manual/html_node/Versioning.html#Versioning" rel="nofollow noreferrer">here</a> for the official manual.)</p> <p>You can additionally play with <code>-release</code> to make the version number of your package more apparent, but I doubt you will ever get the exact naming you'd like. Libtool has its own set of rules to define how to name the file and what symlinks to create depending on the system: these should really be regarded as implementation details of how a shared library is installed.</p>
<p>IMHO, the layout you want is broken. Apps that are linked to your library will depend on libA-X.so because of the soname. But what happens when libA.so is version X+1? To what will the libA-X.so symlink point?</p> <p>The idea behind the layout you get with the -release flag is, when an app links with -lA, it will result in it being linked against the latest version. It will then, because of the soname, depend on libA-X.Y.Z.so at runtime. When you install a new version of the library, that will install a new libA-X.Y.Q.so, but it will leave the old one alone - exactly as old apps that depend on it expect. New apps will still, because of the libA symlink, link against the latest version.</p> <p>Years of thought by some very smart people have went into a versioning scheme that allows new apps to link against the latest version of a library, while allowing multiple versions to co-exist peacefully to satisfy dependencies for apps that need them. My advice is, don't second-guess all that.</p>
31,691
<p>What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster?</p> <pre><code>def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) </code></pre> <p>Here is some test data. The first one is recursive, the second uses the generator:</p> <pre><code>s = time.time() for i in range(100000): e.inc_counter() print time.time() - s s = time.time() for i in range(100000): for e in e.children(): e.inc_counter_s() print time.time() - s </code></pre> <p>Results:</p> <pre><code>0.416000127792 0.298999786377 </code></pre> <p>Test code:</p> <pre><code>import random class Entity(): def __init__(self, name): self.entities = [] self.name = name self.counter = 1 self.depth = 0 def add_entity(self, e): e.depth = self.depth + 1 self.entities.append(e) def inc_counter_r(self): for e in self.entities: e.counter += 1 e.inc_counter_r() def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) root = Entity("main") def fill_node(root, max_depth): if root.depth &lt;= max_depth: for i in range(random.randint(10, 15)): e = Entity("node_%s_%s" % (root.depth, i)) root.add_entity(e) fill_node(e, max_depth) fill_node(root, 3) import time s = time.time() for i in range(100): root.inc_counter_r() print "recursive:", time.time() - s s = time.time() for i in range(100): for e in root.children(): e.counter += 1 print "generator:", time.time() - s </code></pre>
<p>I can't think of any big algorithmic improvements, but a simple microoptimisation you can make is to bind frequently called methods (such as stack.append / stack.pop) to locals (this saves a dictionary lookup)</p> <pre><code>def children(self): stack = [self.entities] push = stack.append pop = stack.pop while stack: for e in pop(): yield e if e.entities: push(e.entities) </code></pre> <p>This gives a small (~15%) speedup by my tests (using 100 traversals of an 8-deep tree with 4 children at each node gives me the below timings:)</p> <pre><code>children : 5.53942348004 children_bind: 4.77636131253 </code></pre> <p>Not huge, but worth doing if speed is important.</p>
<p>I don't know too much about Python internals of function calls, but I really can't imagine that your code snippet is faster than recursively traversing the tree.</p> <p>The call stack (used for function calls, including recursive ones) is typically very fast. Going to the next object will only cost you a single function call. But in your snippet - where you use a stack object, going to the next object will cost you a stack.append (possibly allocating memory on heap), a stack.push (possibly freeing memory from heap), and a yield.</p> <p>The main problem with recursive calls is that you might blow the stack if your tree gets too deep. This isn't likely to happen.</p>
41,393
<p>I'm trying to do a subselect in pgsql aka postgresql and the example I found doesn't work:</p> <pre><code>SELECT id FROM (SELECT * FROM table); </code></pre>
<p>I just needed to add an AS for the subselect, like so:</p> <pre><code>SELECT id FROM (SELECT * FROM table) AS aliasname; </code></pre>
<p>I think you need something like:</p> <pre><code>SELECT * FROM table WHERE id IN (SELECT id FROM table2); </code></pre> <p>I don't understand what your non-working subquery is attempting to do, it seems like you could just say <code>SELECT id FROM table</code> because presently its not valid SQL92 syntax.</p>
33,771
<p>I am trying to inherit from my generated datacontext in LinqToSQL - something like this </p> <pre><code>public class myContext : dbDataContext { public System.Data.Linq.Table&lt;User&gt;() Users { return (from x in base.Users() where x.DeletedOn.HasValue == false select x); } } </code></pre> <p>But my Linq statement returns IQueryable which cannot cast to Table - does anyone know a way to limit the contents of a Linq.Table - I am trying to be certain that anywhere my Users table is accessed, it doesn't return those marked deleted. Perhaps I am going about this all wrong - any suggestions would be greatly appreciated.</p> <p>Hal</p>
<p>Another approach would to be use views..</p> <pre><code>CREATE VIEW ActiveUsers as SELECT * FROM Users WHERE IsDeleted = 0 </code></pre> <p>As far as linq to sql is concerned, that is just the same as a table. For any table that you needed the DeletedOn filtering, just create a view that uses the filter and use that in place of the table in your data context.</p>
<p>You can use a stored procedure that returns all the mapped columns in the table for all the records that are not marked deleted, then map the LINQ to SQL class to the stored procedure's results. I think you just drag-drop the stored proc in Server Explorer on to the class in the LINQ to SQL designer.</p>
11,100
<p>I'm having trouble finding an open-source IDE with support for Git. Are there any that you could point me to or recommend?</p>
<p>There's an <a href="http://www.eclipse.org/egit/" rel="nofollow noreferrer">Eclipse plugin in progress</a>.</p>
<p>The great <a href="http://www.aptana.com/studio" rel="nofollow noreferrer">Aptana Studio</a> has support (via plugins) for SVN, CVS, and Git (via <a href="http://git.or.cz/gitwiki/EclipsePlugin" rel="nofollow noreferrer">this plugin</a>). I'm still a noob with Aptana, and I haven't used Git yet, but it looks promising.</p>
46,069
<p>The last GUI programming I have done was with Visual Basic, which included objects like Winsock and Inet to easily connect to the internet and retrieve the source from webpages.</p> <p>I just got started into XCode, and was wondering if there is a similar component. I see that there is a Webkit option in the Library, but I have no idea how to use it.</p> <p>Any help would be appreciated.</p> <hr> <p>I want to simulate the browser as well as possible (including cookies, headers, etc). Is the Webkit approach better than the link you just gave me? Sorry I was no more clear in the OP.</p>
<p>Apple has two guides in the documentation you'll want to look at, <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html" rel="nofollow noreferrer">URL Loading System</a> and <a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/DisplayWebContent/DisplayWebContent.html" rel="nofollow noreferrer">WebKit Objective-C Programming Guide</a>. You'll probably be most interested in the former if you want to request data from a web server behind the scenes, or the latter if you want to actually put a web browser control into your application. Both documents should explain the classes you'll use and the general process, but let me know if you have questions.</p> <p>A lot of the core Cocoa data types like NSString, NSDate, and even NSArray and NSDictionary have methods for loading data from a URL like Heng-Cheong Leong mentioned, but they abstract away all the low level stuff and probably won't be suitable if you want to deal with HTTP headers.</p>
<p>The NSString class have methods to retrieve source from webpages, such as stringWithContentsOfURL:encoding:error:.</p> <p>For more control, take a look at the classes described in <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html" rel="nofollow noreferrer">http://developer.apple.com/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html</a> documentation.</p> <p>WebKit is more like MSIE ActiveX control.</p>
49,310
<p>Any suggestions on how to improve DataGridViewComboBoxColumn performace with large item sets?</p> <p>I've got a DataGridView with several columns of type DataGridViewComboBoxColumn. I'm databinding those combobox columns to a rather large collection (10k+ items). As a result it's very slow to display the items (when i click on the down-arrow button on a cell it takes about 10 seconds to display the items).</p> <p>I've tested the same collection of items with a standard ComboBox control, and it works really fast.</p> <p>Any ideas?</p> <p>Thanks.</p>
<p>A much better solution is to populate a string array with the values from the database and set the column datasource to null, then set the Items property of the column to the array of values you populated. This way it does not requery the database each time it populates the combobox. Hope this helps.</p>
<p>Are you data binding 10k items to the combo boxes or the data grid? </p> <p>Either way you should think about the usability of your design. </p> <p>If its to the data grid then use paging and cut the size of the data source bound to a more reasonable size. </p> <p>If its to the combo box then your solution can't be usable. You'd be better giving your users an autocomplete box like the one from the ajax toolkit (<a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx" rel="nofollow noreferrer">http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx</a>) or a popup though which they can page or search though your 10k items.</p>
33,620
<p>I have a bit of code that passes around a ton of objects and I want to determine if there are any references still lingering around that I am unaware of and where it is those references are located. Any idea of how I can do this? </p> <p>My understanding is that the watch window only allows me to see items available to the currently executing code block, and the "Find All References" only helps if I add references to objects at compile time. Unless there is more to the watch window than I am aware of.</p>
<p>if you are talking in the code, just right click on the object name, in the drop down menu pick "Find all references", the list of references will appear below in the output window</p> <p>EDIT: Since there was only a .NET tag, Visual Studio assumed</p>
<p>In a IDE like Elcipse or Visual Studio you can do it with the context menu.</p>
16,350
<p>I have wrapped Log4net in a static wrapper and want to log </p> <pre><code>loggingEvent.LocationInformation.MethodName loggingEvent.LocationInformation.ClassName </code></pre> <p>However all I get is the name of my wrapper.</p> <p>How can I log that info using a forwardingappender and a static wrapper class like </p> <pre><code>Logger.Debug("Logging to Debug"); Logger.Info("Logging to Info"); Logger.Warn("Logging to Warn"); Logger.Error(ex); Logger.Fatal(ex); </code></pre>
<p>Well the error was somewhere in my appender but for completeness ill include the answer to the best of my knowledge:</p> <p>the Facade you need should wrap ILogger and NOT ILog</p> <pre><code> public static class Logger { private readonly static Type ThisDeclaringType = typeof(Logger); private static readonly ILogger defaultLogger; static Logger() { defaultLogger = LoggerManager.GetLogger(Assembly.GetCallingAssembly(),"MyDefaultLoggger"); </code></pre> <p>...</p> <pre><code> public static void Info(string message) { if (defaultLogger.IsEnabledFor(infoLevel)) { defaultLogger.Log(typeof(Logger), infoLevel, message, null); } } </code></pre>
<p>The only thing I can think of doing (as I dont currently use log4net) is to request a stacktrace(new StackTrace), and go back a frame to get the info you need. However, I am unsure of the runtime performance impact of this.</p>
19,025
<p>I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the <code>HttpRequest</code> object?</p> <p>My <code>HttpRequest.GET</code> currently returns an empty <code>QueryDict</code> object.</p> <p>I'd like to learn how to do this without a library, so I can get to know Django better.</p>
<p>When a URL is like <code>domain/search/?q=haha</code>, you would use <code>request.GET.get('q', '')</code>.</p> <p><code>q</code> is the parameter you want, and <code>''</code> is the default value if <code>q</code> isn't found.</p> <p>However, if you are instead just configuring your <code>URLconf</code>**, then your captures from the <code>regex</code> are passed to the function as arguments (or named arguments).</p> <p>Such as:</p> <pre><code>(r'^user/(?P&lt;username&gt;\w{0,50})/$', views.profile_page,), </code></pre> <p>Then in your <code>views.py</code> you would have</p> <pre><code>def profile_page(request, username): # Rest of the method </code></pre>
<p>url parameters may be captured by <code>request.query_params</code></p>
18,138
<p>I have a website built in PHP 4 with a framework made by hand by me. The code is 3 years old and I am limited (well it requires a lot of effort to make changes).</p> <p>I decided to do new version of this website. My knowledge has since increased, and now I know that a lot of frameworks exist and that <strong>IOC</strong> is there and <strong>ORM</strong> too... The problem is that in all my research, <strong>I do not find something that satisfies me completely in PHP</strong>. On the other hand, at my job (mostly in .Net winform 2.0) I see many good IOC and other solutions possible, and, I think that .Net is more mature for developing software with best-practices.</p> <p>I haven't found many good IOC for PHP. As for ORM, I have seen Propel, which looks nice, but haven't found a complete Framework too (Symfony documentation isn't up-to-date, contains lot of error; Zend looks too big I think...), etc.</p> <p>Do you suggest that I simply try another framework and keep the website in PHP, or would it would be a good idea to switch to .Net?</p> <h2>Reasons of this question</h2> <ul> <li>The system works but has begun to slow down (since it has more users). The database is normalized too much... etc.</li> <li>The code isn't bad - business logic is separated of the HTML - but the problem is that controllers are inside the view so it's harder and harder to make some layout changes.</li> <li>No unit tests have been done, and it's very &quot;stressful&quot; to make change.</li> <li>There's no logging in the system, and it's hard to get a snapshot to see if everything is working properly.</li> </ul> <h2>More information (added the 3 nov 2008)</h2> <ul> <li>I know .Net 2.0 this is why my alternative is .Net and not RoR.</li> <li>I were suggesting an other language not for the speed issue but for the tool/framework available.</li> <li>It's slow because of the database normalisation, too many table that are great in theory but not in practice (we learn from our mistake!)</li> <li>It's an hobby, but I take it seriously cause I have over 25 000 users registered since the beginning (not all active).</li> </ul> <h2>Current suggestion from people over here</h2> <p>I think I'll keep what I have done and try to do some refactoring slowly. I am surprise that most of the vote have been to keep the current system but well :P this might be the simpler for me for the short term.</p> <hr /> <p>Thx to <strong>nickf</strong> who has spell check all my text.</p>
<p>If you made the whole framework yourself, I would suggest you just upgrade it for PHP 5 and go forward from there. Most PHP 4 code will "just work" in PHP 5; the exceptions are code that uses the new reserved words, and code that relies on the way PHP 4 differs from PHP 5 -- which means a few things in classes and references at the edge of PHP 4's capabilities. </p>
<p>And why are you limiting yourself to these choices? Why not try Ruby on Rails? I has a built-in ORM!</p>
32,149
<p>How do I create tabbed navigation with the "Current" tab highlighted in the UI?</p>
<p>Before MVC I looked at the file path and figured out which tab was currrent. Now it's a lot easier, you can assign the current tab based on the current controller.</p> <p>Check it out ...</p> <p>Most of the work happens in the usercontrol. </p> <pre><code>public partial class AdminNavigation : ViewUserControl { /// &lt;summary&gt; /// This hold a collection of controllers and their respective "tabs." Each Tab should have at least one controller in the collection. /// &lt;/summary&gt; private readonly IDictionary&lt;Type, string&gt; dict = new Dictionary&lt;Type, string&gt;(); public AdminNavigation() { dict.Add(typeof(BrandController), "catalog"); dict.Add(typeof(CatalogController), "catalog"); dict.Add(typeof(GroupController), "catalog"); dict.Add(typeof(ItemController), "catalog"); dict.Add(typeof(ConfigurationController), "configuration"); dict.Add(typeof(CustomerController), "customer"); dict.Add(typeof(DashboardController), "dashboard"); dict.Add(typeof(OrderController), "order"); dict.Add(typeof(WebsiteController), "website"); } protected string SetClass(string linkToCheck) { Type controller = ViewContext.Controller.GetType(); // We need to determine if the linkToCheck is equal to the current controller using dict as a Map string dictValue; dict.TryGetValue(controller, out dictValue); if (dictValue == linkToCheck) { return "current"; } return ""; } } </code></pre> <p>Then in your .ascx part of the usercontol call into the SetClass method to check the link against the dict. Like so:</p> <pre><code>&lt;li class="&lt;%= SetClass("customer") %&gt;"&gt;&lt;%= Html.ActionLink&lt;CustomerController&gt;(c=&gt;c.Index(),"Customers",new{@class="nav_customers"}) %&gt;&lt;/li&gt; </code></pre> <p>All you need now is the CSS to highlight your current tab. There are a bunch of different ways to do this, but you can get started with some ideas here: <a href="http://webdeveloper.econsultant.com/css-menus-navigation-tabs/" rel="noreferrer">http://webdeveloper.econsultant.com/css-menus-navigation-tabs/</a> Oh, and don't forget to put the usercontrol on your page (or MasterPage) ...</p> <pre><code>&lt;% Html.RenderPartial("AdminNavigation"); %&gt; </code></pre>
<p>MVC's default <code>Site.css</code> comes with a class named <code>'selectedLink'</code> which should be used for this.</p> <p>Add the following to your <code>ul</code> list in <code>_Layout.cshtml</code>:</p> <pre><code>@{ var controller = @HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString(); } &lt;ul id="menu"&gt; &lt;li&gt;@Html.ActionLink("Home", "Index", "Home", null, new { @class = controller == "Home" ? "selectedLink" : "" })&lt;/li&gt; ... &lt;/ul&gt; </code></pre> <p>I know this is not clean. But just a quick and dirty way to get things rolling without messing with partial views or any of that sort.</p>
36,604
<p>Why would someone use <code>WHERE 1=1 AND &lt;conditions&gt;</code> in a SQL clause (Either SQL obtained through concatenated strings, either view definition)</p> <p>I've seen somewhere that this would be used to protect against SQL Injection, but it seems very weird.</p> <p>If there is injection <code>WHERE 1 = 1 AND injected OR 1=1</code> would have the same result as <code>injected OR 1=1</code>.</p> <p>Later edit: What about the usage in a view definition?</p> <hr> <p>Thank you for your answers.</p> <p>Still, I don't understand why would someone use this construction for defining a view, or use it inside a stored procedure.</p> <p>Take this for example:</p> <pre><code>CREATE VIEW vTest AS SELECT FROM Table WHERE 1=1 AND table.Field=Value </code></pre>
<p>If the list of conditions is not known at compile time and is instead built at run time, you don't have to worry about whether you have one or more than one condition. You can generate them all like:</p> <pre><code>and &lt;condition&gt; </code></pre> <p>and concatenate them all together. With the <code>1=1</code> at the start, the initial <code>and</code> has something to associate with.</p> <p>I've never seen this used for any kind of injection protection, as you say it doesn't seem like it would help much. I <em>have</em> seen it used as an implementation convenience. The SQL query engine will end up ignoring the <code>1=1</code> so it should have no performance impact.</p>
<p>I first came across this back with ADO and classic asp, the answer i got was: <strong>performance.</strong> if you do a straight </p> <p><code>Select * from tablename</code></p> <p>and pass that in as an sql command/text you will get a noticeable performance increase with the </p> <p><code>Where 1=1</code></p> <p>added, it was a visible difference. something to do with table headers being returned as soon as the first condition is met, or some other craziness, anyway, it did speed things up.</p>
30,072
<p>I don't need a Link but rather only the href= part of the ActionLink.</p> <p>But if I call Html.ActionLink(...) I get a back. Is there a way to just return the URL of the Action while not getting the ?</p>
<p>MVC also provides a UrlHelper class which can do the same thing:</p> <pre><code>&lt;%=Url.Action(actionName)%&gt; &lt;%=Url.Action(actionName, htmlValues)%&gt; &lt;%=Url.Action(actionName, controllerName, htmlValues)%&gt; </code></pre>
<p>Edit: in response to commment, now including parameters:</p> <pre><code>&lt;% =Html.BuildUrlFromExpression&lt;YourController&gt;(c =&gt; c.YourAction(parameter)) %&gt; </code></pre>
18,351
<p>Is there a way to just tell the compiler, that I want my objects to be serializable by default?</p>
<p>Pretty much every serialization engine is going to want to know that your objects are suitable. This can take the form of:</p> <ul> <li><code>[Serializable]</code>/<code>ISerializable</code> (<code>BinaryFormatter</code>,<code>SoapFormatter</code>)</li> <li><code>[Serializable]</code>/<code>IXmlSerializable</code> (and <code>public</code>) (<code>XmlSerializer</code>)</li> <li><code>[DataContract]</code>/<code>[MessageContract]</code> (or most of the above) (<code>DataContractSerializer</code> and variants)</li> </ul> <p>AFAIK, there is no way of avoiding this step.</p>
<p>No, you need to decorate the objects with the Serializable attribute. FYI all objects are Xml Serializable by default. The Xml Serializer doesn't require the attribute.</p> <p>I'm not sure about DataContracts but last I checked you needed to decorate them as well. </p>
44,266
<p>Anyone found a good pattern for getting around immutable styles in Silverlight 2? <br/><br/>What I mean is does anyone have a workaround for the fact that you cannot switch the style of an element programmatically once it has been set, i.e. the second line here will throw a catastrophic failure exception:</p> <p>this.TestButton.Style = (Style)Application.Current.Resources["Fred"];<br/> this.TestButton.Style = (Style)Application.Current.Resources["Barney"];</p>
<p>It's not possible. The best workaround I've seen is from Nikhil Kothari at Microsoft:</p> <p><a href="http://www.nikhilk.net/Silverlight-Themes.aspx" rel="nofollow noreferrer">http://www.nikhilk.net/Silverlight-Themes.aspx</a></p> <p>There is a major drawback to defining styles centrally in App.xaml anyway, which is that it breaks all designer support when you reference those styles from other user controls. I haven't used it but Nikhil's theme engine looks very promising, and I have a funny feeling that many of his ideas will make it into the silverlight product eventually anyway.</p>
<p>I don't know if this helps, but I believe you can change the control's template as many times as you want during runtime. Maybe that would be a potential workaround.</p>
15,413
<p>I would like to know how to loop through each line in a text file using a Windows batch file and process each line of text in succession.</p>
<p>I needed to process the entire line as a whole. Here is what I found to work.</p> <pre><code>for /F &quot;tokens=*&quot; %%A in (myfile.txt) do [process] %%A </code></pre> <p>The tokens keyword with an asterisk (*) will pull all text for the entire line. If you don't put in the asterisk it will only pull the first word on the line. I assume it has to do with spaces.</p> <p><a href="http://technet.microsoft.com/en-us/library/bb490909.aspx" rel="noreferrer">For Command on TechNet</a></p> <hr /> <p>If there are spaces in your file path, you need to use <code>usebackq</code>. For example.</p> <pre><code>for /F &quot;usebackq tokens=*&quot; %%A in (&quot;my file.txt&quot;) do [process] %%A </code></pre>
<p>Modded examples here to list our Rails apps on Heroku - thanks!</p> <pre><code>cmd /C "heroku list &gt; heroku_apps.txt" find /v "=" heroku_apps.txt | find /v ".TXT" | findstr /r /v /c:"^$" &gt; heroku_apps_list.txt for /F "tokens=1" %%i in (heroku_apps_list.txt) do heroku run bundle show rails --app %%i </code></pre> <p>Full code <a href="https://gist.github.com/4512454/" rel="nofollow">here</a>.</p>
18,865
<p>I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a concern. My OOP classes create new objects (in this case I will need 250,000 new objects, each object is an array of 1,000 doubles) to handle the data. What is the overhead in terms of memory and computing required in creating objects for a generic OOP language? In python? What about in C++?</p> <p>Yes, I realize I could make a new class that is an array. But 1) I already have these classes finished and 2) I put each object that I create back into an array for access later anyways. The question is pedagogical </p> <p>*update: I want to be efficient with time, my time and the computers. I don't want to rewrite a program I already have if I don't have to and spending time optimizing the code wastes my time, I don't care <em>that</em> much if I waste the computers time. I actually do have a 64bit machine with 4Gig ram. The data is an image and I need to do several filters on each pixel.*</p>
<p>See <a href="http://code.activestate.com/recipes/546530/" rel="nofollow noreferrer">http://code.activestate.com/recipes/546530/</a></p> <p>This is the approximate size of Python objects.</p> <p>The OO size "penalty" is often offset by the ability to (a) simplify processing and (b) keep less stuff in memory in the first place.</p> <p>There is no OO performance overhead. Zero. In C++, the class definitions are optimized out of existence, and all you have left is C. In Python -- like all dynamic languages -- the dynamic programming environment adds some run-time lookups. Mostly, these are direct hashes into dictionaries. It's slower than code where a compiler did all the resolving for you. However it's still very fast with relatively low overhead.</p> <p>A bad algorithm in C can easily be slower than the right algorithm in Python.</p>
<p>Impossible to answer without knowing the shape of the data and the structure that you've designed to contain it.</p>
48,695
<p>Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc).</p> <pre><code>CREATE TABLE `log` ( `id` INTEGER NOT NULL AUTO_INCREMENT , `date` DATETIME NOT NULL , `count` INTEGER NOT NULL , PRIMARY KEY (`id`) ); </code></pre> <p>Is it possible to have the count column calculated for me whenever I do an insert?</p> <p>e.g. do something like:</p> <pre><code>INSERT INTO log (date='foo'); </code></pre> <p>and have count calculated by mysql.</p> <p>Obviously I could do it myself by doing a query to get the count and inserting it, but this would be better.</p>
<p>Triggers are the best tool for annotating data when a table is changed by insert, update or delete.</p> <p>To automatically set the date column of a new row in the log with the current date, you'd create a trigger that looked something like this:</p> <pre><code>create trigger log_date before insert on log for each row begin set new.date = current_date() end; </code></pre>
<p>Why don't you use information_schema.TABLES?</p>
6,722
<p>I can start with my own .NET dll. I have a dll I use in all my web projects (around 10) and I have util classes for FTP, zip, imageresizing, extensionmethods and a generic singleton class.</p> <p>I think it is a common practice and I just thought it would be interesting to hear what people put in their 'Utils' dlls</p> <p>EDIT: What small code gems do you have that have made you much more productive with lesser code?</p> <p>These extension methods are pretty useful for me when parsing nullable form input before putting into the database</p> <pre><code> public static int? ToInt(this string input) { int val; if (int.TryParse(input, out val)) return val; return null; } public static DateTime? ToDate(this string input) { DateTime val; if (DateTime.TryParse(input, out val)) return val; return null; } public static decimal? ToDecimal(this string input) { decimal val; if (decimal.TryParse(input, out val)) return val; return null; } </code></pre>
<p>I think carrying utility assemblies beyond the current version of your language does more harm than good.</p> <p>The main reason is that as the language grows new methods and better ways of doing things are built in. By carrying around a utilities assembly, you will quickly end up with a lot of dead weight which may expose security problems.</p> <p>A prime example is boosts list of functions. A quick glance will show that .Net (just like most other languages) already cover at least 75% of that code.</p>
<p>I have only just really started mine but at the moment it mostly contains just common extension methods that I use all the time. Stuff like "ThrowIfNull()" so I don't have to do heaps of if statements every time I want to check for nulls.</p> <p>I also have a playground project which just has any ideas that I am toying around with but I'm not 100% sure that they will even work.</p>
41,287
<p>I have an ASP.Net 2.0 application in which the Session_Start event is not firing in my Global.asax file. Can anyone tell why this is happening and how I can get it working?</p> <p>The application worked fine on my Windows XP development machine, but stopped working when deployed to the server (Win Server 2003/IIS 6/ASP.Net 2.0). </p> <p>I'm not sure if this is relevant, but the server also hosts a SharePoint installation (WSS 3.0) which I know does change some settings at the default web site level.</p>
<p>Is the site precompiled before adding global.asax? Try compiling it again.</p>
<p>Are you sure the website in IIS is set to use ASP.NET 2.0 rather than 1.1?</p>
9,719
<p>I have a text file which contains some data. I am trying to search for EA in <strong>ID column only</strong> and prints the whole row. But the code recognize all EA and prints all rows. What code I should add to satisfy the condition? Thanks Again:-)!</p> <p>DATA: <br> Name Age ID <br> ---------------------<br> KRISTE,22,<strong>EA</strong>2008<br> J<strong>EA</strong>N,21,ES4567<br> JAK,45,<strong>EA</strong>2008<br><br> The code prints:<br> KRISTE,22,<strong>EA</strong>2008<br> J<strong>EA</strong>N,21,ES4567<br> JAK,45,<strong>EA</strong>2008<br></p> <p>Desired output:<br> KRIS,22,<strong>EA</strong>2008<br> Kane,45,<strong>EA</strong>2008,<br></p> <pre><code>file='save.txt'; open(F,$file)||die("Could not open $file"); while ($line=&lt;F&gt;){ if ($line=~ m/$EA/i) { my @cells=($f1,$f2,$f3)= split ',',$line; print "&lt;TD&gt;f1&lt;/TD&gt;"; print "&lt;TD&gt;f2&lt;/TD&gt;"; print "&lt;TD&gt;f3&lt;/TD&gt;"; } </code></pre>
<p>You should post the actual sample program you are using to illustrate the problem. Here's your cleansed program:</p> <pre><code>use strict; use warnings; use CGI; my $EA = param('keyword'); my $file = 'save.txt'; open my $fh, "&lt;", $file or die "Could not open $file: $!"; while( $line=&lt;$fh&gt; ) { if( $line=~ m/$EA/i ) { my( $f1, $f2, $f3 ) = split ',', $line; print "&lt;TD&gt;$f1&lt;/TD&gt;"; print "&lt;TD&gt;$f2&lt;/TD&gt;"; print "&lt;TD&gt;$f3&lt;/TD&gt;"; } } </code></pre> <p>Here's a few things that can help you.</p> <ul> <li>Your variables need their sigils. They don't do anything without them.</li> <li>When you try to open a file and want to report an error, include the $! variable so you see what the error is.</li> <li>You can split directly to scalar variables. It's just a list assignment. You don't need the extra @cell variable.</li> <li>Give your statements some room to breathe by using some whitespace. It's free, after all.</li> </ul>
<p>Your regex is incorrect for what you are trying to do. Ben's solution works, although there should also be a ^ at the start, which ensures that the regex will start matching from the start of the string:</p> <p>/^.<em>?,.</em>?,.*EA/</p> <p>Also, your code is kinda noisy, from a perl point of view. If you want to make your code easier to read, you can do this (I'm using Ben's regex):</p> <p><code> $f = 'save.txt';</p> <p>open( F, $file );</p> <p>@matches = grep { /^.<em>?,.</em>?,.*EA/ } &lt;F&gt;; </code></p> <p>Now @matches will hold all your matched records, you can do what you want with them.</p>
32,626
<p>We all know that prepared statements are one of the best way of fending of SQL injection attacks. What is the best way of creating a prepared statement with an "IN" clause. Is there an easy way to do this with an unspecified number of values? Take the following query for example.</p> <pre><code>SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (1,2,3) </code></pre> <p>Currently I'm using a loop over my possible values to build up a string such as. </p> <pre><code>SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (@IDVAL_1,@IDVAL_2,@IDVAL_3) </code></pre> <p>Is it possible to use just pass an array as the value of the query paramter and use a query as follows?</p> <pre><code>SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (@IDArray) </code></pre> <p>In case it's important I'm working with SQL Server 2000, in VB.Net</p>
<p>Here you go - first create the following function...</p> <pre><code>Create Function [dbo].[SeparateValues] ( @data VARCHAR(MAX), @delimiter VARCHAR(10) ) RETURNS @tbldata TABLE(col VARCHAR(10)) As Begin DECLARE @pos INT DECLARE @prevpos INT SET @pos = 1 SET @prevpos = 0 WHILE @pos &gt; 0 BEGIN SET @pos = CHARINDEX(@delimiter, @data, @prevpos+1) if @pos &gt; 0 INSERT INTO @tbldata(col) VALUES(LTRIM(RTRIM(SUBSTRING(@data, @prevpos+1, @pos-@prevpos-1)))) else INSERT INTO @tbldata(col) VALUES(LTRIM(RTRIM(SUBSTRING(@data, @prevpos+1, len(@data)-@prevpos)))) SET @prevpos = @pos End RETURN END </code></pre> <p>then use the following...</p> <pre><code>Declare @CommaSeparated varchar(50) Set @CommaSeparated = '112,112,122' SELECT ID,Column1,Column2 FROM MyTable WHERE ID IN (select col FROM [SeparateValues](@CommaSeparated, ',')) </code></pre> <p>I think sql server 2008 will allow table functions.</p> <p><strong>UPDATE</strong></p> <p>You'll squeeze some extra performance using the following syntax...</p> <pre><code>SELECT ID,Column1,Column2 FROM MyTable Cross Apply [SeparateValues](@CommaSeparated, ',') s Where MyTable.id = s.col </code></pre> <p>Because the previous syntax causes SQL Server to run an extra "Sort" command using the "IN" clause. Plus - in my opinion it looks nicer :D!</p>
<p>In SQL Server 2008, they finally got around to addressing this classic problem by adding a new "table" datatype. Apparently, that lets you pass in an array of values, which can be used in a sub-select to accomplish the same as an IN statement.</p> <p>If you're using SQL Server 2008, then you might look into that.</p>
11,860
<p>Does anyone know how to use the <a href="http://msdn.microsoft.com/en-us/library/ms645543(VS.85).aspx" rel="nofollow noreferrer">Raw Input</a> facility on Windows from a WX Python application?</p> <p>What I need to do is be able to differentiate the input from multiple keyboards. So if there is another way to achieving that, that would work too.</p>
<p>Have you tried using ctypes?</p> <pre><code>&gt;&gt;&gt; import ctypes &gt;&gt;&gt; ctypes.windll.user32.RegisterRawInputDevices &lt;_FuncPtr object at 0x01FCFDC8&gt; </code></pre> <p>It would be a little work setting up the Python version of the necessary structures, but you may be able to query the Win32 API directly this way without going through wxPython.</p>
<p>Theres a nice looking library here <a href="http://code.google.com/p/pymultimouse/" rel="nofollow noreferrer">http://code.google.com/p/pymultimouse/</a></p> <p>It's not wx-python specific - but it does use raw input in python with ctypes (and worked in my test with 2 mice)</p>
36,313
<p>It seems that all of the documentation I can find about OpenGL-ES says something to the effect of "OpenGL-ES is just like OpenGL, but without a lot of stuff. For example, there's no glBegin or glEnd."</p> <p>Ok, that's great. So, what ELSE isn't there any of? Or is there a list of what's <em>in</em>? Or maybe a porting guide?</p> <p>(Specifically, I'm trying to move an existing GL app to the iPhone, although I don't want to necessarily limit my Q to the iPhone.)</p>
<p>The <a href="http://www.khronos.org/registry/gles/specs/1.1/es_cm_spec_1.1.12.pdf" rel="noreferrer">"OpenGL ES 1.1.12 Difference Specification"</a> (PDF) linked to from <a href="http://www.khronos.org/opengles/1_X/" rel="noreferrer">the OpenGL ES 1.X info page at Khronos.org</a> goes through the differences between OpenGL ES 1.X and OpenGL 1.5. OpenGL ES 1.1 is the version used on the iPhone.</p> <p>The difference specification is not the simplest document I've ever seen, but it is easier reading than the OpenGL specs in general. I recommend getting a list of OpenGL functions you call and then searching through the difference document for them. It will show you if they are supported in OpenGL ES, and if support is only partial you can go to the full spec for more information.</p>
<p>Part of the problem in answering your question is there are many things missing and often it's a set of rarely used or non-applicable bit flags. The best document describing the differences is actually the implementation headers.</p> <p>For the framework I'm working on I decided to make it completely cross platform between desktop and iPhone. The approach I take in figuring it out is write code in OpenGL, and see where it breaks. Then look in </p> <p><code>/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.sdk/ System/Library/Frameworks/OpenGLES.framework/Headers/ES1/gl.h</code></p> <p>and compare it to </p> <p><code>/Developer/SDKs/MacOSX10.5.sdk/ System/Library/Frameworks/OpenGL.framework/Versions/A/Headers/gl.h</code></p> <p>These headers are very straightforward and easy to follow.</p> <p>The main difference I've discovered so far is there is no GLdouble (anything using GLdouble such as glOrtho and glFrustum has a GLfloat version glOrthof and glFrustumf). Also there is no gluPerspective or gluPerspectivef for some reason. </p> <p>Here is a drop in replacement:</p> <pre><code>void gluPerspective( GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar ) { GLfloat xmin, xmax, ymin, ymax; ymax = zNear * tan(fovy * M_PI / 360.0); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; glFrustumf( xmin, xmax, ymin, ymax, zNear, zFar ); } </code></pre> <p>Since you have no glBegin and glEnd, you have to do everything through glDrawArray or glDrawElements (preferred). A quick and dirty example:</p> <pre><code>void draw( short x, short y, short w, short h ) { const GLshort t[8] = { 0, 0, 1, 0, 1, 1, 0, 1 }; const GLshort v[8] = { x, y, x+w, y, x+w, y+h, x, y+h }; glVertexPointer( 2, GL_SHORT, 0, v ); glEnableClientState( GL_VERTEX_ARRAY ); glTexCoordPointer( 2, GL_SHORT, 0, t ); glEnableClientState( GL_TEXTURE_COORD_ARRAY ); glDrawArrays( GL_TRIANGLE_FAN, 0, 4 ); } </code></pre> <p>Check out Apple's Technical Note <a href="http://developer.apple.com/iphone/library/technotes/tn2008/tn2230.html" rel="noreferrer">TN2230 "Optimizing OpenGL ES for iPhone OS"</a> for some other hints that could be useful in porting.</p> <p>Porting so far has been fairly pain free for me, and unless your app does some pretty advanced OGL stuff or uses completely unsupported functionality you'll find your problems by hitting the build button and a simple fix will be apparent by digging a little in the gl.h files. In fact, porting to ES kind of forces you to write good optimized rendering code.</p>
34,375
<p>Someone left the organisation but before leaving, he locked all the files for an unknown reason. </p> <p>How do you unlock them all so that the other developers can work?</p>
<p>For the following operation, you will need to be either a project administrator for the project you want to undo the check-in on or a Team Foundation Administrator if you want to do this across all projects.</p> <p>If you still have the username of the person, you can simply do something like this:</p> <ul> <li>Open up Visual Studio command prompt (Start -> Programs -> Microsoft Visual Studio 200X -> Visual Studio Tools -> Visual Studio 200X Command Prompt)</li> <li>Run the following command:</li> </ul> <blockquote> <p>tf lock /lock:none /workspace:WorkspaceName;USERNAME /recursive $/</p> </blockquote> <p>To get the list of workspaces for a user, just run the following command from the same prompt:</p> <blockquote> <p>tf workspaces /owner:username</p> </blockquote> <p>For more commands, check <strong>tf /?</strong></p>
<p><strong>Use this solution as the very last resort</strong>.</p> <p>I’m using TFS 2012. I went to the TFS database and ran the following queries. And it worked! <strong>Of course be very careful when messing with the database, take backups, etc.</strong></p> <p>The database is called <em>Tfs_&lt;&lt;your_TFS_collection_name&gt;&gt;</em>. Ignore the <em>Tfs_Configuration</em> MSSQL database. I'm not sure but if you don't have a <em>Tfs_&lt;&lt;your_TFS_collection_name&gt;&gt;</em> database, settings might be in the <em>Tfs_DefaultCollection</em> database. Locks are stored in <em>tbl_PendingChange.LockStatus</em>.</p> <pre><code>/*Find correct row*/ SELECT LockStatus, PendingChangeId, * FROM tbl_PendingChange WHERE TargetServerItem like '%&lt;&lt;fileName&gt;&gt;%' /*Set lock status to NULL (mine was set to 2 initially)*/ UPDATE tbl_PendingChange SET LockStatus = NULL WHERE TargetServerItem like '%&lt;fileName&gt;&gt;%' AND PendingChangeId = &lt;&lt;PendingChangeId from above&gt;&gt; </code></pre>
33,750
<p>Due to current limitations on getting DIV tags to work well across browser platforms for the particular liquid layout I desire, I have opted to use a combination of Tables and DIVs for layout. That being said, a couple of issues remain. </p> <p>The FIRST issue is that in Firefox, my table row height for my footer is being rendered differently than it is being rendered in IE when using a table with a height of 100%. What happens is that in Firefox the footer row for the table has a height that is greater than the height specified for the table row. This, in turn, throws off my footer layout. </p> <p>Here is the code for the page:</p> <hr> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta NAME="DESCRIPTION" CONTENT="Cold Fusion Applications and Development"&gt; &lt;meta NAME="keywords" CONTENT="cold fusion, coldfusion, sql server, graphic design, houston, texas, tx, web developer, web development, e-commerce, survey, surveys, web applications, php, mysql, access, foxpro, sql, perl, shopping cart, web programming, macromedia, webmaster, html, cfml, xml, 77057, cfware, cfware.com, www.cfware.com, hosting, dhtml, dynamic html, web programmer, graphic designer, website, resume"&gt; &lt;link href="style.css" rel="stylesheet" type="text/css"&gt; &lt;/head&gt; &lt;!-- BODY --&gt; &lt;body topmargin="0" bottommargin="0" rightmargin="0" leftmargin="0"&gt; &lt;!--TABLE I --&gt; &lt;table class="fullheight" width="100%" height="100%" min-height="100%" border="1" align="center" cellpadding="0" cellspacing="0"&gt; &lt;tr&gt;&lt;td height="116" align="center" valign="top"&gt; &lt;!-- HEADER --&gt; &lt;div class="header"&gt; &lt;div class="lfc"&gt;Cornerstone&lt;/div&gt; &lt;div class="rfl"&gt;&lt;img src="c4sqlogo.gif" width="295" height="68"&gt;&lt;/div&gt; &lt;div class="lf4"&gt;Foursquare&lt;/div&gt; &lt;/div&gt; &lt;div class="spacer"&gt;&lt;/div&gt; &lt;!-- HEADER END --&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt;&lt;td align="center" valign="center" bgcolor="#FFFFFF"&gt; &lt;!-- CONTENT --&gt; &lt;div class="content"&gt; &lt;table class="fullheight" width="100%" height="100%"&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td align="center" valign="middle"&gt; &lt;h1 class="font-black"&gt;Cornerstone Foursquare Church&lt;/h1&gt; &lt;br&gt; &lt;h2&gt;7791 Hillbarn Dr. Houston, TX 77040&lt;/h2&gt; &lt;br&gt; &lt;h2&gt;(713) 856 - 7773&lt;/h2&gt; &lt;br&gt; &lt;br&gt; &lt;h3&gt;Service Times:&lt;br&gt;Sunday Morning Worship 10:30AM&lt;br&gt;Sunday Evening Bible Study 6:00PM &lt;br&gt;Wednesday Evening Bible Study and Prayer 7:00PM&lt;/h3&gt; &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;!-- CONTENT END --&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tfoot height="28"&gt;&lt;td height="28" align="center" valign="middle" bgcolor="#FFFFFF"&gt; &lt;!-- FOOTER --&gt; &lt;div class="clearspacer"&gt;&lt;img src="1.gif" height="10" width="1"&gt;&lt;/div&gt; &lt;div class="footer"&gt;&lt;div class="footertext"&gt;&lt;a href="http://www.c4sq.org"&gt; w w w . c 4 s q . o r g &lt;/a&gt;&lt;/div&gt;&lt;/div&gt; &lt;!-- FOOTER END --&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;!-- TABLE I END --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <hr> <p>And here is the code for the sytle sheet:</p> <pre><code>html, body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; color: :#a02f1d; height: 100%; width: 100%; } a { color: #ffffff; text-decoration: none; font-size: 12; font-weight: 500; } .header { color: #ff0000; margin: 0 auto; width: 760px; height: 116px; background-image: url(stripe.gif); background-repeat: repeat-x; } .fullheight { height:100%;} .lf4 { float: left; margin-top: 0px; clear: left; width: 240px; margin-left: 190px; color: #a02f1d; font-size: 26px; font-weight: semi-bold; font-style: italic; } .lfc { float: left; margin-top: 8px; margin-left: 20px; color: #a02f1d; font-size: 48px; font-weight: semi-bold; font-style: italic; } .rfl { float: right; margin-top: 24px; margin-right: 20px; clear: right; } .content { margin: 0 auto; width: 760px; overflow: hidden; color: :#a02f1d; } .spacer { background-color:#a02f1d; margin: 0 auto; width: 760px; height: 4px; overflow: hidden; } .clearspacer { background-color:#000000; } .footer { color: #ffffff; background-color:#a02f1d; margin: 0 auto; width: 760px; height: 30px; clear: both; } .footertext { color:#ffffff; margin-top: 6px; font-size: 12px; } </code></pre> <hr> <p>The SECOND issue has to do with modifying the existing layout so that there is a centered vertical area of 760px in width that displays in a shade of color different from the surrounding viewport. The primary difficulty is that in order to get my footer to stick to the bottom in both browsers and resize with the viewport, I had to re-adopt a table layout. The current strategy, however, is to use as few nests as possible in order to benefit from the speed and clarity from using DIVs. I would opt to use a DIV layout to the exclusion of a TABLE layout if it were not for the apparently, currently insoluble problem of getting a working sticky-footer to work with a DIV liquid layout.</p>
<p>I know this is quite unrelated, but I recommend that you use <a href="http://validator.w3.org/#validate_by_input" rel="nofollow noreferrer">the w3c validator</a> to validate your HTML once in a while.</p>
<p>A couple suggestions: </p> <p>Add a doctype - if use use the right one you can get IE to standards mode rather than quirks mode <a href="http://www.quirksmode.org/css/quirksmode.html" rel="nofollow noreferrer">http://www.quirksmode.org/css/quirksmode.html</a>, so behaviour will be more consistent between IE and other browsers. </p> <p>As suggested by K4emic - validate your markup. </p> <p>Add a css reset to zero default margins and paddings, a good starting point here <a href="http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/" rel="nofollow noreferrer">http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/</a>. </p> <p>You will find that these things will make chasing down layout bugs a lot easier. Otherwise, you just won't know where to start, is it your css, your html, the default browser stylings, the rendering mode of IE......? </p>
41,220
<p>If I have Python code</p> <pre><code>class A(): pass class B(): pass class C(A, B): pass </code></pre> <p>and I have class <code>C</code>, is there a way to iterate through it's super classed (<code>A</code> and <code>B</code>)? Something like pseudocode:</p> <pre><code>&gt;&gt;&gt; magicGetSuperClasses(C) (&lt;type 'A'&gt;, &lt;type 'B'&gt;) </code></pre> <p>One solution seems to be <a href="http://docs.python.org/lib/module-inspect.html" rel="noreferrer">inspect module</a> and <code>getclasstree</code> function.</p> <pre><code>def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type] </code></pre> <p>but is this a "Pythonian" way to achieve the goal?</p>
<p><code>C.__bases__</code> is an array of the super classes, so you could implement your hypothetical function like so:</p> <pre><code>def magicGetSuperClasses(cls): return cls.__bases__ </code></pre> <p>But I imagine it would be easier to just reference <code>cls.__bases__</code> directly in most cases.</p>
<p>The inspect module was a good start, use the <a href="http://docs.python.org/library/inspect.html#inspect.getmro" rel="nofollow noreferrer">getmro</a> function:</p> <blockquote> <p>Return a tuple of class cls’s base classes, including cls, in method resolution order. No class appears more than once in this tuple. ...</p> </blockquote> <pre><code>&gt;&gt;&gt; class A: pass &gt;&gt;&gt; class B: pass &gt;&gt;&gt; class C(A, B): pass &gt;&gt;&gt; import inspect &gt;&gt;&gt; inspect.getmro(C)[1:] (&lt;class __main__.A at 0x8c59f2c&gt;, &lt;class __main__.B at 0x8c59f5c&gt;) </code></pre> <p>The first element of the returned tuple is <code>C</code>, you can just disregard it.</p>
4,541
<p>I'm having major rendering issues in Safari with the web application I'm working on. Most of the design is done with divs using absolute positioning. This renders fine on Internet Explorer, Firefox, Chrome, Opera, Netscape, and konqueror. In Safari, it's just a jumbled mess. </p> <p>Does Safari lack support for absolute positioning of div elements? </p> <p>What is the best way to trouble shoot and find out what is going on with the safari browser? <a href="https://i.stack.imgur.com/gtgCi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gtgCi.jpg" alt="alt text"></a></p> <p>UPDATE: I'd like to note I did find the issue, and I would like to thank everyone that gave suggestions. It was the WebKit's "Inspect Element" that gave the most useful information. It appears that their were conflicts with inline styles and styles from the CSS. While safari grabed the styles from the .css file, the rest of the browsers were using the inline styles. i was able to see those conflicts with the information in the tool that was suggested. </p>
<p>The <code>readonly</code> keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the <code>const</code> modifier, which must have its value set at compile time. Using <code>readonly</code> you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of.</p> <p>Also use it if you don't want to have to recompile external DLLs that reference the constant (since it gets replaced at compile time).</p>
<p>There can be a performance benefit in WPF, as it removes the need for expensive DependencyProperties. This can be especially useful with collections</p>
34,947
<p>The company I just started working for is using <a href="http://www.stripesframework.org/display/stripes/Home" rel="noreferrer">Stripes</a> for parts of its web page development these days, and while it seems to be a nice enough web framework it no one really uses it-- it is almost non existent on the 'net. It's not even first in it's <a href="http://www.google.com/search?client=opera&amp;rls=en&amp;q=stripes&amp;sourceid=opera&amp;ie=utf-8&amp;oe=utf-8" rel="noreferrer">google search</a> and the result you <strong>do</strong> get is for its old home page.</p> <p>So, do any of you people use Stripes? Of your own volition? Do you know of any good tutorials / examples?</p>
<p>I've never used (or even heard of) Stripes.</p> <p>Regardless, there's a book from <a href="http://www.pragprog.com/" rel="nofollow noreferrer">The Pragmatic Bookshelf</a> called <a href="http://www.pragprog.com/titles/fdstr/stripes" rel="nofollow noreferrer">Stripes: ...and Java web development is fun again</a> that may be worth checking out. You could also check out the Stripes <a href="https://sourceforge.net/mail/?group_id=145476" rel="nofollow noreferrer">mailing list archive</a>.</p>
<p>We considered it when we were looking at open source frameworks. But we saw the same thing your did that there really just isn't much support or information for it. You should always weight the community support factor surrounding open source projects before picking one. (which is what you are doing here)</p>
3,649
<p>Can anyone point me to a tutorial on the best way to open a connection from client to server, read in a binary file and send its contents reliably across the network connection? Even better, is there an open source library that already does this that I could refer to? </p>
<p>You should look into binary serialization and sending it over a TCP socket.</p> <p>Good explanation on different types of serialization:</p> <p><a href="http://www.dotnetspider.com/resources/408-XML-serialization-Binary-serialization.aspx" rel="noreferrer">http://www.dotnetspider.com/resources/408-XML-serialization-Binary-serialization.aspx</a></p> <p>Good primer on TCP Client/Server in C#:</p> <p><a href="http://www.codeproject.com/KB/IP/tcpclientserver.aspx" rel="noreferrer">http://www.codeproject.com/KB/IP/tcpclientserver.aspx</a></p>
<p>How about using HTTP or FTP? They were sort of made for this.</p> <p>Alex</p>
12,086
<p>I haven't programmed games for about 10 years (My last experience was DJGPP + Allegro), but I thought I'd check out XNA over the weekend to see how it was shaping up.</p> <p>I am fairly impressed, however as I continue to piece together a game engine, I have a (probably) basic question.</p> <p>How much should you rely on C#'s Delegates and Events to drive the game? As an application programmer, I use delegates and events heavily, but I don't know if there is a significant overhead to doing so.</p> <p>In my game engine, I have designed a "chase cam" of sorts, that can be attached to an object and then recalculates its position relative to the object. When the object moves, there are two ways to update the chase cam.</p> <ul> <li>Have an "UpdateCameras()" method in the main game loop.</li> <li>Use an event handler, and have the chase cam subscribe to object.OnMoved.</li> </ul> <p>I'm using the latter, because it allows me to chain events together and nicely automate large parts of the engine. Suddenly, what would be huge and complex get dropped down to a handful of 3-5 line event handlers...Its a beauty.</p> <p>However, if event handlers firing every nanosecond turn out to be a major slowdown, I'll remove it and go with the loop approach.</p> <p>Ideas?</p>
<p>If you were to think of an event as a subscriber list, in your code all you are doing is registering a subscriber. The number of instructions needed to achieve that is likely to be minimal at the CLR level.</p> <p>If you want your code to be generic or dynamic, then you're need to check if something is subscribed prior to calling an event. The event/delegate mechanism of C# and .NET provides this to you at very little cost (in terms of CPU).</p> <p>If you're really concerned about every clock cycle, you'd never write generic/dynamic game logic. It's a trade off between maintainable/configurable code and outright speed.</p> <p>Written well, I'd favour events/delegates until I could prove it is an issue.</p> <p>The only way you'll truly know if it is an issue for you is by profiling your code -- which you should do anyway for any game development!</p>
<p>XNA encourages the use of interfaces, events and delegates to drive something written with it. Take a look at the GameComponent related classes which set this up for you.</p> <p>The answer is, "As much as you feel comfortable with".</p> <p>To elaborate a little bit, If for example you take and inherit from the gamecomponent class into a cameracontroller class and add it to the Game.Component collection. Then you can create your camera classes and add them to your cameracontroller. </p> <p>Doing this will cause the cameracontroller to be called regularly and be able to select and activate the proper camera or multiple cameras if that is what you are going for.</p> <p>Here is an example of this (All of his tutorials are excellent): <a href="http://roecode.wordpress.com/2008/02/11/xna-framework-gameengine-development-part-10-cameramanager-gamecomponents/" rel="nofollow noreferrer">ReoCode</a></p>
8,942
<p>It took me 2 days (and a lot of head/wall pounding) to finally discover that the reason ad-hoc distribution wasn't working for me was because my app-name had UTF-8 characters. I'm still boggling over how such a widely international platform like the Apple iPhone can prohibit this.</p> <p><em>i.e.</em>, if my app were a Chinese game of Go, am I not allowed to call it "Go! (圍棋)"?!</p> <p>Anyway, I'm wondering...</p> <ul> <li>Is this an actual limitation, or a bug in the ad-hoc process?</li> <li>Are there other restrictions on app-name (perhaps chars that don't play well with unix, like ?, *, !, &amp;, etc.)</li> <li>Is any of this documented, anywhere? (If so, where :)</li> <li>Can anyone point to an example of an app in the app-store with UTF-8 chars (particularly Japanese/Chinese) in the name?</li> </ul> <p>Thanks!</p> <p>(I know: it looks like several questions, but they really are all related!)</p>
<p>Turns out (according to DTS), it's a bug in the way iTunes handles ad-hoc distribution. This problem is specific to ad-hoc -- my developer distribution works fine, and I'm told the app-store will handle it fine, too -- it's just ad-hoc distribution (the common mechanism for things like beta-testing.)</p> <p>In part, DTS's response was:</p> <p>"I've been able to reproduce it. I've also confirmed it only appears to be an issue for Ad Hoc distribution, so I'm inclined to believe it's a bug in iTunes (I tested in 8.0.1, the latest).</p> <p>I'm awaiting a ruling from iPhone OS engineering on this, but I would recommend you file a bug with your test case app."</p> <p>(Hey, do I get to vote-up my own answer? Is that cheating? :D)</p> <p>(Answer: no you can't. So I guess it would be ;)</p>
<p>OSX in general supports UTF8 natively, throughout Cocoa to the Filesystem.</p> <p>An example in 日本語: <a href="http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=294753911&amp;mt=8" rel="nofollow noreferrer">http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=294753911&amp;mt=8</a></p> <p>If I had to guess, you probably have to name your application something in ASCII but you can make the application title UTF8. Not sure though.</p>
33,417
<p>Visual Studio includes support for __forceinline. The Microsoft Visual Studio 2005 documentation states:</p> <blockquote> <p>The __forceinline keyword overrides the cost/benefit analysis and relies on the judgment of the programmer instead.</p> </blockquote> <p>This raises the question: When is the compiler's cost/benefit analysis wrong? And, how am I supposed to know that it's wrong? </p> <p>In what scenario is it assumed that I know better than my compiler on this issue?</p>
<p>You know better than the compiler only when your profiling data tells you so.</p>
<p>There are several situations where the compiler is not able to determine categorically whether it is appropriate or beneficial to inline a function. Inlining may involve trade-off's that the compiler is unwilling to make, but you are (e.g,, code bloat).</p> <p>In general, modern compilers are actually pretty good at making this decision.</p>
18,313
<p>We are developing a desktop application(visual basic 6.0).We have our own logging framework. What are good practices? When we have a web application, then we can control the level of logging. How to go about in a desktop app?</p>
<p>Any answer needs to be considered based on your environment:</p> <ul> <li>Do your business rules (or laws) <em>require</em> certain activities to be logged?</li> <li>Is security an issue?</li> <li>Do actions need to be traceable?</li> <li>Is the size of the log file (or the amount of disk space) an issue?</li> <li>Is your motivation to record activity, to debug, or both?</li> </ul> <p>With those in mind:</p> <ul> <li>Consider allowing the user to select the verbosity, or "logging level."</li> <li>Log all program errors and significant user errors.</li> <li>Log any activities that affect system configuration or operation.</li> <li>Log the start and end of user sessions.</li> <li>Log the start and end of the application.</li> <li>Consider logging the first time a significant activity occurs.</li> </ul> <p>Other suggestions:</p> <ul> <li>Include timestamps, either in each log or at the beginning of a "group" of logs, as best appropriate for your application.</li> <li>If you're logging to a file, consider rotating the log (<em>i.e.</em> closing one file and opening a new one) when it reaches a certain size or age.</li> <li>If the application contains several modules, include the name of the module in each log.</li> <li>If more than one person uses the application (shared computer?), log the user ID at the beginning of each session.</li> <li>Assign log "levels" based on the severity (Error, Warning, Info, Debug). The <code>syslog</code> specification defines 7 "standard" levels that serve as a good reference.</li> <li>Ask your customer what they expect to see in the log.</li> </ul>
<p>An important feature to consider is to allow for adjustment of the log level dynamically at run time without requiring stopping and restarting the application (I've implemented this on *nix with a custom signal handler). This is a great help when debugging in the field. </p> <p>Many times, a misbehaving application will behave fine when restarted. Dynamically tweakable log levels let you see whats going on before you release all your resources back to the OS.</p>
31,470
<p>The situation: We're out of beta and version 1.0 has been released to several customer sites. Team A is already busy working on version 1.1 that will have incremental bugfixes and usability tweaks, while another team works on version 2.0 with large-scale changes, where the core of the product may have been completely redesigned. Now, most of the changes made for 1.1 will have to make their way into 2.0 at some point, and some of the bug fixes made in the 2.0 branch might in fact need to be scheduled for an earlier release. The problem is that since 2.0 has fundamental differences, no changes from 1.1 can be merged in without manual conversion, nor vice versa.</p> <p>My question: What are the best revision control practises to minimise merge conflicts and duplicate work in this kind of situation? How can I ensure that my teams spend as little time and effort as possible on revision control issues, while still providing regular patches to customers?</p>
<p>One good way is to fix each bug in the stable branch and merge the stable branch into the development branch. This is the <a href="http://www.cmcrossroads.com/bradapp/acme/branching/branch-structs.html#ParallelMaintDev" rel="nofollow noreferrer">Parallel Maintenance/Development Lines</a> pattern, and the key is to merge early and often. Merging infrequently and late means that the development branch is unrecognisable compared to the stable one, or the bug cannot be repeated in the same way.</p> <p><a href="http://subversion.tigris.org/" rel="nofollow noreferrer">Subversion</a> includes merge tracking since version 1.5 so you ensure that the same change set is not merged twice, causing silly conflicts. Other systems exist (e.g. <a href="http://git-scm.com/" rel="nofollow noreferrer">Git</a>, <a href="http://mercurial.selenic.com/" rel="nofollow noreferrer">Mercurial</a>, <a href="http://www.accurev.com" rel="nofollow noreferrer">Accurev</a>, <a href="http://www.perforce.com/" rel="nofollow noreferrer">Perforce</a>) that let you make queries of the type "what changes on branch A have not been merged into branch B?" and cherry-pick the fixes you need across to the dev branch.</p>
<p>Merge early, merge often, and make sure that QA on the mainline knows and regresses/verifies the defects fixed in each patch of the maintenance releases. </p> <p>It's really easy to let something slip out and "unfix" a bug in a subsequent release, and let me tell you, customers don't care about how complicated it can get to manage multiple branches -- that's your job.</p> <p>Make sure you're using a source control system that supports branching and merging (I've had experience with Perforce and SVN, and while Perforce is better, SVN is free).</p> <p>I also believe that having a single person responsible for performing the merges in a consistent manner helps ensure that they happen regularly. It's generally been me or one of the senior people on our team.</p>
6,634
<p>I have following POJOs:</p> <pre><code>class Month { long id; String description; List&lt;Day&gt; days; // always contains 29, 30 or 31 elements } class Day { byte nr; // possible values are 1-31 String info; } </code></pre> <p>Is there a way to store these objects into following DB structure using JPA+Hibernate:</p> <p>Table MONTHS:</p> <pre>id;description;</pre> <p>Table DAYS:</p> <pre>id-of-month;nr-of-day;info;</pre> <p>Any better solution for this situation?</p>
<p>If you can't change your pojo's or table structure you are a bit screwed. If you can then a simple annotated pojo will work. </p> <pre><code>class Month { @Id private long id; private String description; @OneToMany(mappedBy="month",fetchType=Lazy) private List&lt;Day&gt; days; } </code></pre> <p>---- Surrogate key required DB change for Days table</p> <pre><code>class Day { @Id private int id; private Month month; private byte nr; // possible values are 1-31 private String info; } </code></pre>
<p>Here is one solution I found:</p> <pre><code>class Month { long id; String description; @CollectionOfElements(fetch = FetchType.EAGER) @IndexColumn(name = "nr-of-day") List&lt;Day&gt; days; // always contains 29, 30 or 31 elements } @Embeddable class Day { byte nr; // possible values are 1-31 String info; } </code></pre> <p>@CollectionOfelements and @IndexColumn are Hibernate annotations. If I use @OneToMany annotation available in JPA, hibernate creates 3 tables instead of 2.</p> <p>My only problem now is that Day.nr is saved twice: first as IndexColumn of the List (0-based counter) and second time as field of class Day (1-based counter).</p>
41,207
<p>We got <a href="https://3dprinting.meta.stackexchange.com/questions/314/can-we-get-mathjax-enabled">MathJax enabled</a>. Today I learned that there is even more! We could have <a href="https://worldbuilding.meta.stackexchange.com/questions/9710/can-we-extend-mhchem-support-in-mathjax-to-include-physical-units?cb=1"><strong>support for Physical units</strong> enabled as part of the mhchem package</a>! We use physical units <strong>a lot</strong> and demand the SI formatting. Let me quote from Worldbuilding:</p> <blockquote> <p>Chemistry Stack Exchange is obviously the main consumer of this feature and has a <a href="https://worldbuilding.meta.stackexchange.com/questions/9710/can-we-extend-mhchem-support-in-mathjax-to-include-physical-units?cb=1">nice FAQ on its use</a>. The chemists get two things that we don't:</p> <ul> <li><code>\require{mhchem}</code> is implicit... you get support automatically without having to require it explicitly.</li> <li>They get physical unit formatting via <code>$\pu{273.15 K}$</code>, which currently renders as a grumpy error on WB.SE and WB meta that looks [with only mhchem enabled] like this <a href="https://i.stack.imgur.com/NyXoU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NyXoU.png" alt="mathjax markup error" /></a></li> </ul> </blockquote> <p><strong>Can we have that too? Pretty please?</strong> I am tired of having to type <code>$273.15\ \text{K}$</code> and such, especially if it is complex things in the unit!</p>
<p>The deed is done. Behold! In all its glory:</p> <p><span class="math-container">$$\pu{273.15 K}$$</span></p>
<p>I do not support this request to support physical units.</p> <p><em>(vote up this answer if you are not in favor)</em></p>
81
<p>Up to now in my application, I've been supporting all flavors of Windows from Windows 98 to Windows NT/2000 to XP to Vista.</p> <p>But because of adding Unicode in my next version, support of Windows 98 would still be possible, but very difficult.</p> <p>I know there are still some of my users running Windows 98. </p> <p>What are the pros and cons of me no longer supporting Windows 98?</p>
<p>Dropping support for Win98 opens up a whole host of new Win32 API's that you can use in your software. This will allow you to provide a better experience for the majority of your customers on newer OS's.</p> <p>Continue to provide the current version of your software for Win98 users, but make it clear that Win98 will not be supported in future versions of your software.</p> <p>I think most Win98 users are starting to get the message and will be upgrading soon. Also, if they are unwilling to pay for upgrades to their computer/OS, they are unlikely to be willing to pay for upgrades to your software ;)</p>
<p>Depending on your roadmap and technologies you use - it may be possible (but a bit of a pain) to branch your code. Using a decent SCM system, you could develop in your "new" branch and back-port (merge) features and bug fixes that are also relevant to the win98 branch.</p> <p>It's a bit of work, but it would allow you to continue to provide new features to all customers, and not leave your win98 users out of the process.</p>
41,028
<p>What are the most user-friendly color combinations for Web 2.0 websites, such as background, button colors, etc.? </p>
<p><a href="http://www.colorschemer.com/online.html" rel="noreferrer">ColorSchemer</a> will suggest good schemes for you.</p> <p>If you want to try something out on your own, try <a href="http://www.colorcombos.com/" rel="noreferrer">Color Combinations</a>.</p>
<p><a href="http://useit.mondosearch.com/cgi-bin/MsmFind.exe?QUERY=color" rel="nofollow noreferrer">search for color on useit</a> </p> <p><a href="http://www.boxesandarrows.com/search?q=color" rel="nofollow noreferrer">search for color on boxesandarrows</a></p> <p>There has been loads of research on this sort of stuff and most of it is conflicting a couple of good jump off points are listed above.</p> <p>Generally lighter backgrounds and good contrast are favoured by all researchers but the details get niggly.</p>
4,799
<p>Want a WYSIWYG jQuery Editor as an example to illustrate how to use jQuery to built OOP javascript component. </p> <p>P.S. It is so good stackoverflow can use markdown... Would be a heaven if users would love such thing too</p>
<p><a href="http://jhtmlarea.codeplex.com" rel="nofollow noreferrer">jHtmlArea - WYSIWYG HTML Editor for jQuery</a></p> <p>A simple, light weight, extensible WYSIWYG HTML Editor built on top of jQuery. This component allows you to easily display a WYSIWYG HTML Editor in place of any TextArea DOM Elements on the page. The minified script alone is 7kb, and with css and image files it's a total of 15kb.</p> <p>This project also include Visual Studio JavaScript Intellisense support.</p> <p><a href="http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=jhtmlarea&amp;DownloadId=76574" rel="nofollow noreferrer">alt text http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=jhtmlarea&amp;DownloadId=76574</a></p>
<p><a href="http://wmd-editor.com/features#compatibility" rel="nofollow noreferrer">http://wmd-editor.com/features#compatibility</a></p> <p>or maybe if you just have time to write/modify for your own parse (as i will do) use this: </p> <p><a href="http://markitup.jaysalvat.com" rel="nofollow noreferrer">http://markitup.jaysalvat.com</a></p>
11,072
<pre><code>public enum myEnum { VAL1(10), VAL2(20), VAL3("hai") { public Object getValue() { return this.strVal; } public String showMsg() { return "This is your msg!"; } }; String strVal; Integer intVal; public Object getValue() { return this.intVal; } private myEnum(int i) { this.intVal = new Integer(i); } private myEnum(String str) { this.strVal = str; } } </code></pre> <p>In the above enum what exactly happens when I add a constant specific class body for VAL3?<br><br> The type of VAL3 is definetly a subtype of myEnum as it has overloaded and additional methods. (the class type comes as 'myEnum$1' ) <br><br> But how can the compiler creates a subtype enum extending myEnum as all the enums are already extending java.lang.enum ? <br></p>
<p>Your class myEnum inherits from java.lang.Enum. VAL3 is an anonymous inner class that inherits from myEnum called myEnum$1. Think of the enum keyword as syntatic sugar. It sets up classes with normal inheritance trees for you, but will not allow you to extend java.lang.Enum or myEnum directly.</p>
<p>From decompiler</p> <pre><code> package com.sun.tools.xjc.outline; public final class Aspect extends Enum { public static final Aspect EXPOSED; public static final Aspect IMPLEMENTATION; private static final Aspect $VALUES[]; static { EXPOSED = new Aspect("EXPOSED", 0); IMPLEMENTATION = new Aspect("IMPLEMENTATION", 1); $VALUES = (new Aspect[] { EXPOSED, IMPLEMENTATION }); } public static final Aspect[] values() { return (Aspect[])$VALUES.clone(); } public static Aspect valueOf(String name) { Aspect arr$[] = $VALUES; int len$ = arr$.length; for(int i$ = 0; i$ &lt; len$; i$++) { Aspect aspect = arr$[i$]; if(aspect.name().equals(name)) return aspect; } throw new IllegalArgumentException(name); } private Aspect(String s, int i) { super(s, i); } } </code></pre>
41,340
<p>example:</p> <pre><code>a_list = [1, 2, 3] a_list.len() # doesn't work len(a_list) # works </code></pre> <p>Python being (very) object oriented, I don't understand why the 'len' function isn't inherited by the object. Plus I keep trying the wrong solution since it appears as the logical one to me</p>
<p>Guido's explanation is <a href="http://mail.python.org/pipermail/python-3000/2006-November/004643.html" rel="noreferrer">here</a>:</p> <blockquote> <p>First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much later). There are two intertwined reasons actually, both HCI:</p> <p>(a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of doing the same thing using a raw OO notation.</p> <p>(b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method.</p> <p>Saying the same thing in another way, I see ‘len‘ as a built-in operation. I’d hate to lose that. /…/</p> </blockquote>
<p>Maybe you're looking for <code>__len__</code>. If that method exists, then len(a) calls it:</p> <pre><code>&gt;&gt;&gt; class Spam: ... def __len__(self): return 3 ... &gt;&gt;&gt; s = Spam() &gt;&gt;&gt; len(s) 3 </code></pre>
10,953
<p>Staring JBoss server from within Eclipse Ganymede gives me the following problem: "Server JBoss v4.0 at localhost was unable to start within 120 seconds. If the server requires more time, try increasing the timeout in the server editor."</p> <p>The console shows JBoss has started in so and so minutes but soon after, there is a pop up if the above message. I can also start the JBoss externally. </p>
<p>I had a similar problem, but it was with a Tomcat 5.5 server. The startup time was quite important, so I got this error.</p> <p>To solve this problem, I did that steps: In Preferences, Server, I changed the property "Server timeout delay" to "Unlimited".</p> <p><strong>Edit:</strong></p> <p>For Eclipse Ganymede, you must do that: In the server view, double-click on your server JBoss. In the overview, you have a "Timeouts" panel (by default, it is collapsed). You can define the timeouts for server start and stop operations.</p>
<p>You may check whether you are running Jboss version 4.0.4 or version 4.2.2. You might get this error when you have installed Jboss 4.2.2 but configured Jboss 4.0.4 in Eclipse.</p>
38,182
<p>Suppose that I have a Java class with a static method, like so:</p> <pre> class A { static void foo() { // Which class invoked me? } } </pre> <p>And suppose further that class A has an arbitrary number of subclasses:</p> <pre> class B extends A { } class C extends A { } class D extends A { } ... </pre> <p>Now consider the following method invocations:</p> <pre> A.foo(); B.foo(); C.foo(); D.foo(); ... </pre> <p>My question is, how can method <code>foo()</code> tell which class is invoking it?</p>
<p>It can't, and that's part of the problem with static methods. As far as the compiler is concerned <code>A.foo()</code> and <code>B.foo()</code> are exactly the same thing. In fact, they compile down to the same bytecode. You can't get more similar than that.</p> <p>If you really need this sort of information, use a singleton and turn <code>foo()</code> into an instance method. If you still like the static syntax, you can build a facade <code>A.foo()</code>.</p>
<pre><code>class A { static void foo(A whoIsCalingMe) { // Which class invoked me? } } </code></pre>
35,851
<p>As I understand it, when asked to reserve a larger block of memory, the realloc() function will do one of three different things:</p> <p><code><pre> if free contiguous block exists grow current block else if sufficient memory allocate new memory copy old memory to new free old memory else return null </pre></code></p> <p>Growing the current block is a very cheap operation, so this is behaviour I'd like to take advantage of. However, if I'm reallocating memory because I want to (for example) insert a char at the start of an existing string, I don't want realloc() to copy the memory. I'll end up copying the entire string with realloc(), then copying it again manually to free up the first array element.</p> <p>Is it possible to determine what realloc() will do? If so, is it possible to achieve in a cross-platform way?</p>
<p><code>realloc()</code>'s behavior is likely dependent on its specific implementation. And basing your code on that would be a terrible hack which, to say the least, violates encapsulation.</p> <p>A better solution for your specific example is:</p> <ol> <li>Find the size of the current buffer <ul> <li>Allocate a new buffer (with <code>malloc()</code>), greater than the previous one</li> <li>Copy the prefix you want to the new buffer</li> <li>Copy the string in the previous buffer to the new buffer, starting after the prefix</li> <li>Release the previous buffer</li> </ul></li> </ol>
<p>No <strike>- and if you think about it, it can't work. Between you checking what it's going to do and actually doing it, another process could allocate memory.</strike> In a multi-threaded application this can't work. Between you checking what it's going to do and actually doing it, another thread could allocate memory.</p> <p>If you're worried about this sort of thing, it might be time to look at the data structures you're using to see if you can fix the problem there. Depending on how these strings are constructed, you can do so quite efficiently with a well designed buffer.</p>
26,605
<p>I learned that by trying to use the tablesorter plug in from jquery the table needs to use the &lt; thead> and<br> &lt; tbody> tags. I am using an html table, and I use the runat="server" attribute because I need to bind data to the table on the server side. but by using the runat= server attribute the code is rendered in a different way..instead of the view source looking like this which is what is in my markup view :</p> <pre><code>&lt;table id="Table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;1st&lt;/th&gt; &lt;th&gt;2nd&lt;/th&gt; &lt;th&gt;3rd&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt;&lt;td&gt;1st value&lt;/td&gt;&lt;td&gt;2nd value&lt;/td&gt;&lt;td&gt;3rd value&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;1st value&lt;/td&gt;&lt;td&gt;2nd value&lt;/td&gt;&lt;td&gt;3rd value&lt; /td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;1st value&lt;/td&gt;&lt;td&gt;2nd value&lt;/td&gt;&lt;td&gt;3rd value&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;1st value&lt;/td&gt;&lt;td&gt;2nd value&lt;/td&gt;&lt;td&gt;3rd value&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>it looks like that but without the &lt; thead> and &lt; tbody> tags.. which will make the table sorter not work? can someone help me fix this? " .NET 3.5 sp1 is the version I am using"</p>
<p>You should take a look here -<a href="http://www.codeproject.com/KB/aspnet/SortableGridViewjQuery.aspx" rel="noreferrer">Code Project Sortable Gridview using JQuery Tablesorter</a></p> <p>Essentially, you need to use the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.useaccessibleheader.aspx" rel="noreferrer">UseAccessibleHeader property</a> of the Gridview so that a thead tag is outputted in the HTML output.</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { if (this.gridView.Rows.Count &gt; 0) { gridView.UseAccessibleHeader = true; gridView.HeaderRow.TableSection = TableRowSection.TableHeader; gridView.FooterRow.TableSection = TableRowSection.TableFooter; } } </code></pre> <p>if using a html table with the runat="server" attribute instead of asp.net server controls, it looks as though there isn't an easy way to prevent the thead tags from not rendering in the html output. You could use some JQuery to insert thead tags into the DOM on document ready-</p> <pre><code> //in script tags after JQuery and JQuery tablesorter src declarations $(function() { $('#test').prepend( $('&lt;thead&gt;&lt;/thead&gt;').append($('#test tr:first').remove()) ); $("#test").tablesorter(); //your table options }); //your html and asp markup &lt;table id="test" runat="server"&gt; &lt;thead&gt;&lt;tr&gt;&lt;th&gt;1&lt;/th&gt;&lt;th&gt;2&lt;/th&gt;&lt;th&gt;3&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt;&lt;td&gt;my data 1.1&lt;/td&gt;&lt;td&gt;this data 1.2&lt;/td&gt;&lt;td&gt;that data 1.3&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;this data 2.1&lt;/td&gt;&lt;td&gt;that data 2.2&lt;/td&gt;&lt;td&gt;my data 2.3&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;that data 3.1&lt;/td&gt;&lt;td&gt;my data 3.2&lt;/td&gt;&lt;td&gt;this data 3.3&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>outputs this, which works correctly with tablesorter-</p> <pre><code>&lt;table id="test"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="header"&gt;1&lt;/th&gt; &lt;th class="header"&gt;2&lt;/th&gt; &lt;th class="header headerSortDown"&gt;3&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;this data 1.1&lt;/td&gt; &lt;td&gt;that data 1.2&lt;/td&gt; &lt;td&gt;my data 1.3&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;my data 2.1&lt;/td&gt; &lt;td&gt;this data 2.2&lt;/td&gt; &lt;td&gt;that data 2.3&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;that data 3.1&lt;/td&gt; &lt;td&gt;my data 3.2&lt;/td&gt; &lt;td&gt;this data 3.3&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
<p>start with this...</p> <pre><code>print("&lt;table class='turnMeIntoTableSort'&gt;&lt;tr&gt;&lt;td&gt;heading1&lt;/td&gt;&lt;td&gt;heading2&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;content1&lt;/td&gt;&lt;td&gt;content2&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;content3&lt;/td&gt;&lt;td&gt;content4&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;"); </code></pre> <p>then do this:</p> <pre><code>print("$(document).ready(){ $('table.turnMeIntoTableSort &gt; tr:first').wrap('&lt;thead&gt;&lt;/thead&gt;'); $('table.turnMeIntoTableSort &gt; tr:gt(1)').wrapAll('&lt;tbody&gt;&lt;/tbody&gt;'); //now draw the tablesorter $('table.turnMeIntoTableSort').tablesorter(); }"); </code></pre>
48,295
<p>Is it faster to do the following:</p> <pre><code> if ($var != 'test1' &amp;&amp; $var != 'test2' &amp;&amp; $var != 'test3' &amp;&amp; $var != 'test4') { ... } </code></pre> <p>Or:</p> <pre><code> if (!in_array($var, array('test1', 'test2', 'test3', 'test4') { ... } </code></pre> <p>Is there a number of values at which point it's faster to do one or the other?</p> <p>(In this case, the array used in the second option doesn't alreay exist.)</p>
<p>i'd strongly suggest just using <code>in_array()</code>, any speed difference would be negligible, but the readability of testing each variable separately is horrible.</p> <p>just for fun here's a test i ran:</p> <pre><code>$array = array('test1', 'test2', 'test3', 'test4'); $var = 'test'; $iterations = 1000000; $start = microtime(true); for($i = 0; $i &lt; $iterations; ++$i) { if ($var != 'test1' &amp;&amp; $var != 'test2' &amp;&amp; $var != 'test3' &amp;&amp; $var != 'test4') {} } $end = microtime(true); print &quot;Time1: &quot;. ($end - $start).&quot;&lt;br /&gt;&quot;; $start2 = microtime(true); for($i = 0; $i &lt; $iterations; ++$i) { if (!in_array($var, $array) ) {} } $end2 = microtime(true); print &quot;Time2: &quot;.($end2 - $start2).&quot;&lt;br /&gt;&quot;; // Time1: 1.12536692619 // Time2: 1.57462596893 </code></pre> <p>slightly trivial note to watch for, if <code>$var</code> is not set, method 1 takes much longer (depending on how many conditions you test)</p> <h2>Update for newer PHP versions:</h2> <p>Martijn: I'ved extended the array to <strong>five</strong> elements, and look for <code>test3</code>, as sort of an average case.</p> <p><strong>PHP5.6</strong></p> <pre><code>Time1: 0.20484399795532 Time2: 0.29854393005371 </code></pre> <p><strong>PHP7.1</strong></p> <pre><code>Time1: 0.064045906066895 Time2: 0.056781053543091 </code></pre> <p><strong>PHP7.4</strong></p> <pre><code>Time1: 0.048759937286377 Time2: 0.049691915512085 </code></pre> <p><strong>PHP8.0</strong></p> <pre><code>Time1: 0.045055150985718 Time2: 0.049431085586548 </code></pre> <p>Conclusion: The original test wasnt the best test, and also: In php7+ is has become a matter of preference.</p>
<p>I know this question is nearly 10 years old, but there are other ways to do this. I used method B from <a href="http://nickology.com/2012/07/03/php-faster-array-lookup-than-using-in_array/" rel="nofollow noreferrer">Nick's page</a> with thousands of entries. It was incredibly fast.</p> <pre><code>foreach(array_values($haystack) as $v) $new_haystack[$v] = 1; } // So haystack becomes: $arr[“String1”] = 1; $arr[“String2”] = 1; $arr[“String3”] = 1; // Then check for the key: if (isset($haystack[$needle])) { echo("needle ".$needle." found in haystack"); } </code></pre>
42,042
<p>I wonder why no browser out there has such simple but essential feature. Am I missing something? Is there a technical reason?</p> <p>I'm tired of all those javascript/flash/java hacks out there ...</p>
<p>There is no technical reason preventing the browser from calculating the total bytes to be sent and then tracking how many have been received by the server (Thanks, Kibbee for your comment). Firefox had a functional upload progress indicator until version 0.9, but that <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=249338" rel="noreferrer">build</a> broke it in 2004. </p> <p>Reading through the Bugzilla updates, it seems that this feature doesn't seem to benefit enough users to get any traction from the developers. </p> <p>Users who regularly upload very large files tend to use tools like FTP that are designed for this purpose, so they are not affected.</p>
<p>The web browser has always been that, a browser of the web. It is a mechanism for consumption. Our ability to upload information through the same portal is somewhat of a hack. </p>
29,123
<p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p> <p>Say, to allow..</p> <pre><code>mystatement "Something" </code></pre> <p>Or,</p> <pre><code>new_if True: print "example" </code></pre> <p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
<p>You may find this useful - <a href="http://eli.thegreenplace.net/2010/06/30/python-internals-adding-a-new-statement-to-python/" rel="noreferrer">Python internals: adding a new statement to Python</a>, quoted here:</p> <hr> <p>This article is an attempt to better understand how the front-end of Python works. Just reading documentation and source code may be a bit boring, so I'm taking a hands-on approach here: I'm going to add an <code>until</code> statement to Python.</p> <p>All the coding for this article was done against the cutting-edge Py3k branch in the <a href="http://code.python.org/hg/branches/py3k/" rel="noreferrer">Python Mercurial repository mirror</a>.</p> <h3>The <code>until</code> statement</h3> <p>Some languages, like Ruby, have an <code>until</code> statement, which is the complement to <code>while</code> (<code>until num == 0</code> is equivalent to <code>while num != 0</code>). In Ruby, I can write:</p> <pre><code>num = 3 until num == 0 do puts num num -= 1 end </code></pre> <p>And it will print:</p> <pre><code>3 2 1 </code></pre> <p>So, I want to add a similar capability to Python. That is, being able to write:</p> <pre><code>num = 3 until num == 0: print(num) num -= 1 </code></pre> <h3>A language-advocacy digression</h3> <p>This article doesn't attempt to suggest the addition of an <code>until</code> statement to Python. Although I think such a statement would make some code clearer, and this article displays how easy it is to add, I completely respect Python's philosophy of minimalism. All I'm trying to do here, really, is gain some insight into the inner workings of Python.</p> <h3>Modifying the grammar</h3> <p>Python uses a custom parser generator named <code>pgen</code>. This is a LL(1) parser that converts Python source code into a parse tree. The input to the parser generator is the file <code>Grammar/Grammar</code><strong>[1]</strong>. This is a simple text file that specifies the grammar of Python.</p> <p><strong>[1]</strong>: From here on, references to files in the Python source are given relatively to the root of the source tree, which is the directory where you run configure and make to build Python.</p> <p>Two modifications have to be made to the grammar file. The first is to add a definition for the <code>until</code> statement. I found where the <code>while</code> statement was defined (<code>while_stmt</code>), and added <code>until_stmt</code> below <strong>[2]</strong>:</p> <pre><code>compound_stmt: if_stmt | while_stmt | until_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] while_stmt: 'while' test ':' suite ['else' ':' suite] until_stmt: 'until' test ':' suite </code></pre> <p><strong>[2]</strong>: This demonstrates a common technique I use when modifying source code I’m not familiar with: <em>work by similarity</em>. This principle won’t solve all your problems, but it can definitely ease the process. Since everything that has to be done for <code>while</code> also has to be done for <code>until</code>, it serves as a pretty good guideline.</p> <p>Note that I've decided to exclude the <code>else</code> clause from my definition of <code>until</code>, just to make it a little bit different (and because frankly I dislike the <code>else</code> clause of loops and don't think it fits well with the Zen of Python).</p> <p>The second change is to modify the rule for <code>compound_stmt</code> to include <code>until_stmt</code>, as you can see in the snippet above. It's right after <code>while_stmt</code>, again.</p> <p>When you run <code>make</code> after modifying <code>Grammar/Grammar</code>, notice that the <code>pgen</code> program is run to re-generate <code>Include/graminit.h</code> and <code>Python/graminit.c</code>, and then several files get re-compiled.</p> <h3>Modifying the AST generation code</h3> <p>After the Python parser has created a parse tree, this tree is converted into an AST, since ASTs are <a href="http://eli.thegreenplace.net/2009/02/16/abstract-vs-concrete-syntax-trees/" rel="noreferrer">much simpler to work with</a> in subsequent stages of the compilation process.</p> <p>So, we're going to visit <code>Parser/Python.asdl</code> which defines the structure of Python's ASTs and add an AST node for our new <code>until</code> statement, again right below the <code>while</code>:</p> <pre><code>| While(expr test, stmt* body, stmt* orelse) | Until(expr test, stmt* body) </code></pre> <p>If you now run <code>make</code>, notice that before compiling a bunch of files, <code>Parser/asdl_c.py</code> is run to generate C code from the AST definition file. This (like <code>Grammar/Grammar</code>) is another example of the Python source-code using a mini-language (in other words, a DSL) to simplify programming. Also note that since <code>Parser/asdl_c.py</code> is a Python script, this is a kind of <a href="http://en.wikipedia.org/wiki/Bootstrapping_%28compilers%29" rel="noreferrer">bootstrapping</a> - to build Python from scratch, Python already has to be available.</p> <p>While <code>Parser/asdl_c.py</code> generated the code to manage our newly defined AST node (into the files <code>Include/Python-ast.h</code> and <code>Python/Python-ast.c</code>), we still have to write the code that converts a relevant parse-tree node into it by hand. This is done in the file <code>Python/ast.c</code>. There, a function named <code>ast_for_stmt</code> converts parse tree nodes for statements into AST nodes. Again, guided by our old friend <code>while</code>, we jump right into the big <code>switch</code> for handling compound statements and add a clause for <code>until_stmt</code>:</p> <pre><code>case while_stmt: return ast_for_while_stmt(c, ch); case until_stmt: return ast_for_until_stmt(c, ch); </code></pre> <p>Now we should implement <code>ast_for_until_stmt</code>. Here it is:</p> <pre><code>static stmt_ty ast_for_until_stmt(struct compiling *c, const node *n) { /* until_stmt: 'until' test ':' suite */ REQ(n, until_stmt); if (NCH(n) == 4) { expr_ty expression; asdl_seq *suite_seq; expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, 3)); if (!suite_seq) return NULL; return Until(expression, suite_seq, LINENO(n), n-&gt;n_col_offset, c-&gt;c_arena); } PyErr_Format(PyExc_SystemError, "wrong number of tokens for 'until' statement: %d", NCH(n)); return NULL; } </code></pre> <p>Again, this was coded while closely looking at the equivalent <code>ast_for_while_stmt</code>, with the difference that for <code>until</code> I've decided not to support the <code>else</code> clause. As expected, the AST is created recursively, using other AST creating functions like <code>ast_for_expr</code> for the condition expression and <code>ast_for_suite</code> for the body of the <code>until</code> statement. Finally, a new node named <code>Until</code> is returned.</p> <p>Note that we access the parse-tree node <code>n</code> using some macros like <code>NCH</code> and <code>CHILD</code>. These are worth understanding - their code is in <code>Include/node.h</code>.</p> <h3>Digression: AST composition</h3> <p>I chose to create a new type of AST for the <code>until</code> statement, but actually this isn't necessary. I could've saved some work and implemented the new functionality using composition of existing AST nodes, since:</p> <pre><code>until condition: # do stuff </code></pre> <p>Is functionally equivalent to:</p> <pre><code>while not condition: # do stuff </code></pre> <p>Instead of creating the <code>Until</code> node in <code>ast_for_until_stmt</code>, I could have created a <code>Not</code> node with an <code>While</code> node as a child. Since the AST compiler already knows how to handle these nodes, the next steps of the process could be skipped.</p> <h3>Compiling ASTs into bytecode</h3> <p>The next step is compiling the AST into Python bytecode. The compilation has an intermediate result which is a CFG (Control Flow Graph), but since the same code handles it I will ignore this detail for now and leave it for another article.</p> <p>The code we will look at next is <code>Python/compile.c</code>. Following the lead of <code>while</code>, we find the function <code>compiler_visit_stmt</code>, which is responsible for compiling statements into bytecode. We add a clause for <code>Until</code>:</p> <pre><code>case While_kind: return compiler_while(c, s); case Until_kind: return compiler_until(c, s); </code></pre> <p>If you wonder what <code>Until_kind</code> is, it's a constant (actually a value of the <code>_stmt_kind</code> enumeration) automatically generated from the AST definition file into <code>Include/Python-ast.h</code>. Anyway, we call <code>compiler_until</code> which, of course, still doesn't exist. I'll get to it an a moment.</p> <p>If you're curious like me, you'll notice that <code>compiler_visit_stmt</code> is peculiar. No amount of <code>grep</code>-ping the source tree reveals where it is called. When this is the case, only one option remains - C macro-fu. Indeed, a short investigation leads us to the <code>VISIT</code> macro defined in <code>Python/compile.c</code>:</p> <pre><code>#define VISIT(C, TYPE, V) {\ if (!compiler_visit_ ## TYPE((C), (V))) \ return 0; \ </code></pre> <p>It's used to invoke <code>compiler_visit_stmt</code> in <code>compiler_body</code>. Back to our business, however...</p> <p>As promised, here's <code>compiler_until</code>:</p> <pre><code>static int compiler_until(struct compiler *c, stmt_ty s) { basicblock *loop, *end, *anchor = NULL; int constant = expr_constant(s-&gt;v.Until.test); if (constant == 1) { return 1; } loop = compiler_new_block(c); end = compiler_new_block(c); if (constant == -1) { anchor = compiler_new_block(c); if (anchor == NULL) return 0; } if (loop == NULL || end == NULL) return 0; ADDOP_JREL(c, SETUP_LOOP, end); compiler_use_next_block(c, loop); if (!compiler_push_fblock(c, LOOP, loop)) return 0; if (constant == -1) { VISIT(c, expr, s-&gt;v.Until.test); ADDOP_JABS(c, POP_JUMP_IF_TRUE, anchor); } VISIT_SEQ(c, stmt, s-&gt;v.Until.body); ADDOP_JABS(c, JUMP_ABSOLUTE, loop); if (constant == -1) { compiler_use_next_block(c, anchor); ADDOP(c, POP_BLOCK); } compiler_pop_fblock(c, LOOP, loop); compiler_use_next_block(c, end); return 1; } </code></pre> <p>I have a confession to make: this code wasn't written based on a deep understanding of Python bytecode. Like the rest of the article, it was done in imitation of the kin <code>compiler_while</code> function. By reading it carefully, however, keeping in mind that the Python VM is stack-based, and glancing into the documentation of the <code>dis</code> module, which has <a href="http://docs.python.org/py3k/library/dis.html" rel="noreferrer">a list of Python bytecodes</a> with descriptions, it's possible to understand what's going on.</p> <h3>That's it, we're done... Aren't we?</h3> <p>After making all the changes and running <code>make</code>, we can run the newly compiled Python and try our new <code>until</code> statement:</p> <pre><code>&gt;&gt;&gt; until num == 0: ... print(num) ... num -= 1 ... 3 2 1 </code></pre> <p>Voila, it works! Let's see the bytecode created for the new statement by using the <code>dis</code> module as follows:</p> <pre><code>import dis def myfoo(num): until num == 0: print(num) num -= 1 dis.dis(myfoo) </code></pre> <p>Here's the result:</p> <pre><code>4 0 SETUP_LOOP 36 (to 39) &gt;&gt; 3 LOAD_FAST 0 (num) 6 LOAD_CONST 1 (0) 9 COMPARE_OP 2 (==) 12 POP_JUMP_IF_TRUE 38 5 15 LOAD_NAME 0 (print) 18 LOAD_FAST 0 (num) 21 CALL_FUNCTION 1 24 POP_TOP 6 25 LOAD_FAST 0 (num) 28 LOAD_CONST 2 (1) 31 INPLACE_SUBTRACT 32 STORE_FAST 0 (num) 35 JUMP_ABSOLUTE 3 &gt;&gt; 38 POP_BLOCK &gt;&gt; 39 LOAD_CONST 0 (None) 42 RETURN_VALUE </code></pre> <p>The most interesting operation is number 12: if the condition is true, we jump to after the loop. This is correct semantics for <code>until</code>. If the jump isn't executed, the loop body keeps running until it jumps back to the condition at operation 35.</p> <p>Feeling good about my change, I then tried running the function (executing <code>myfoo(3)</code>) instead of showing its bytecode. The result was less than encouraging:</p> <pre><code>Traceback (most recent call last): File "zy.py", line 9, in myfoo(3) File "zy.py", line 5, in myfoo print(num) SystemError: no locals when loading 'print' </code></pre> <p>Whoa... this can't be good. So what went wrong?</p> <h3>The case of the missing symbol table</h3> <p>One of the steps the Python compiler performs when compiling the AST is create a symbol table for the code it compiles. The call to <code>PySymtable_Build</code> in <code>PyAST_Compile</code> calls into the symbol table module (<code>Python/symtable.c</code>), which walks the AST in a manner similar to the code generation functions. Having a symbol table for each scope helps the compiler figure out some key information, such as which variables are global and which are local to a scope.</p> <p>To fix the problem, we have to modify the <code>symtable_visit_stmt</code> function in <code>Python/symtable.c</code>, adding code for handling <code>until</code> statements, after the similar code for <code>while</code> statements <strong>[3]</strong>:</p> <pre><code>case While_kind: VISIT(st, expr, s-&gt;v.While.test); VISIT_SEQ(st, stmt, s-&gt;v.While.body); if (s-&gt;v.While.orelse) VISIT_SEQ(st, stmt, s-&gt;v.While.orelse); break; case Until_kind: VISIT(st, expr, s-&gt;v.Until.test); VISIT_SEQ(st, stmt, s-&gt;v.Until.body); break; </code></pre> <p><strong>[3]</strong>: By the way, without this code there’s a compiler warning for <code>Python/symtable.c</code>. The compiler notices that the <code>Until_kind</code> enumeration value isn’t handled in the switch statement of <code>symtable_visit_stmt</code> and complains. It’s always important to check for compiler warnings!</p> <p>And now we really are done. Compiling the source after this change makes the execution of <code>myfoo(3)</code> work as expected.</p> <h3>Conclusion</h3> <p>In this article I've demonstrated how to add a new statement to Python. Albeit requiring quite a bit of tinkering in the code of the Python compiler, the change wasn't difficult to implement, because I used a similar and existing statement as a guideline.</p> <p>The Python compiler is a sophisticated chunk of software, and I don't claim being an expert in it. However, I am really interested in the internals of Python, and particularly its front-end. Therefore, I found this exercise a very useful companion to theoretical study of the compiler's principles and source code. It will serve as a base for future articles that will get deeper into the compiler.</p> <h3>References</h3> <p>I used a few excellent references for the construction of this article. Here they are, in no particular order:</p> <ul> <li><a href="http://www.python.org/dev/peps/pep-0339/" rel="noreferrer">PEP 339: Design of the CPython compiler</a> - probably the most important and comprehensive piece of <em>official</em> documentation for the Python compiler. Being very short, it painfully displays the scarcity of good documentation of the internals of Python.</li> <li>"Python Compiler Internals" - an article by Thomas Lee</li> <li>"Python: Design and Implementation" - a presentation by Guido van Rossum</li> <li>Python (2.5) Virtual Machine, A guided tour - a presentation by Peter Tröger</li> </ul> <p><a href="http://eli.thegreenplace.net/2010/06/30/python-internals-adding-a-new-statement-to-python/" rel="noreferrer">original source</a></p>
<p>Ten years ago you couldn't, and I doubt that's changed. However, it wasn't that hard to modify the syntax back then if you were prepared to recompile python, and I doubt that's changed, either.</p>
26,413
<p>What is the difference between using the <code>Runnable</code> and <code>Callable</code> interfaces when designing a concurrent thread in Java, why would you choose one over the other?</p>
<p>See explanation <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html" rel="noreferrer">here</a>.</p> <blockquote> <p>The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. <strong>A Runnable, however, does not return a result and cannot throw a checked exception.</strong></p> </blockquote>
<p>In addition to all other answers:</p> <p>We can not pass/use Callable to an individual thread for execution i.e. Callable can be used only in Executor Framework. But, Runnable can be passed to an individual thread for execution (new Thread(new CustomRunnable())), as well as can be used in Executor Framework.</p>
17,066
<p>For years, I've been investigating how to create music streams from my computer. I've seen programs, but anything useful I've seen is Windows only (I use a Mac).</p> <p>Eventually, I got interested in <em>how</em> streams work. Is there any way I could create my <em>own</em> stream, possibly using socket functions in <code>PHP</code>? Is there a <code>PHP</code> library for this?</p>
<p>Take a look at <a href="http://ampache.org/" rel="nofollow noreferrer">Ampache</a>. It is a Web-based Open Source Audio file manager. It is implemented with MySQL, and PHP. It allows you to view, edit, and play your audio files via the web.</p>
<p>In the end it all boils down to the protocol you'd want to use. Shoutcast IMHO is plain HTTP, so to <em>make</em> your own stream, you just output the streams content.</p> <p>To make an ogg based webradio work with my Sonos system, I have created a little transcoding wrapper around sox which is is actually written in PHP, so it may be helpful to you to serve as an example.</p> <p>You'll find it here: <a href="http://www.gnegg.ch/ogg2mp3/" rel="nofollow noreferrer">http://www.gnegg.ch/ogg2mp3/</a></p> <p>If you are after implementing your very own streaming protocol - maybe even UDP based, then, I'm afraid, PHP may not be the right solution for the problem - at least not as long as it has its share of problems when used for long running processes (which 5.3 may bring some help for with its integrated garbage collection)</p>
6,697
<p>I'm implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known shape.</p> <p>I would like to write unit tests to test the entire family of functions for this property, without having to write an individual test case for each function (particularly since more functions might be added later). </p> <p>One way to do this would be to iterate over a list of these functions:</p> <pre><code>import unittest import numpy from somewhere import the_functions from somewhere.else import TheClass class Test_the_functions(unittest.TestCase): def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5) def testOutputShape(unittest.TestCase): """Output of functions be of a certain shape""" for function in all_functions: output = function(self.matrix1, self.matrix2) fail_message = "%s produces output of the wrong shape" % str(function) self.assertEqual(self.matrix1.shape, output.shape, fail_message) if __name__ == "__main__": unittest.main() </code></pre> <p>I got the idea for this from <a href="http://www.diveintopython.net/unit_testing/romantest.html" rel="noreferrer">Dive Into Python</a>. There, it's not a list of functions being tested but a list of known input-output pairs. The problem with this approach is that if any element of the list fails the test, the later elements don't get tested.</p> <p>I looked at subclassing unittest.TestCase and somehow providing the specific function to test as an argument, but as far as I can tell that prevents us from using unittest.main() because there would be no way to pass the argument to the testcase.</p> <p>I also looked at dynamically attaching "testSomething" functions to the testcase, by using setattr with a lamdba, but the testcase did not recognize them.</p> <p>How can I rewrite this so it remains trivial to expand the list of tests, while still ensuring every test is run?</p>
<p>You could use a metaclass to dynamically insert the tests. This works fine for me:</p> <pre><code>import unittest class UnderTest(object): def f1(self, i): return i + 1 def f2(self, i): return i + 2 class TestMeta(type): def __new__(cls, name, bases, attrs): funcs = [t for t in dir(UnderTest) if t[0] == 'f'] def doTest(t): def f(slf): ut=UnderTest() getattr(ut, t)(3) return f for f in funcs: attrs['test_gen_' + f] = doTest(f) return type.__new__(cls, name, bases, attrs) class T(unittest.TestCase): __metaclass__ = TestMeta def testOne(self): self.assertTrue(True) if __name__ == '__main__': unittest.main() </code></pre>
<blockquote> <p>The problem with this approach is that if any element of the list fails the test, the later elements don't get tested.</p> </blockquote> <p>If you look at it from the point of view that, if a test fails, that is critical and your entire package is invalid, then it doesn't matter that other elements won't get tested, because 'hey, you have an error to fix'.</p> <p>Once that test passes, the other tests will then run.</p> <p>Admittedly there is information to be gained from knowledge of which other tests are failing, and that can help with debugging, but apart from that, assume any test failure is an entire application failure.</p>
45,165
<p>When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?</p>
<p>This is one of those cases that really boil down to personal preference or situational details. If you're more comfortable and experienced with Python, then say so. Are they asking you to justify it because they're more comfortable with one of the other environments? After you're done, will the system be passed off to someone else for long-term maintenance?</p> <p>If they ask you to use a technology or language that you're not as familiar with, then make sure they know up-front that it's going to take you longer.</p>
<p>I agree with mreggen. Tell them by working in Python you can get things done faster. Getting things done faster possibly means money saved by the client. In the least it means that you are working with a language you a more comfortable in, meaning faster development, debugging, and refactoring time. There will be less time spent looking up documentation on what function to use to find the length of a string, etc. </p>
2,693
<p>I have a simple cart page that displays items that are in someones cart, and having it display via an ASP while from my table. I have a column where a user can delete an entry. I have the ASP working properly, now I am trying to add some AJAX in to it. I have the following code:</p> <pre><code>$("img.delete").click(function() { var id = $('#id').attr('value'); $.ajax({ type: "POST", url: "delete.php", data: "id="+ id, success: function(){ $('tr.selector').remove(); $('div.success').fadeIn(); } }); return false; }); </code></pre> <p>The thing is, how wouild I go about setting it up for each value, because if I use the above, I click one and they will all go. I am confused on how to set it up to work with numerous rows.</p>
<p>You need to select only the item's row for removal. I'm not sure how you have it set up, but if the image element is inside the row you could use:</p> <pre><code> $("img.delete").click(function() { var row = $(this).parents('tr:first'); ... success: function(){ $(row).remove(); //Remove the row containing the image element ... } ... }); </code></pre>
<p>If it is the html id-attribute you want, then that would work. Why don't you try it?</p> <p>EDIT: It might be just row.attr('id'); It have slipped from my mind, havn't ben using jQuery for sometime :)</p>
49,120
<p>This pretty much has me defeated.</p> <p>On XP and earlier versions of Windows you could customise Open With filetypes to include java - jar "myjar.jar", but on Vista this functionality seems to have been removed. I can of course create a .bat file to launch my application, but is it possible to make Vista execute a .jar as required?</p>
<p>You can do it from the command line with 2 utilities.</p> <p>The first one, ASSOC, is used to create a file association. To verify if there is one defined for JAR type :</p> <pre><code>&gt;assoc .jar .jar=jarfile </code></pre> <p>If not found then create it with :</p> <pre><code>&gt;assoc .jar=jarfile </code></pre> <p>The next step is to define the association. This is done with FTYPE.</p> <p>To verify if one is already defined , type </p> <pre><code>&gt;ftype jarfile jarfile="C:\Program Files\Java\jre1.5.0_10\bin\javaw.exe" -jar "%1" %* </code></pre> <p>Again if not found or the wrong JRE is used, use FTYPE to fix the problem</p> <pre><code>&gt;ftype jarfile="C:\Program Files\Java\jre1.5.0_10\bin\javaw.exe" -jar "%1" %* </code></pre>
<p>Use the software JarFix >= 1.1.0 . There is Vista support included and it "recovers" the .jar association!</p> <p>download for example here: <a href="http://www.softpedia.com/get/Others/Miscellaneous/Jarfix.shtml" rel="nofollow noreferrer">http://www.softpedia.com/get/Others/Miscellaneous/Jarfix.shtml</a></p>
46,204
<p>On a Cartesian printer movements are really simple. If we assume the printer has 100 steps/mm on each axis, then a move of 10mm on a axis is just 1000 Steps on that axis.</p> <p>Movements that are not aligned with one axis are also simple. Moving from x,y = 0,0 to 10,10 would be 1000 steps on x and y.</p> <p>On deltas even for simple moves more than one motor has to move. And just calculating the amount of steps on each axis needed to reach the destination probably gives a curved move.</p> <p>So what is the algorithm to calculate the steps for a given move for a delta printer?</p>
<p>There are two main special steps to the technique used by most open-source 3d printer controllers:</p> <ol> <li>Divide each linear gcode segment into lots of very small subsegments ("Segmentation")</li> <li>Use some basic trigonometry or the pythagorean theorem to tie extruder position to carriage height for each of the three towers ("Inverse Kinematics") to find the target position for each small segment</li> </ol> <p>The inverse kinematics are surprisingly simple. A virtual 90 degree triangle is constructed from two known lengths to solve for the unknown third length: </p> <ul> <li>The fixed delta arm length is the hypotenuse of the triangle</li> <li>The horizontal distance between the column joints and end-effector joints is calculated from the XY coordinates of the nozzle and the fixed position of the column, to determine the length of the lower side of the triangle</li> <li>The length of the upper side of the triangle is calculated from the previous two via the pythagorean theorem</li> <li>The length of the upper side is added to the nozzle Z height to get the necessary carriage height</li> </ul> <p>I think the best open-source reference here is Steve Grave's Rostock Kinematics document, rev3 available for download here: <a href="https://groups.google.com/d/msg/deltabot/V6ATBdT43eU/jEORG_l3dTEJ" rel="noreferrer">https://groups.google.com/d/msg/deltabot/V6ATBdT43eU/jEORG_l3dTEJ</a> Some relevant pictures: <a href="https://i.stack.imgur.com/MxCMc.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/MxCMc.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/geOQI.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/geOQI.jpg" alt="enter image description here"></a></p> <p>These inverse kinematics calculations are performed for each carriage to get a "carriage space" target position, and this is performed for every path sub-segment.</p> <p>The results from these steps can then be reinserted back into the standard linear path interpolation techniques for the printer, in which it fires steps in the necessary ratios and at the necessary rates to produce the desired straight-line motion and acceleration/velocity profile. (How THAT is done is a different question.)</p> <p>The net effect is that the printer will move through a series of small "linear" carriage movements (linear meaning constant* speed with respect to time) that collectively approximate the necessary curved (quadratic position with respect to time) carriage motions required to produce a straight-line end-effector move.</p> <p>*(<em>Constant speed before acceleration slowdowns are applied in order to obey dynamics constraints, anyway. Again, that's the subject of a different question.)</em></p> <p>Segmentation is very similar to the process of using a polygon to approximate a circle. If the facets are small enough, the polygon is a good approximation. Higher Segmentation rates produce less path-following error. The primary conceptual difference between drawing circle arcs and Delta motion paths is that the so-called "faceted arc" with Delta Segmentation is constructed in height-vs-time coordinates instead of the X-vs-Y coordinates you'd use to draw a circle on a computer screen. </p> <p>This system is used in large part because support for Delta style printers was originally bolted onto GRBL-based motion planners which were written exclusively for straight-line motion paths in Cartesian printers. It was a relatively minimal modification to the existing codebase compared to implementing full quadratic path interpolation.</p> <p>Techniques have evolved over the years. And alternate approaches are often used: for example, the dc42 fork of RepRapFirmware performs exact path-following without segmentation, by recalculating the proper time for the next step <em>after every step</em>. This is functionally equivalent to approximating a circle with a polygon facet count <em>so high that every pixel on the screen gets its own facet</em>. So it is exactly as accurate as the positioning resolution of the motors allows. The downside is that this segmentation-free technique is fairly processor-intensive, so it only works on relatively fast controllers, not the older 8bit Atmega AVR that powers most existing consumer/hobbyist printers today. </p> <p>Other techniques are possible. The academic parallel robotics control literature is a whole other world of mathematical techniques and complexity in order to produce generalized control algorithms that work for a wide range of robot mechanisms. The version we use in open-source 3d printers is quite simple and application-specific in comparison. </p>
<p>I am describing how this is done in the Marlin firmware.</p> <p>The first step is to split a linear movement from (x, y, z) to (x', y', z') into many discrete segments. To this end, the amount of time the move would take at a given speed is calculated, and the value <em>delta_segments_per_second</em> is used to calculate the number of segments used.</p> <p>This is done in the function <em>prepare_move_delta</em> in the file Marlin_main.cpp. The endpoints of each of these segments is then passed to the function <em>calculate_delta</em>:</p> <pre><code>void calculate_delta(float cartesian[3]) { //reverse kinematics. // Perform reversed kinematics, and place results in delta[3] // The maths and first version has been done by QHARLEY . Integrated into masterbranch 06/2014 and slightly restructured by Joachim Cerny in June 2014 float SCARA_pos[2]; static float SCARA_C2, SCARA_S2, SCARA_K1, SCARA_K2, SCARA_theta, SCARA_psi; SCARA_pos[X_AXIS] = cartesian[X_AXIS] * axis_scaling[X_AXIS] - SCARA_offset_x; //Translate SCARA to standard X Y SCARA_pos[Y_AXIS] = cartesian[Y_AXIS] * axis_scaling[Y_AXIS] - SCARA_offset_y; // With scaling factor. #if (Linkage_1 == Linkage_2) SCARA_C2 = ((sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS])) / (2 * (float)L1_2)) - 1; #else SCARA_C2 = (sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS]) - (float)L1_2 - (float)L2_2) / 45000; #endif SCARA_S2 = sqrt(1 - sq(SCARA_C2)); SCARA_K1 = Linkage_1 + Linkage_2 * SCARA_C2; SCARA_K2 = Linkage_2 * SCARA_S2; SCARA_theta = (atan2(SCARA_pos[X_AXIS], SCARA_pos[Y_AXIS]) - atan2(SCARA_K1, SCARA_K2)) * -1; SCARA_psi = atan2(SCARA_S2, SCARA_C2); delta[X_AXIS] = SCARA_theta * SCARA_RAD2DEG; // Multiply by 180/Pi - theta is support arm angle delta[Y_AXIS] = (SCARA_theta + SCARA_psi) * SCARA_RAD2DEG; // - equal to sub arm angle (inverted motor) delta[Z_AXIS] = cartesian[Z_AXIS]; } </code></pre> <p>This function takes care of the delta geometry and calculations needed to convert the (x,y,z) coordinates of the segment endpoints to corresponding positions for the carriages. The translated coordinates are then passed to <em>plan_buffer_line</em>, which calculates the steps needed for each stepper motor and actually makes these steps happen.</p> <p>The exact kinematics used in this function are explained in much more detail at the <a href="https://github.com/MarlinFirmware/Marlin/wiki/Delta-kinematics" rel="nofollow">Marlin github</a>.</p> <p>What is important to note is that plan_buffer_line moves the carriages linearly, and the printhead thus describes an arc and not a straight line. A straight line move is thus approximated by many small arcs.</p>
199
<p>I have an Excel application in which I want to present the user with a list of the Data Source Names (ie: DSN's), whereby s/he can choose what data source to use.</p> <p>Hopefully once I've got the list, I can easily access the DSN properties to connect to the appropriate database.</p> <p>Please note, I do <em>not</em> want to use a DSN-less connection.</p>
<p>The DSN entries are stored in the registry in the following keys.</p> <pre>HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\ODBC Data Sources HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources</pre> <p>This contains the list of all defined DSN. This acts as an global index and the specific details for each DSN are stored in a key with the DSN name under:</p> <pre>HKEY_CURRENT_USER\Software\ODBC\ODBC.INI HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI</pre> <p>Create some entries in both User DSN and System DSN tabs from Data Sources (ODBC) control panel applet and check how these values are stored in the registry.</p> <p>The following example enumerate the DSN defined for the user trough Control Panel > Administrative Tools > Data Sources (ODBC) [User Dsn Tab].</p> <p><a href="http://support.microsoft.com/kb/178755" rel="noreferrer">http://support.microsoft.com/kb/178755</a></p> <pre><code> Option Explicit Private Declare Function RegOpenKeyEx Lib "advapi32.dll" _ Alias "RegOpenKeyExA" _ (ByVal hKey As Long, _ ByVal lpSubKey As String, _ ByVal ulOptions As Long, _ ByVal samDesired As Long, phkResult As Long) As Long Private Declare Function RegEnumValue Lib "advapi32.dll" _ Alias "RegEnumValueA" _ (ByVal hKey As Long, _ ByVal dwIndex As Long, _ ByVal lpValueName As String, _ lpcbValueName As Long, _ ByVal lpReserved As Long, _ lpType As Long, _ lpData As Any, _ lpcbData As Long) As Long Private Declare Function RegCloseKey Lib "advapi32.dll" _ (ByVal hKey As Long) As Long Const HKEY_CLASSES_ROOT = &amp;H80000000 Const HKEY_CURRENT_USER = &amp;H80000001 Const HKEY_LOCAL_MACHINE = &amp;H80000002 Const HKEY_USERS = &amp;H80000003 Const ERROR_SUCCESS = 0&amp; Const SYNCHRONIZE = &amp;H100000 Const STANDARD_RIGHTS_READ = &amp;H20000 Const STANDARD_RIGHTS_WRITE = &amp;H20000 Const STANDARD_RIGHTS_EXECUTE = &amp;H20000 Const STANDARD_RIGHTS_REQUIRED = &amp;HF0000 Const STANDARD_RIGHTS_ALL = &amp;H1F0000 Const KEY_QUERY_VALUE = &amp;H1 Const KEY_SET_VALUE = &amp;H2 Const KEY_CREATE_SUB_KEY = &amp;H4 Const KEY_ENUMERATE_SUB_KEYS = &amp;H8 Const KEY_NOTIFY = &amp;H10 Const KEY_CREATE_LINK = &amp;H20 Const KEY_READ = ((STANDARD_RIGHTS_READ Or _ KEY_QUERY_VALUE Or _ KEY_ENUMERATE_SUB_KEYS Or _ KEY_NOTIFY) And _ (Not SYNCHRONIZE)) Const REG_DWORD = 4 Const REG_BINARY = 3 Const REG_SZ = 1 Private Sub Command1_Click() Dim lngKeyHandle As Long Dim lngResult As Long Dim lngCurIdx As Long Dim strValue As String Dim lngValueLen As Long Dim lngData As Long Dim lngDataLen As Long Dim strResult As String lngResult = RegOpenKeyEx(HKEY_CURRENT_USER, _ "SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources", _ 0&amp;, _ KEY_READ, _ lngKeyHandle) If lngResult &lt;&gt; ERROR_SUCCESS Then MsgBox "Cannot open key" Exit Sub End If lngCurIdx = 0 Do lngValueLen = 2000 strValue = String(lngValueLen, 0) lngDataLen = 2000 lngResult = RegEnumValue(lngKeyHandle, _ lngCurIdx, _ ByVal strValue, _ lngValueLen, _ 0&amp;, _ REG_DWORD, _ ByVal lngData, _ lngDataLen) lngCurIdx = lngCurIdx + 1 If lngResult = ERROR_SUCCESS Then strResult = strResult &amp; lngCurIdx &amp; ": " &amp; Left(strValue, lngValueLen) &amp; vbCrLf End If Loop While lngResult = ERROR_SUCCESS Call RegCloseKey(lngKeyHandle) Call MsgBox(strResult, vbInformation) End Sub </code></pre>
<p>You can use the <b>SQLDataSources</b> function of the ODBC API. See <a href="http://msdn.microsoft.com/en-us/library/ms711004.aspx" rel="nofollow noreferrer">MSDN documentation</a>.</p>
19,938
<p>Since you guys are having lots of questions or not enough info to work with, below is proprietary information and as such be careful as you can. The question – (please refer to if [$7 -eq "AAA"]...then statement - in bold ) has a problem with an output, where I can only output/print count of 'AAA' regardless the variable coming in either 'BBB' or ‘AAA’. As a result, and as an error, the program outputs/prints count of ‘AAA’. </p> <p>Again, in this situation I tried with my best knowledge to explain to those available and savvy. Thanks.</p> <pre><code>----------------------------------------------------------------------- # Print the run date echo "**********************" echo " TALK Program " echo " Run Date " date echo "**********************" # DIRECTORIES/VARIABLES/PARAMETERS p1=$1 p2=$2 p3=$3 p4=$4 p5=$5 p6=$6 p7=$7 p8=$8 echo "***********************************************" echo "The parameteres are" echo " " echo " Param 1 (Username/Password) = " echo " Param 2 (User account number) = "$2 echo " Param 3 (Requestor name) = "$3 echo " Param 4 (Requestor ID) = "$4 echo " Param 7 (AAA or BBB) = "$7 echo " Param 8 (TALK Data Filename) = "$8 echo "***********************************************" AREA1=$WILLS_TOP/bin # Switch-variable points to GENEX bin dir AREA2=$WILLS_TOP/sql # Switch-variable points to GENEX sql dir SQL_CTL=$AREA1/WILLSTALK.ctl # Name of SQL*Load ctrl file SQL_VALID=$AREA2/WILLSTALK.sql # Name of validation PL/SQL script FTP_BIN=/usr/local/bin # Where ftp program is UNIX_GET=$FTP_BIN/ftpmget.sh # Name of UNIX file get program UNIX_PUT=$FTP_BIN/ftpmput.sh # Name of UNIX file put program UNIX_DEL=$FTP_BIN/ftpdel.sh # Name of UNIX file delete program TEMP=/tmp # Name of temp dir INPUT_DIR=/oracle/inbound # For DVLP Where input file is comming from ARCHIVE_NT_DIR=/oracle/inbound/RFS_DVLP # For DVLP Modified on 2005 OUTPUT_DIR=/oracle/outbound/ # Where output file is going to OUTPUT_UNIX_DIR=$OUTCSF/$$OUTLOG/ # Directory of where output is DES_NAME=${OUTPUT_UNIX_DIR}${OUT_FILE} # Where output is going to be USERACCNUM=$p2 # User Account Number USERNAME=$p5 # Username PASSWORD=$p6 # Password AAA_OR_BBB=$p7 # Either 'AAA' or default of 'BBB' DATAFILE_NAME=$p8 # Datafile name (NT) SERVER='172.........' # Server (NT) LOG_DIR=$WILLS_TIP/log # Path of log dir LOCAL_DIR=$WILLS_TIP/data # Directory where file is at (UNIX) ARCHIVE_DIR=$WILLS_TIP/archive # Directory for archive (UNIX) FILE_NAME="" # File name (UNIX) FILE_TRAN_TYPE='ascii' # File transfer type #***************************************************************************** # MAIN PROCEDURE #***************************************************************************** if [ ! "$p7" ] then echo "At least one MS Excel Update Data File must be entered !" echo "No files were entered." exit 1 fi #---------------------------------------------------------------------- # Remove all MS Excel datafile in $GENEX_TOP/data directory if exist #---------------------------------------------------------------------- rm -f $WILLS_TIP/data/TALK* #-------- # FTP #-------- ${UNIX_GET} $p5 $p6 $SERVER $INPUT_DIR $DATAFILE_NAME $LOCAL_DIR "" $TEMP $FILE_TRAN_TYPE if [ $? != 0 ] then echo "The MS Excel Datafile(s) ftp has failed." exit 1 fi if [ ! -s $LOCAL_DIR/$p8 ] then echo "FTP command executed, but MS Excel file(s) did not get copied." exit 2 fi #----------------------------------------- # SQL*Loads - New MS Excel file to load #----------------------------------------- for i in $LOCAL_DIR/$DATAFILE_NAME do SQLOAD_DAT_FILE=`echo $i | sed "s/\// /g" | awk ' { print $NF } '` SQLOAD_LOG_FILE=$SQLOAD_DAT_FILE.log # Sqlload log file name SQLOAD_BAD_FILE=$SQLOAD_DAT_FILE.bad # Sqlload bad file name if [ -s $LOG_DIR/$SQLOAD_BAD_FILE ] then rm -f $LOG_DIR/$SQLOAD_BAD_FILE # Remove prev. bad file, if such exists echo "Previous bad file has been successfully removed." else echo "No bad file was identified and removed." echo "Resume Normal Processing." fi echo $i echo "Now loading datafile: $LOCAL_DIR/$SQLOAD_DAT_FILE" #--------------------------------------------------------------- sed "s/@USERACCNUM/$USERACCNUM/" $SQL_CTL &gt; $TEMP/WILLSTAL.ctl # Changing '@USERACCNUM' #--------------------------------------------------------------- sqlldr userid=${p1} control=$TEMP/WILLSTALK.ctl \ log=$LOG_DIR/$SQLOAD_LOG_FILE \ bad=$LOG_DIR/$SQLOAD_BAD_FILE \ data=$LOCAL_DIR/$SQLOAD_DAT_FILE if test ! -s $LOG_DIR/$SQLOAD_BAD_FILE then tail -20 $LOG_DIR/$SQLOAD_LOG_FILE echo "*** Done SQL*Loader Script ***" else echo "The SQL*Load for MS Excel Update file has FAILED due to BAD DATA." echo "*** Exitting Script On Failure ***" echo "*** Process is ready for NEXT LOAD! ***" exit 1 fi done #---------------------------------------- # To run a PL/SQL script #---------------------------------------- sqlplus -s $p1 @$SQL_VALID $AAA_OR_BBB if [ $? -ne 0 ] then echo "The PL/SQL script for validation has FAILED." exit 1 fi #---------------------------------------------------------- # Now run SQL*Plus script Flat File Report After Updating #---------------------------------------------------------- sqlplus -s $1 &lt;&lt;EOF set echo off set heading off set space 0 set newpage 0 set pagesize 0 set feed off set term on SPOOL $OUTCSF/$OUTLOG/l$4.log SELECT 'spool $OUTCSF/$APPLOUT/o$4.out' FROM dual; SPOOL OFF @$OUTCSF/$OUTLOG/l$4.log Select 'Run Date: '||to_char(sysdate, 'DD-MON-YYYY') From dual; Select '*************************************************************' From dual; SELECT 'ERRORS Found: '||count(*) FROM gnx_rel_date_temp WHERE error_text IS NOT NULL; Select '--------------- ----------- ---------------------------------' From dual; Select 'TRX NUMBER NEW DATE ERROR TEXT' From dual; Select '--------------- ----------- ---------------------------------' From dual; SELECT trx_num||'|'||new_date||'|'||error_text FROM will_rel_date_temp WHERE error_text IS NOT NULL; Select '*************************************************************' From dual; #------------- #---- AAA ---- #------------- if [ $7 -eq "AAA" ] then SELECT 'Total AAA Updated: '||count(*)||' records' FROM reldatetemp ,allcustomers WHERE trx_num = trx_no AND error_text IS NULL AND attr2 IS NOT NULL AND attr2 = TO_CHAR(new_date,'YYYY/MM/DD HH24:MI:SS'); else exit 0 fi #--------------- #---- BBB ---- #--------------- if [ $7 -eq "BBB" ] then SELECT 'Total BBB Updated: '||count(*)||' records' FROM reldatetemp ,allcustomers WHERE trx_num = trx_no AND error_text IS NULL AND attr1 IS NOT NULL AND attr1 = TO_CHAR(new_date,'YYYY/MM/DD HH24:MI:SS'); else exit 0 fi SPOOL OFF EOF #---------------------------------------------- # To delete the data files on NT #---------------------------------------------- ${UNIX_DEL} $p5 $p6 $SERVER $INPUT_DIR $DATAFILE_NAME $TEMP mv $WILLS_TIP/data/$DATAFILE_NAME $WILLS_TIP/archive/. # All Done! echo "*** End of program *** " </code></pre>
<p>Anything between "sqlplus -s $1 &lt;&lt; EOF" and "EOF" is called "here-doc" and intended for consumption by sqlplus. You can't really expect sqlplus to understand shell scripting in the form of "if [ "$7" -eq ....] ".</p> <p>You should make all "ifs" outside of the here-doc and use results in it. Like this:</p> <pre><code>if [ "$7" -eq "AAA" ] ; then attr="attr2" elsif [ "$7" -eq "BBB" ] ; then attr="attr1" else echo "Bogus $7 - need AAA or BBB" fi .... sqlplus -s $1 &lt;&lt;EOF ... SELECT 'Total $7 Updated: '||count(*)||' records' FROM reldatetemp ,allcustomers WHERE trx_num = trx_no AND error_text IS NULL AND ${attr} IS NOT NULL AND ${attr} = TO_CHAR(new_date,'YYYY/MM/DD HH24:MI:SS'); ... EOF </code></pre> <p>Pay attention to "${attr}" and read a decent tutorial on shell scripting.</p>
<p>How can the script possibly continue after this code:</p> <pre><code>#------------- #---- AAA ---- #------------- if [ $7 -eq "AAA" ] then SELECT 'Total AAA Updated: '||count(*)||' records' FROM reldatetemp ,allcustomers WHERE trx_num = trx_no AND error_text IS NULL AND attr2 IS NOT NULL AND attr2 = TO_CHAR(new_date,'YYYY/MM/DD HH24:MI:SS'); else exit 0 fi </code></pre> <p>If $7 = "AAA" then run the select, if $7 is not = "AAA" exit the script.....</p> <p>Regards<br> K</p>
37,958
<p>I have a simple C++ DLL that implements a few custom actions for a WiX installer.</p> <p>Debugging the custom actions is usually simple: put up a temporary dialog box at the beginning of the action, and attach to the process when the dialog box appears.</p> <p>But today, whenever I attach to the process, I get the "Microsoft Visual Studio is Busy" bubble appearing at the bottom of the screen. I cannot figure out where this is coming from. Any ideas?</p>
<p>After hours of trying to figure this out, I realized that the problem was that I had debugging symbols enabled in Tools->Options->Debugging->Symbols. The latency in looking up symbols was leading to the apparent lockup.</p> <p>Clearing the "Search the above locations only when symbols are loaded manually" seems to have alleviated the problem.</p>
<p>Are you referring debug symbols from a network location that is not available (e.g. a ClearCase dynamic view or something similar). This can cause Visual Studio to hang when you attach to a process.</p> <p>Check Tools->Options->Debugging->Symbols and try temporarily disabling the symbol file (.pdb) locations until you figure out which is slowing it down (or causing it to hang). Through elimination you should be able to figure this out.</p>
19,456
<p>I am trying to help someone write a program that I thought would be easy, but of course it never is :)</p> <p>I am trying to take a class roster (usually between 10-20 students) and effectivly uniquely pair off each classmate to another to make unique groups. Therefore in a class of 10 people, you can have 9 groups.</p> <p>It needs to be able to handle odd number of students too, adding to my confusion.</p> <p>I was looking at doing this in Java, but that is flexible. Any ideas on an algorithmic way to guarantee a)not infinite looping (ending with 2 people who have already been partners) and b) I am aiming for more efficent time than space, since class size will be small!</p> <p>Thanks!</p>
<p>You want to create a complete graph with each student as a node, then randomly select edges and insert them into a unique set.</p> <p>On the next "pull", you want to do the same thing, except now if the edge has already been selected, discard and reselect.</p>
<p>I don't know if it's exactly what you asked for, but here my take on it in simple python. It spits out each unique grouping you can have for (in my example) 10 students.</p> <p>It is not the fastest thing there is i guess, but its very easy to implement and to follow.</p> <pre class="lang-py prettyprint-override"><code>from itertools import permutations def my_sort(x): assert type(x) in (tuple, list) assert len(x)==10 groups = x[0:2],x[2:4],x[4:6],x[6:8],x[8:10] groups = sorted([sorted(g) for g in groups], key=lambda k:k[0]) return tuple(x for g in groups for x in g ) S = set(my_sort(p) for p in permutations(list(range(10)))) """ len(S) == 945 list(sorted(S))[-3:] == [(0, 9, 1, 8, 2, 7, 3, 4, 5, 6), (0, 9, 1, 8, 2, 7, 3, 5, 4, 6), (0, 9, 1, 8, 2, 7, 3, 6, 4, 5)] """ </code></pre> <p>a tuple represents all groups in a row: (0, 9, 1, 8, 2, 7, 3, 4, 5, 6) means 0 is grouped with 9, 1 is grouped with 8 and so on.</p>
24,347
<p>I'm working on a big .NET 1.1 project, and there exists a wish to upgrade this, majorily to be able to use better tools like Visual Studio 2008, but also because of the new features and smaller amount of bugs in the .NET 2.0 framework.</p> <p>The project consist for the bigger part of VB.NET, but there are also parts in C#. It is a Windows Forms application, using various third party controls. Using .NET remoting the rich client talks to a server process which interfaces with a MSSQL 2000 database.</p> <p>What kind of issues can we expect in case we decide to perform the upgrade?</p>
<p>We're looking at doing the same migration right now Tobi. First, you can get a good idea of what to expect by making a copy of your project (or a portion of it) and give it a "dry run" through the .NET 2.0 compiler. My experience with this was that the 2.0 compiler gives more warnings about bad programming practices that the 1.1 compiler let slide. The compiler will warn you about implicit casts, "ambiguous" return paths (a code path where a function doesn't return a value), and some other minor things.</p> <p>Here's a few links that you might find helpful: <a href="http://msdn.microsoft.com/en-us/library/ms994381.aspx" rel="noreferrer">.NET Framework Compatability</a></p> <p><a href="http://go.microsoft.com/fwlink/?linkid=51223" rel="noreferrer">Word Document of Breaking changes in .NET Framework 2.0</a></p>
<p>You probably won't have any <strong>breaking</strong> issues, though you may get some deprecated method warnings. The compiler should generally tell you what the replacement is though. I know that some of the System.Configuration things were updated.</p>
8,167
<p>I need to cut out and save/use part of a string in C#. I figure the best way to do this is by using Regex. My string looks like this:</p> <p><code>"changed from 1 to 10"</code>. </p> <p>I need a way to cut out the two numbers and use them elsewhere. What's a good way to do this?</p>
<p>Error checking left as an exercise...</p> <pre><code> Regex regex = new Regex( @"\d+" ); MatchCollection matches = regex.Matches( "changed from 1 to 10" ); int num1 = int.Parse( matches[0].Value ); int num2 = int.Parse( matches[1].Value ); </code></pre>
<p>Here is a code snippet that does <em>almost</em> what I wanted:</p> <pre><code>using System.Text.RegularExpressions; string text = "changed from 1 to 10"; string pattern = @"\b(?&lt;digit&gt;\d+)\b"; Regex r = new Regex(pattern); MatchCollection mc = r.Matches(text); foreach (Match m in mc) { CaptureCollection cc = m.Groups["digit"].Captures; foreach (Capture c in cc){ Console.WriteLine((Convert.ToInt32(c.Value))); } } </code></pre>
36,498
<p>I just have started to learn Haskell and combine reading books and tutorials with solving problems from Project Euler. I have stuck on <a href="http://projecteuler.net/index.php?section=problems&amp;id=27" rel="nofollow noreferrer">Problem 27</a> because I get "C stack overflow" error using this code: </p> <p><strong>euler.hs</strong></p> <pre><code>divisors n = [x | x &lt;- [1..n `div` 2], n `mod` x == 0] ++ [n] is_prime n = divisors n == [1, n] f a b = [n^2 + a * n + b | n &lt;- [0..]] primes_from_zero a b = length(takeWhile is_prime (f a b)) </code></pre> <p><strong>command window</strong></p> <p>this command gives Euler's coefficients 1 and 41 (40 primes in row)</p> <pre><code>foldr (max) (0, 0, 0) [(primes_from_zero a b, a, b) | a &lt;- [0..10], b &lt;- [0..50]] </code></pre> <p>this one fails with "C stack overflow" (I wanted to obtain coefficients -79 and 1601 also mentioned in the problem definition):</p> <pre><code>foldr (max) (0, 0, 0) [(primes_from_zero a b, a, b) | a &lt;- [-100..0], b &lt;- [1500..1700]] </code></pre> <p>Would you tell me, please, why does the error arise and how to resolve it? Thank you!</p> <p>I use WinHugs.</p>
<p>A "stack overflow" error means that the chain of function calls in your program (from the entry function down to the currently executing function) has grown too large. Most compilers and runtimes implement the call chain as a stack data structure&mdash;each element is a "stack frame" containing the local variables and context of a single function call&mdash;with a limited size.</p> <p>Usually, a stack overflow means there's something wrong with a recursive function. For example, if a recursion never terminates, it will eventually hit the stack limit and "overflow." Even if a recursion is terminating, it may overflow if there are simply too many calls. This is often the case with very large lists, and seems to be the case with your example.</p> <p>One way to avoid stack overflows in Haskell (and many other languages) is to write <a href="http://en.wikipedia.org/wiki/Tail_recursion" rel="nofollow noreferrer">tail-recursive functions</a>. A tail-recursive function is one where the only recursive call is the result of the function. For example,</p> <pre><code>foldl f x (y:ys) = foldl f (f x y) ys </code></pre> <p>In contrast, <code>foldr</code> is not tail recursive </p> <pre><code>foldr f x (y:ys) = f y (foldr f x ys) </code></pre> <p>For technical reasons, a tail recursive call can re-use the stack frame of its caller, and thus does not cause the call stack to grow.</p> <p>(A side note: <code>foldr</code> is not tail recursive but is "lazier" than <code>foldl</code>, because it may not need to evaluate the whole list. This may guide your decision on which to use.)</p> <p>Even with a tail-recursive function, you may run out of memory due to a <a href="http://www.haskell.org/haskellwiki/Performance/Space" rel="nofollow noreferrer">"space leak"</a>. For example, in <code>foldl</code> each recursive call will build a new suspension for <code>(f x y)</code>. <code>foldl</code> uses constant stack space, but O(n) space for unevaluated calls to <code>f</code>. To avoid this in cases where strictness is desirable, you can use <code>foldl'</code></p> <pre><code>foldl' f x (y:ys) = (foldl' f $! f x y) ys </code></pre> <p>where the infix operator <code>$!</code> forces strict evaluation.</p>
<p>I don't know why <a href="https://stackoverflow.com/users/34509/litb">litb</a> put his answer into a comment instead of an answer, so I'm copying it here so that people will see it:</p> <p><a href="http://www.haskell.org/haskellwiki/Stack_overflow" rel="nofollow noreferrer">http://www.haskell.org/haskellwiki/Stack_overflow</a></p> <p>I think it's the right answer. But the short version is that foldr is not tail recursive.</p> <p>I've marked this post as Community Wiki, so I won't get any reputation from it.</p>
48,426
<p>Got my Ender 3 v2 and stack with the bed leveling.</p> <p>Used default settings, Creality slicer 4.2, test PLA from the kit and print model <a href="https://www.thingiverse.com/thing:3013319" rel="nofollow noreferrer">https://www.thingiverse.com/thing:3013319</a> (4 squares in each corner and 1 in the middle), nozzle 200 °C, bed 60 °C.</p> <p>After some adjustments, I have good solid pieces on the bed corners but the center one has small gaps. Is it possible to fix this problem?</p> <p>Corner pice: <a href="https://i.stack.imgur.com/BGeA2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BGeA2.jpg" alt="enter image description here" /></a></p> <p>Center piece: <a href="https://i.stack.imgur.com/gfSas.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gfSas.jpg" alt="enter image description here" /></a></p>
<p>The gaps are, because the nozzle is to far from the bed at this point. It may sound like a big deal, but actually this is not leveling alone, but it looks like the bed is not a perfect plane/perfectly flat. This is normal, my ikea mirror and my stock bed show the same thing. Now here's one solution:</p> <p>Print calibration stickers, like you already did on various places around the bed to get a feel, where it is too low. Let it cool and put painters tape (the very very thin tape, that should not burn) on areas, where the bed is too low. Print more calibration rectangles and check if you have enough. Repeat until you cannot see a difference.</p> <p>It took me about 2h to level everything absolutely perfectly. This was 2 years ago and I didn't have to touch the tape below my bed ever since. It just works.</p> <p>Alternative solutions involve mesh bed leveling and buying a new bed surface or even the surface below the bed. However, I found that to neither of them work reliably, whereas the simple tuning does what it's supposed to.</p>
<p>I had exact same issues with my Ender 3 v2. Using the stock default glass the middle would be too far out and I was never able to level it just right - no matter what I did - I could have stayed on it for hours.</p> <p>In matter of fact, it wasn't just the middle, it was the middle between each of the corner points as well, meaning, imagine a plus sign going across from the dead middle of the bed vertically and horizontally, where all that area would be a little too far out.</p> <p>I did anything I could, eventually what solved it for me was tightening all of the frame once again, making sure the x-axis gantry doesn't wobble, the hotend doesn't wobble and then realign the gantry nuts below the bed, to help with this alignment I actually tilted the whole printer 90° so gravity will help the wheels get the right alignment.</p> <p>The issues such as you are describing were gone after complete overhaul tightening as mentioned above.</p>
1,709
<p>I use <code>PHPMyAdmi</code>n for convenience in updating a remote database.</p> <p>But it doesn't show warnings, by default, which recently got me into some embarrassing trouble where I was updating a SET field with string not on its list and not noticing the problem. </p> <p>I'm using <code>2.11.9.1 (Dreamhost's default install)</code>.</p> <p>On the <code>PHPMyAdmin</code> wiki it lists "Display warnings" as a feature of <a href="http://wiki.cihar.com/pma/phpMyAdmin_2.9.0-rc1" rel="nofollow noreferrer">version 2.9.0</a> and even "Display all warnings" as a feature of 2.10.2 -- but how do I actually turn this on? The documentation isn't great.</p>
<p>I don't believe Dreamhost gives you access to the configuration file for their installation of phpMyAdmin. However, you can easily make your own installation of phpMyAdmin by downloading the source from <a href="http://www.phpmyadmin.net/home_page/index.php" rel="nofollow noreferrer">their website</a> and just untarring it to the directory you want to access it at (your-domain.com/phpma for example). Then, follow the <a href="http://www.phpmyadmin.net/documentation/#quick_install" rel="nofollow noreferrer">website's instructions for editing your config file</a> (which should include enabling warnings like you've asked).</p>
<p>I could be mistaken but if I remember correctly you need to have access to the phpMyAdmin config file to enable it.</p>
13,228
<p>Do objects added to the SqlException.Data collection need to be [Serializable]?</p>
<p>Yes, they need to be. It's because ISerializable's implementation in Exception type add Data property into StreamingContext. And all objects in Data property (which is a IDictionary) must be serializable. Having exception classes and instances serializable is good practice even if aren't going to build distributed app.</p>
<p>Well, strictly speaking, no... you can add any type to an Exception's Data dictionary... but why would you ask? What boundary do you think they are going to be serialized across?</p>
19,322
<p>Does anybody know if there is a way to make autocompletion work in MySQL Command Line Client under Windows? It's working nicely under Linux for me, but simply moves the cursor under Windows instead.</p>
<p>It ought to work this way:</p> <pre><code>C:\&gt; mysql --auto-rehash </code></pre> <p>Or configure your my.cnf:</p> <pre><code>[mysql] auto-rehash </code></pre> <p><strong>edit:</strong> My apologies. I have found some references that the tab-completion feature in mysql client works only on UNIX/Linux. It does not work on Windows.</p> <p><strong>update:</strong> The reason for this is mentioned briefly in MySQL <a href="http://bugs.mysql.com/bug.php?id=4731" rel="noreferrer">bug #4731</a>:</p> <blockquote> <p>[31 Jul 2004 12:47] Sergei Golubchik </p> <p>I just downloaded 4.0.15 - command completion in mysql.exe is NOT working, as expected. It was never working in mysql.exe because we were not able to make readline to compile with VC++. </p> <p>mysqlc.exe is a cygwin build, and it is linked with readline.</p> </blockquote> <p>Explanation: <a href="http://en.wikipedia.org/wiki/GNU_readline" rel="noreferrer">GNU readline</a> is a standard open-source library for handling user input. The MySQL team uses the readline library, but they are not its author. From the above comment, I understand that they were unsuccessful in compiling the readline library on Windows with Microsoft Visual C++, the tool they use to build the MySQL product. Some open-source projects have not been made fully compatible with the Microsoft Windows environment.</p> <p>At one time in the past, the MySQL product provided an alternative client they called <code>mysqlc.exe</code>, which they compiled with the <a href="http://www.cygwin.com/" rel="noreferrer">cygwin</a> toolset on Windows, but they don't provide this anymore. The cygwin toolset includes the readline library, so it was possible to compile the <code>mysqlc.exe</code> client with support for tab-completion.</p> <p>So in theory, if you are really intrepid, you could download the cygwin toolset including the readline library, then download the MySQL source code and build it using cygwin. Then you should have a mysql client program that can perform tab-completion. But this sounds like a lot of work even for someone who is familiar with building MySQL from source.</p>
<p>This is probably not what you are looking for, but the enterprise version of SQLYog offers a somewhat limited schema auto-completion.</p>
33,877
<p>I have an application that works pretty well in Ubuntu, Windows and the Xandros that come with the Asus EeePC.</p> <p>Now we are moving to the <a href="http://en.wikipedia.org/wiki/Aspire_One" rel="nofollow noreferrer">Acer Aspire One</a> but I'm having a lot of trouble making php-gtk to compile under the Fedora-like (Linpus Linux Lite) Linux that come with it.</p>
<p>Hi Guys well I finally got this thing to work the basic workflow was this:</p> <pre><code>#!/bin/bash sudo yum install yum-utils #We don't want to update the main gtk2 by mistake so we download them #manually and install with no-deps[1](and forced because gtk version #version of AA1 and the gtk2-devel aren't compatible). sudo yumdownloader --disablerepo=updates gtk2-devel glib2-devel sudo rpm --force --nodeps -i gtk2*rpm glib2*rpm #We install the rest of the libraries needed. sudo yum --disablerepo=updates install atk-devel pango-devel libglade2-devel sudo yum install php-cli php-devel make gcc #We Download and compile php-gtk wget http://gtk.php.net/do_download.php?download_file=php-gtk-2.0.1.tar.gz tar -xvzf php-gtk-2.0.1.tar.gz cd php-gtk-2.0.1 ./buildconf ./configure make sudo make install </code></pre> <p>If you want to add more libraries like gtk-extra please type <code>./configure -help</code> before making it to see the different options available.</p> <p>After installing you'll need to add <code>php_gtk2.so</code> to the <em>Dynamic Extensions</em> of <code>/etc/php.ini</code></p> <pre><code>extension=php_gtk2.so </code></pre> <p>Sources:</p> <p>[1]: <a href="http://macles.blogspot.com/2008/08/dependency-problems-on-acer-aspire-one.html" rel="nofollow noreferrer">Dependency problems on Acer Aspire One Linux</a></p>
<p>If you could give us more to go on than just trouble making it compile; we might be better able to help you with your issues.</p>
10,383
<p>Using Oracle, if a column value can be 'YES' or 'NO' is it possible to constrain a table so that only one row can have a 'YES' value?</p> <p>I would rather redesign the table structure but this is not possible.</p> <p>[UDPATE] Sadly, null values are not allowed in this table.</p>
<p>Use a function-based index:</p> <pre><code>create unique index only_one_yes on mytable (case when col='YES' then 'YES' end); </code></pre> <p>Oracle only indexes keys that are not completely null, and the CASE expression here ensures that all the 'NO' values are changed to nulls and so not indexed.</p>
<p>I guess I'd use a second table to point to the appropriate row in your current table. That other table could be used to store values of other variables too too.</p>
22,024
<p>I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution. </p> <pre><code>def run(): owd = os.getcwd() #first change dir to build_dir path os.chdir(testDir) #run jar from test directory os.system(cmd) #change dir back to original working directory (owd) </code></pre> <p>note: I think my code formatting is off - not sure why. My apologies in advance</p>
<p>You simply need to add the line:</p> <pre><code>os.chdir(owd) </code></pre> <p>Just a note this was also answered in your other <A href="http://stackoverflow.com/questions/299249/how-can-i-get-my-python-version-25-script-to-run-a-jar-file-inside-a-folder-ins">question</A>.</p>
<p>I looked around the answers on StackOverflow and eventually decided to write my own decorator for this purpose:</p> <pre><code>from collections.abc import Callable from functools import wraps from typing import ParamSpec, TypeVar T = TypeVar('T') P = ParamSpec('P') def enter_subdir(subdir: str) -&gt; Callable[[Callable[P, T]], Callable[P, T]]: &quot;&quot;&quot;During the execution of a function, temporarily enter a subdirectory.&quot;&quot;&quot; def decorator(function: Callable[P, T]) -&gt; Callable[P, T]: @wraps(function) def wrapper(*args, **kwargs) -&gt; T: os.makedirs(subdir, exist_ok=True) os.chdir(subdir) result = function(*args, **kwargs) os.chdir(&quot;..&quot;) return result return wrapper return decorator </code></pre>
38,362
<p>Windows, Firefox or Google Chrome all monitor usage statistics and analyze the crash reports are sent to them. I am thinking of implementing the same feature into my application. </p> <p>Of course it's easy to litter an application with a lot of logging statement, but this is the approach that I want to avoid because I don't want my code to have too many cross cutting concern in a function. I am thinking about using AOP to do it, but before that I want to know how other people implement this feature first.</p> <p>Anyone has any suggestion?</p> <p>Clarification: I am working on desktop application, and doesn't involve any RDBMS</p>
<p>In "Debugging .Net 2.0 Applications" John Robbins (of Wintellect) writes extensively about how to generate and debug crash reports (acutally windbg/SOS mini dumps). His Superassert class contains code to generate these. Be warned though - there is a lot of effort required to set this up properly: symbol servers, source servers as well as a good knowledge of VS2005 and windbg. His book, however, guides you through the process.</p> <p>Regarding usage statistics, I have often tied this into authorisation, i.e. has a user the right to carry out a particular task. Overly simply put this could be a method like this (ApplicationActions is an enum):</p> <pre><code>public static bool HasPermission( ApplicationActions action ) { // Validate user has permission. // Log request and result. } </code></pre> <p>This method could be added to a singleton SercurityService class. As I said this is overly simple but should indicate the sort of service I have in mind.</p>
<p>I would take a quick look at the Logging Application Block that is part of the Enterprise Library. It provided a large number of the things you require, and is well maintained. Check out some of the scenarios and samples available, I think you will find them to your liking.</p> <p><a href="http://msdn.microsoft.com/en-us/library/cc309506.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cc309506.aspx</a></p>
48,876
<p>There are all sorts of stories of what to put on your printer bed to make your part not come loose when it is printing but can be removed after it is done without requiring a hammer and chisel.</p> <p>Is there anything out there that shows an analytical comparison?</p> <p>My biggest interest is PLA on a heated glass base. </p>
<p>I use a product called <a href="http://www.3dlac.com/index.php/en/" rel="nofollow noreferrer">3DLAC</a> but I suppose it's regular hairspray. Makes my PLA stick to the heated bed like a charm. After cooling down the print can be removed from the bed with ease.</p> <p>Only today, after a few thousand prints the glass bed of my printer broke. But I suppose this is because we didn't have enough patience to let the bed cool down to room temperature before removing the printed piece.</p>
<p>I use a product called <a href="http://www.3dlac.com/index.php/en/" rel="nofollow noreferrer">3DLAC</a> but I suppose it's regular hairspray. Makes my PLA stick to the heated bed like a charm. After cooling down the print can be removed from the bed with ease.</p> <p>Only today, after a few thousand prints the glass bed of my printer broke. But I suppose this is because we didn't have enough patience to let the bed cool down to room temperature before removing the printed piece.</p>
597
<p>I have a web application where there are number of Ajax components which refresh themselves every so often inside a page (it's a dashboard of sorts).</p> <p>Now, I want to add functionality to the page so that when there is no Internet connectivity, the current content of the page doesn't change and a message appears on the page saying that the page is offline (currently, as these various gadgets on the page try to refresh themselves and find that there is no connectivity, their old data vanishes).</p> <p>So, what is the best way to go about this?</p>
<pre><code>navigator.onLine </code></pre> <p>That should do what you're asking.</p> <p>You probably want to check that in whatever code you have that updates the page. Eg:</p> <pre><code>if (navigator.onLine) { updatePage(); } else { displayOfflineWarning(); } </code></pre>
<p>One possible solution is that if the page and the cached page have a different url to just look and see what url you are on. If you are on the url of the cached page then you are in offline mode. <a href="http://remysharp.com/2011/04/19/broken-offline-support/" rel="nofollow">This</a> blog makes a good point about why navigator.online is broke</p>
12,036
<p>We currently have an appserver setup where EVERYTHING is off of one big context root, and we copy class files and restart app servers to deploy. Not ideal. I'm trying to set up an ant script to do the build and deploy using wdeploy, and everything works, except I need my servlet to forward to jsps outside of the context root of my war file deploy. So I figure if I can put a symlink in my war file, it can point to somewhere outside of my context root space.</p> <p>This is the goal I'm trying to achieve, perhaps the symlink isn't the best idea. I just need a way to forward outside of my context root from a servlet.</p>
<p>There are a number of them depending on the type you are casting to</p> <pre><code>cint() Cast to integer cstr() cast to string clng() cast to long cdbl() cast to double cdate() cast to date </code></pre> <p>It also has implicit casting so you can do this myString=myInt</p>
<p>Ctype() I believe. The C* (CDate(), CStr(), etc) are holdovers for the most part. </p>
39,488
<p>Is there anything like Firebug that you can use within Google Chrome?</p> <p>Essential features I would like:</p> <ul> <li>Inspect HTML source (select elements, delete them, etc.)</li> <li>check CSS values (the built-in solution is weird, somehow)</li> </ul>
<p>There is a Firebug-like tool already built into Chrome. Just right click anywhere on a page and choose "Inspect element" from the menu. Chrome has a graphical tool for debugging (like in Firebug), so you can debug JavaScript. It also does CSS inspection well and can even change CSS rendering on the fly.</p> <p>For more information, see <a href="https://developers.google.com/chrome-developer-tools/" rel="noreferrer">https://developers.google.com/chrome-developer-tools/</a></p>
<p>If you are using Chromium on Ubuntu using the nightly ppa, then you should have the <code>chromium-browser-inspector</code></p>
39,678
<p>As of the fall of 2008 I'm about to embark on a new development cycle for a major product that has a winforms and an asp.net interface. We use Telerik, DevExpress and Infragistics components in it and all are going to have a release within a month or so which will be the one I target for our spring release of our product. </p> <p>They all support VS2005 and we will continue to target .net 2+ so I can't see any compelling reason so far to upgrade to VS2008.</p> <p>Has anyone found a compelling reason for upgrading to VS2008?</p>
<p>It's worth it. It's faster, the designer is vastly improved (split view, faster context switching), it has better support for javascript and when you're ready to target 3.5, you'll be ready to go.</p>
<p>It is worth the upgrade for me for the main reason that I can target different .NET versions (2, 3, 3.5) from the same IDE whereas in the past, one version of Visual Studio supported one version of .NET.</p> <p>The UI seems much more responsive now, but the core set of tools and processes hasn't changed that much.</p>
9,047
<p>I want to play around a bit with FLASH for app development. I'm looking for a good IDE for that. Someone suggested Flash Develop.</p>
<p><strong>Flash Builder</strong></p> <p><em>Pros</em></p> <ul> <li>better debugging and profiling </li> <li>visual designer for MXML</li> <li>because of Eclipse: support for other languages (eg. with Aptana, PDT...) and usage of plug-ins for the Eclipse Platform with features not shipped with FlexBuilder (code snippets with CFEclipse "Dynamic Snippets", "auto-code" for getter/setters with Monkey scripts...)</li> <li>support of virtual folders/files (links to external files/folders handled intern by Eclipse, so also working on Windows)</li> <li>refactoring (renaming of classes, functions, properties with automatic changing of dependencies)</li> </ul> <p><em>Cons</em></p> <ul> <li>Commercial license</li> <li>Big and because of Eclipse problematic with newer Eclipse versions for the FlexBuilder plug-in version (eg. not working with Eclipse Ganymede 3.4.1)</li> <li>adding and configuring the missing features with Eclipse plug-ins needs time and searching in the Internet (which plug-in? settings etc.)</li> <li>Code assist only average and sometimes buggy eg. if correct imports are missing ("java.lang.NullPointerException")</li> <li>missing of a code formatter or automatic get/setters (but there are solutions with other Eclipse plugins like Monkey Scripts, CFeclipse, Flexformatter "FlexPrettyPrintCommand"...)</li> <li>sometimes a bit sluggish if background tasks in Eclipse are working</li> <li>no package explorer</li> <li>AS2 and AS3 only - no Haxe</li> </ul> <p><strong>FlashDevelop</strong></p> <p><em>Pros</em></p> <ul> <li>free and Open Source (developed with C#)</li> <li>lightweight and snappy</li> <li>best available Code Assist for ActionScript</li> <li>supports all flash languages - AS2, AS3, haxe</li> <li>"auto code" for automatic getter/setter, variables, code for event handlers</li> <li>code snippets with integrated snippet editor </li> <li>extendible with plug-ins</li> <li>support for asdoc comments</li> <li>package explorer (show classes, symbols from a SWC file) </li> <li>basic refactoring</li> <li>multiple source code folders per project</li> <li><a href="http://www.flashdevelop.org/wikidocs/index.php?title=3rd_Party_Plugins_FD4" rel="noreferrer">useful plugins</a> : ANT integration, SWC creation, mini map, quick navigate</li> </ul> <p><em>Cons</em></p> <ul> <li>only for Windows</li> <li>no visual designer for MXML</li> <li>no support of virtual folders/files inside the project</li> <li>weak refactoring</li> <li>changing classpaths must be done manually</li> <li>plug-ins often not working in newer versions and many plug-ins are only rarely updated</li> <li>limited support for debugging Haxe applications</li> </ul> <p><strong>Common</strong></p> <p><em>Pros</em></p> <ul> <li>projects for full range of flash apps : websites, AIR (desktop, mobile)</li> <li>debugging of FP/AIR apps with breakpoints and stepping</li> <li>debugging with watch windows and locals</li> <li>support for ASDoc comments</li> <li>automatic adding of imports and organizing of imports </li> <li>class wizard</li> <li>SVG/GIT integration</li> </ul> <p>Cons</p> <ul> <li>no editing of graphics or animation (use Flash IDE for that)</li> </ul> <p><strong>Summary</strong></p> <p>For debugging, visual design of MXML forms : <strong>Flash Builder</strong></p> <p>For coding AS2/AS3/Haxe projects under Windows : <strong>FlashDevelop</strong></p>
<p>Along with what was already mentioned, Flex Builder has some nice tools that helps a developer to learn how to create a data enabled Flex application in form of the <strong>Data Wizards</strong> and also a nice <strong>web services introspection</strong> tool that automatically creates an ActionScript 3 client for a web service. </p>
40,314
<p>I'm using the urlrewriter.net as recommended in several questions in here. I'm having difficulties with displaying images and with the stylesheet.</p> <p>I read ScottGu's Blog (again as recommended in here) and in the end he does reffer to this problem and states to use ~/ for server controls etc. ("Handling CSS and Image Reference Correctly" at the end of the article).</p> <p>I tried his solution and it doesn't seem to work.</p> <p>The only thing that seems to work for me is to write the full path. For some reason, it doesn't seem to me as the right solution. It would make a serious problem developing and debugging.</p> <p>Does anyone know what can be the cause of the problem? Is there something I need to change in the web.config file?</p> <p>Thanks</p>
<p>In my experience <strong>the base tag is the source of far more problems than it solves</strong> </p> <p>I strongly suggest the first option, of limiting what the URLrewriter is allowed to effect by i.e. <strong>checking for .aspx</strong> extension before acting.</p>
<p>I think you need to exclude your stylesheets and image directories from the rewrite engine. I am not familiar with the engine you are using, but if you are using a rewrite rule that rewrites based on a very wide rule, it will incorrectly point to your stylesheets and images, and javascripts I believe.</p> <p>You could also experiment with the base tag.</p> <pre><code>&lt;base href="http://www.w3schools.com/images/" /&gt; </code></pre> <p>Try placing it in your <code>&lt;head&gt;</code>, pointing to your images folder.</p>
45,106
<p>I need to make an ArrayList of ArrayLists thread safe. I also cannot have the client making changes to the collection. Will the unmodifiable wrapper make it thread safe or do I need two wrappers on the collection?</p>
<p>It depends. The wrapper will only prevent changes to the collection it wraps, not to the objects in the collection. If you have an ArrayList of ArrayLists, the global List as well as each of its element Lists need to be wrapped separately, and you may also have to do something for the contents of those lists. Finally, you have to make sure that the original list objects are not changed, since the wrapper only prevents changes through the wrapper reference, not to the original object.</p> <p>You do NOT need the synchronized wrapper in this case.</p>
<p>This is neccessary if:</p> <ol> <li>There is still a reference to the original modifiable list.</li> <li>The list will possibly be accessed though an iterator.</li> </ol> <p>If you intend to read from the ArrayList by index only you could assume this is thread-safe.</p> <p>When in doubt, chose the synchronized wrapper.</p>
11,368
<p>If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?</p> <p>For example, if I inherit from the Exception class I want to do something like this:</p> <pre><code>class MyExceptionClass : Exception { public MyExceptionClass(string message, string extraInfo) { //This is where it's all falling apart base(message); } } </code></pre> <p>Basically what I want is to be able to pass the string message to the base Exception class.</p>
<p>Modify your constructor to the following so that it calls the base class constructor properly:</p> <pre><code>public class MyExceptionClass : Exception { public MyExceptionClass(string message, string extrainfo) : base(message) { //other stuff here } } </code></pre> <p>Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body.</p>
<p>Using newer C# features, namely <code>out var</code>, you can get rid of the static factory-method. I just found out (by accident) that out var parameter of methods called inse base-"call" flow to the constructor body.</p> <p>Example, using this base class you want to derive from:</p> <pre><code>public abstract class BaseClass { protected BaseClass(int a, int b, int c) { } } </code></pre> <p>The non-compiling pseudo code you want to execute:</p> <pre><code>public class DerivedClass : BaseClass { private readonly object fatData; public DerivedClass(int m) { var fd = new { A = 1 * m, B = 2 * m, C = 3 * m }; base(fd.A, fd.B, fd.C); // base-constructor call this.fatData = fd; } } </code></pre> <p>And the solution by using a static private helper method which produces all required base arguments (plus additional data if needed) and without using a static factory method, just plain constructor to the outside:</p> <pre><code>public class DerivedClass : BaseClass { private readonly object fatData; public DerivedClass(int m) : base(PrepareBaseParameters(m, out var b, out var c, out var fatData), b, c) { this.fatData = fatData; Console.WriteLine(new { b, c, fatData }.ToString()); } private static int PrepareBaseParameters(int m, out int b, out int c, out object fatData) { var fd = new { A = 1 * m, B = 2 * m, C = 3 * m }; (b, c, fatData) = (fd.B, fd.C, fd); // Tuples not required but nice to use return fd.A; } } </code></pre>
3,315
<p>this code always returns 0 in PHP 5.2.5 for microseconds:</p> <pre><code>&lt;?php $dt = new DateTime(); echo $dt-&gt;format("Y-m-d\TH:i:s.u") . "\n"; ?&gt; </code></pre> <p>Output:</p> <pre><code>[root@www1 ~]$ php date_test.php 2008-10-03T20:31:26.000000 [root@www1 ~]$ php date_test.php 2008-10-03T20:31:27.000000 [root@www1 ~]$ php date_test.php 2008-10-03T20:31:27.000000 [root@www1 ~]$ php date_test.php 2008-10-03T20:31:28.000000 </code></pre> <p>Any ideas?</p>
<p>This seems to work, although it seems illogical that <a href="http://us.php.net/date" rel="noreferrer">http://us.php.net/date</a> documents the microsecond specifier yet doesn't really support it:</p> <pre><code>function getTimestamp() { return date("Y-m-d\TH:i:s") . substr((string)microtime(), 1, 8); } </code></pre>
<p>date('u') is supported only from PHP 5.2. Your PHP may be older!</p>
20,453
<p>What is the best way to approach removing items from a collection in C#, once the item is known, but not it's index. This is one way to do it, but it seems inelegant at best.</p> <pre><code>//Remove the existing role assignment for the user. int cnt = 0; int assToDelete = 0; foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments) { if (spAssignment.Member.Name == shortName) { assToDelete = cnt; } cnt++; } workspace.RoleAssignments.Remove(assToDelete); </code></pre> <p>What I would really like to do is find the item to remove by property (in this case, name) without looping through the entire collection and using 2 additional variables.</p>
<p>If RoleAssignments is a <code>List&lt;T&gt;</code> you can use the following code.</p> <pre><code>workSpace.RoleAssignments.RemoveAll(x =&gt;x.Member.Name == shortName); </code></pre>
<p>There is another approach you can take depending on how you're using your collection. If you're downloading the assignments one time (e.g., when the app runs), you could translate the collection on the fly into a hashtable where:</p> <p>shortname => SPRoleAssignment</p> <p>If you do this, then when you want to remove an item by short name, all you need to do is remove the item from the hashtable by key.</p> <p>Unfortunately, if you're loading these SPRoleAssignments a lot, that obviously isn't going to be any more cost efficient in terms of time. The suggestions other people made about using Linq would be good if you're using a new version of the .NET Framework, but otherwise, you'll have to stick to the method you're using.</p>
25,377
<p>How can I create an empty one-dimensional string array?</p>
<p>Dim strEmpty(-1) As String</p>
<p>try this Dim Arraystr() as String ={}</p>
6,645
<p>I've observed printing PETG that the primary if not the only reason for using a high bed temperature seems to be preventing the bed from acting as a huge heat sink and rapidly cooling the initial layers such that they don't bond well to each other. In particulat, the heat is not needed for adhesion-to-the-bed purposes. This got me thinking whether there's a way we could get rid of the requirement, as a way to save time and all the energy spent heating the bed and cooling the room it's eventually dumped into.</p> <p>With that in mind, are there viable bed materials that are good thermal insulators? Just putting down a layer of any insulating material between the underlying bed and buildtak or whatever surface you want might work, but I would think these kinds of print surfaces are designed for moderate to high thermal conductivity themselves, and wouldn't be as bad a heat sink as the underlying metal, but might still sap a noticable amount of heat out of the part right away.</p>
<p>You can place a 2-4 mm thick MDF board on the bed and print directly on it, or you can place a 2 mm thick cork foil (IKEA office desk supplies) between magnetic plate and aluminium heater. The magnetic plate should not absorb too much heat and the cork will avoid conduction to the aluminium heater.</p> <p>If you want to avoid the magnetic plate, print on paper/cardboard on top of cork.</p>
<p>I’m pretty sure it can be brought separately but usually comes with a lot of heat-beds; It is a type of foam that has adhesive on one side and aluminum foil on the other. <a href="https://www.ebay.com.au/itm/3D-Printer-Parts-Heat-Insulation-Cotton-200-220-300mm-Foil-cotton-3D-printer-/193735774067?_trksid=p2349624.m46890.l49286" rel="nofollow noreferrer">Here</a> is an example of what I mean:</p> <p><a href="https://i.stack.imgur.com/R9Qw9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R9Qw9.jpg" alt="Bed insulation material" /></a></p>
1,945
<p>What I want to do is drawing a (large) terrain with OpenGL. So I have a set of vertices, lets say 256 x 256 which I store in a vertex buffer object in the VRAM. I properly triangulated them, so I've got an index buffer for the faces.</p> <pre><code>// vertexes glBindBufferARB(GL_ARRAY_BUFFER_ARB, vertexBufferId); glVertexPointer(3, GL_FLOAT, 0, 0); // textures glBindBufferARB(GL_ARRAY_BUFFER_ARB, texCoordBufferId); glTexCoordPointer(2, GL_FLOAT, 0, 0); // indexes glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, indexBufferId); // draw it glDrawRangeElements(GL11.TRIANGLES, 0, size - 1, size, GL_UNSIGNED_INT, 0); </code></pre> <p>I also loaded a square texture which has to be applied to each triangle. So I've got a problem with the texture coords:</p> <p>Each vertex is included in 4 triangles which means it needs 4 texture coords. But glDrawRangeElements() requires as much texture coords as vertexes.</p> <p>So I don't the see the way how to do this with the VBOs. Maybe there is better concept for solving my problem or I'm just lacking a good idea.</p> <p>Thanks in advance.</p>
<p>If your texture should repeat (or mirror) itself in each quad the best way would be to use texture coordinates that match the number of the (x, y) position in your array. E.g. for the first line of vertices use these texture coordinates: (0.0, 0.0), (1.0, 0.0), (2.0, 0.0)...(255.0, 0.0).</p>
<p>As you probably want your texture to seamlessly tile, all you need to is to compute the proper texture coordinate for each vertex and pass them just like the vertices. </p>
49,581
<p>I want to generate some XML in a stored procedure based on data in a table.</p> <p>The following insert allows me to add many nodes but they have to be hard-coded or use variables (sql:variable):</p> <pre><code>SET @MyXml.modify(' insert &lt;myNode&gt; {sql:variable("@MyVariable")} &lt;/myNode&gt; into (/root[1]) ') </code></pre> <p>So I could loop through each record in my table, put the values I need into variables and execute the above statement.</p> <p>But is there a way I can do this by just combining with a select statement and avoiding the loop?</p> <p><strong>Edit</strong> I have used <code>SELECT FOR XML</code> to do similar stuff before but I always find it hard to read when working with a hierarchy of data from multiple tables. I was hoping there would be something using the <code>modify</code> where the XML generated is more explicit and more controllable.</p>
<p>Have you tried <b>nesting</b> FOR XML PATH scalar valued functions? With the nesting technique, you can brake your SQL into very managable/readable elemental pieces</p> <p>Disclaimer: the following, while adapted from a working example, has not itself been literally tested</p> <p>Some reference links for the general audience</p> <ul> <li><a href="http://msdn2.microsoft.com/en-us/library/ms178107(SQL.90).aspx" rel="noreferrer">http://msdn2.microsoft.com/en-us/library/ms178107(SQL.90).aspx</a></li> <li><a href="http://msdn2.microsoft.com/en-us/library/ms189885(SQL.90).aspx" rel="noreferrer">http://msdn2.microsoft.com/en-us/library/ms189885(SQL.90).aspx</a></li> </ul> <p>The simplest, lowest level nested node example</p> <p>Consider the following invocation </p> <pre><code>DECLARE @NestedInput_SpecificDogNameId int SET @NestedInput_SpecificDogNameId = 99 SELECT [dbo].[udfGetLowestLevelNestedNode_SpecificDogName] (@NestedInput_SpecificDogNameId) </code></pre> <p>Let's say had udfGetLowestLevelNestedNode_SpecificDogName had been written without the FOR XML PATH clause, and for @NestedInput_SpecificDogName = 99 it returns the single rowset record: </p> <pre> @SpecificDogNameId DogName 99 Astro </pre> <p>But with the FOR XML PATH clause, </p> <pre><code>CREATE FUNCTION dbo.udfGetLowestLevelNestedNode_SpecificDogName ( @NestedInput_SpecificDogNameId ) RETURNS XML AS BEGIN -- Declare the return variable here DECLARE @ResultVar XML -- Add the T-SQL statements to compute the return value here SET @ResultVar = ( SELECT @SpecificDogNameId as "@SpecificDogNameId", t.DogName FROM tblDogs t FOR XML PATH('Dog') ) -- Return the result of the function RETURN @ResultVar END </code></pre> <p>the user-defined function produces the following XML (the @ signs causes the SpecificDogNameId field to be returned as an attribute) </p> <pre><code>&lt;Dog SpecificDogNameId=99&gt;Astro&lt;/Dog&gt; </code></pre> <p>Nesting User-defined Functions of XML Type </p> <p>User-defined functions such as the above udfGetLowestLevelNestedNode_SpecificDogName can be nested to provide a powerful method to produce complex XML. </p> <p>For example, the function </p> <pre><code>CREATE FUNCTION [dbo].[udfGetDogCollectionNode]() RETURNS XML AS BEGIN -- Declare the return variable here DECLARE @ResultVar XML -- Add the T-SQL statements to compute the return value here SET @ResultVar = ( SELECT [dbo].[udfGetLowestLevelNestedNode_SpecificDogName] (t.SpecificDogNameId) FROM tblDogs t FOR XML PATH('DogCollection') ELEMENTS ) -- Return the result of the function RETURN @ResultVar END </code></pre> <p>when invoked as </p> <pre><code>SELECT [dbo].[udfGetDogCollectionNode]() </code></pre> <p>might produce the complex XML node (given the appropriate underlying data)</p> <pre><code>&lt;DogCollection&gt; &lt;Dog SpecificDogNameId="88"&gt;Dino&lt;/Dog&gt; &lt;Dog SpecificDogNameId="99"&gt;Astro&lt;/Dog&gt; &lt;/DogCollection&gt; </code></pre> <p>From here, you could keep working upwards in the nested tree to build as complex an XML structure as you please</p> <pre><code>CREATE FUNCTION [dbo].[udfGetAnimalCollectionNode]() RETURNS XML AS BEGIN DECLARE @ResultVar XML SET @ResultVar = ( SELECT dbo.udfGetDogCollectionNode(), dbo.udfGetCatCollectionNode() FOR XML PATH('AnimalCollection'), ELEMENTS XSINIL ) RETURN @ResultVar END </code></pre> <p>when invoked as </p> <pre><code>SELECT [dbo].[udfGetAnimalCollectionNode]() </code></pre> <p>the udf might produce the more complex XML node (given the appropriate underlying data)</p> <pre><code>&lt;AnimalCollection&gt; &lt;DogCollection&gt; &lt;Dog SpecificDogNameId="88"&gt;Dino&lt;/Dog&gt; &lt;Dog SpecificDogNameId="99"&gt;Astro&lt;/Dog&gt; &lt;/DogCollection&gt; &lt;CatCollection&gt; &lt;Cat SpecificCatNameId="11"&gt;Sylvester&lt;/Cat&gt; &lt;Cat SpecificCatNameId="22"&gt;Tom&lt;/Cat&gt; &lt;Cat SpecificCatNameId="33"&gt;Felix&lt;/Cat&gt; &lt;/CatCollection&gt; &lt;/AnimalCollection&gt; </code></pre>
<p>Can you tell a bit more about what exactly you are planning to do. Is it simply generating XML data based on a content of the table or adding some data from the table to an existing xml structure?</p> <p>There are <a href="http://www.sqlservercentral.com/Authors/Articles/Jacob_Sebastian/212008/" rel="nofollow noreferrer">great series of articles</a> on the subject on XML in SQLServer written by Jacob Sebastian, it starts with the <a href="http://www.sqlservercentral.com/articles/SS2K5+-+XML/3022/" rel="nofollow noreferrer">basics of generating XML from the data in the table</a></p>
17,808
<p>So, my question is how do people get the word out that their website or blog exists? Do blogger invest in ads? Is is just through word of mouth? Or searching Google? I'm just curious how does a website build it's popularity. Do you just put your website up on the web and hope people find it? I know you can make your site SEO friendly, create sitemaps and such but what other techniques are used?</p> <p>Thanks, John</p>
<p>The big thing is, build a good site! have good quality relevant content. SEO and page linking will help. Most search traffic comes from Google imho. I would suggest <a href="http://www.google.com/webmasters/start" rel="noreferrer">http://www.google.com/webmasters/start</a> Submite a sitemap would be high on my todo list. Also Use relevant and unique - page titles, Friendly urls and relevant H1 tags</p> <p>Hope that helps</p>
<p><a href="http://news.ycombinator.com/item?id=341138" rel="nofollow noreferrer">This thread at Hacker News</a> is a good starting point.</p>
30,458